Is there any way to check if a class exists in 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".
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);
}
Check whether your class is set in bindings by doing
app()->bound($classname);
Use the getProvider method on the Application container:
if (app()->getProvider($classname)) {
// Do what you want when it exists.
}
It's been available since 5.0 and can be viewed here.
Why don't you just use the PHP function class_exists
?
if(class_exists($widget_class)){
// class exists
}
\App::bound()
might be the proper way.
Latest laravel versions (Maybe >= 5.3, I don't know exactly) register service providers in alittle different way by default.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With