检查类是否是 Laravel 5 中的模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40766734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a class is a Model in Laravel 5
提问by g4b0
I have this code in Laravel 5.2 that checks if a given db table name ($what) has its own Model :
我在 Laravel 5.2 中有这段代码,用于检查给定的 db 表名($what)是否有自己的 Model :
public function manage($what) {
$model = Str::studly(Str::singular($what));
if (!is_subclass_of($model, 'Model')) {
\App::abort(404);
}
/* [... other stuff ...] */
}
The problem is that is_subclass_of always fail, also when the model exist and it's a subclass of Model. I suppose it's a namespace problem, how can I fix it?
问题是 is_subclass_of 总是失败,当模型存在并且它是模型的子类时也是如此。我想这是一个命名空间问题,我该如何解决?
回答by Alexey Mezenin
You can check if your object is an instance of a model with instanceof
:
您可以使用以下命令检查您的对象是否是模型的实例instanceof
:
$article = new \App\Article();
if ($article instanceof \Illuminate\Database\Eloquent\Model) {
回答by aynber
You may need the full namespace. When I do get_parent_class()
on one of my models, it returns Illuminate\Database\Eloquent\Model
. So use this instead:
您可能需要完整的命名空间。当我在我的get_parent_class()
一个模型上做时,它返回Illuminate\Database\Eloquent\Model
. 所以改用这个:
$model = 'App\' . Str::studly(Str::singular($what));
if (!is_subclass_of($model, 'Illuminate\Database\Eloquent\Model')) {