Laravel 5、检查类是否在容器中注册
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28529297/
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
Laravel 5, check if class is registered in the container
提问by Silvio Sosio
Is there any way to check if a class exists in Laravel 5?
有没有办法检查 Laravel 5 中是否存在类?
I had this solution for Laravel 4: try to make a specific class, and if I get a ReflectionException
, I use a generic class.
In Laravel 5 looks like I can't intercept the ReflectionException
and I get a "Whoops".
我为 Laravel 4 提供了这个解决方案:尝试创建一个特定的类,如果我得到一个ReflectionException
,我就使用一个泛型类。
在 Laravel 5 中,我似乎无法拦截ReflectionException
并且收到“哎呀”。
I was wondering if there is some better way to do this.
我想知道是否有更好的方法来做到这一点。
try {
$widgetObject = \App::make($widget_class);
} catch (ReflectionException $e) {
$widgetObject = \App::make('WidgetController');
$widgetObject->widget($widget);
}
回答by lukasgeiter
Why don't you just use the PHP function class_exists
?
为什么不直接使用 PHP 函数class_exists
?
if(class_exists($widget_class)){
// class exists
}
回答by Aderemi Dayo
Check whether your class is set in bindings by doing
通过执行检查您的类是否设置在绑定中
app()->bound($classname);
回答by Alexander Konotop
\App::bound()
might be the proper way.
\App::bound()
可能是正确的方法。
Latest laravel versions (Maybe >= 5.3, I don't know exactly) register service providers in alittle different way by default.
默认情况下,最新的 Laravel 版本(也许 >= 5.3,我不知道确切)以稍微不同的方式注册服务提供者。
For example, a new way of registering:
例如,一种新的注册方式:
$this->app->singleton(MyNamespace\MyClass::class, function()
{
/* do smth */ }
);
instead of the old one:
而不是旧的:
$this->app->singleton('MyClassOrAnyConvenientName', function()
{
/* do smth */ }
);
As a result we should use App::make('\MyNamespace\MyClass')
instead of App::make('MyClassOrAnyConvenientName')
to resolve a service.
因此,我们应该使用App::make('\MyNamespace\MyClass')
而不是App::make('MyClassOrAnyConvenientName')
来解析服务。
We maintain a library which has to support both versions. So we use \App::bound()
to determine whether old or new format of service name is registered in container. class_exists()
did actually work for newer laravel but didn't work as expected for older ones because in old systems we didn't have a properly named Facade
for that service (Facade's name differed from registered service name) and class_exists()
returned false
.
我们维护一个必须支持两个版本的库。所以我们\App::bound()
用来判断容器中注册的是旧格式还是新格式的服务名。class_exists()
实际上确实适用于较新的 Laravel,但对于较旧的 Laravel 没有按预期工作,因为在旧系统中,我们没有Facade
为该服务正确命名(Facade 的名称与注册的服务名称不同)并class_exists()
返回false
.