Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5, check if class is registered in the container

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);
}
like image 440
Silvio Sosio Avatar asked Feb 15 '15 18:02

Silvio Sosio


4 Answers

Check whether your class is set in bindings by doing

app()->bound($classname);
like image 119
Aderemi Dayo Avatar answered Nov 20 '22 07:11

Aderemi Dayo


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.

like image 38
Jamie Holly Avatar answered Sep 23 '22 12:09

Jamie Holly


Why don't you just use the PHP function class_exists?

if(class_exists($widget_class)){
    // class exists
}
like image 9
lukasgeiter Avatar answered Nov 20 '22 09:11

lukasgeiter


\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.

like image 4
Alexander Konotop Avatar answered Nov 20 '22 07:11

Alexander Konotop