Laravel 5, check if the class is registered in the container

Is there a 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, it looks like I cannot catch a ReflectionException , and I get "Oops."

I was wondering if there is a better way to do this.

 try { $widgetObject = \App::make($widget_class); } catch (ReflectionException $e) { $widgetObject = \App::make('WidgetController'); $widgetObject->widget($widget); } 
+5
source share
3 answers

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

 if(class_exists($widget_class)){ // class exists } 
+4
source

\App::bound() may be correct.

Recent versions of laravel (maybe> = 5.3, I don’t know for sure) register service providers differently by default.

For example, a new registration method:

 $this->app->singleton(MyNamespace\MyClass::class, function() { /* do smth */ } ); 

instead of the old:

 $this->app->singleton('MyClassOrAnyConvenientName', function() { /* do smth */ } ); 

As a result, we should use App::make('\MyNamespace\MyClass') instead of App::make('MyClassOrAnyConvenientName') to solve the service.

We support a library that should support both versions. Therefore, we use \App::bound() to determine if the old or new service name format is registered in the container. class_exists() did work for the new laravel, but did not work as expected for the older ones, because on older systems we did not properly name Facade for this service (the facade name is different from the registered service name) and class_exists() returned false .

+1
source

Use the getProvider method in the Application container:

 if (app()->getProvider($classname)) { // Do what you want when it exists. } 

It is available from version 5.0 and can be viewed here .

+1
source

Source: https://habr.com/ru/post/1213423/


All Articles