Reputation: 1435
I have added a custom Service Provider to a Laravel app and the service provider runs well. However, Artisan gets an error now. When I remove the service provider the error goes away ( no errors when the Service Provider runs in normal mode ). In this case the error is related to the DB Drivers not being loaded. "Driver not found" errors.
Apparently, when running in Artisan mode it still loads all of the Service Providers even though some of the dependancies like DB Drivers, and other dependencies, aren't loaded.
Does anyone know of a way around this? Forcing the dependencies to load or to prevent the offending Service Providers to not load in Artisan mode? Possibly conditional loading of Service Providers would work if I can find a way to detect its running in Artisan CLI mode.
In case it helps here's where/how the Service Provider is registered:
public function register()
{
$this->app->singleton(Locations::class, function ($app) {
return new Locations($app->request);
});
}
Error Message:
could not find driver (SQL: select * from...
Apparently the offending custom service provider is loading and running before the DB driver resources are loaded and available in Artisan CLI mode - not having this problem in normal browser mode. Either that or Artisan doesn't load the DB drivers at all in CLI mode.
Any feedback would be appreciated.
Thanks in advance.
Upvotes: 1
Views: 1206
Reputation: 180124
I believe you're going to want to consult the difference between boot
and register
:
As mentioned previously, within the
register
method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method. Otherwise, you may accidentally use a service that is provided by a service provider which has not loaded yet.
Whereas the boot
method:
This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework:
Your return new Locations($app->request);
presumably makes database calls, but the database service provider is not necessarily ready to go in the register
function. In the boot
function, initialize your previously registered singleton with the data you want.
Upvotes: 1
Reputation: 1435
This worked:
if (\App::runningInConsole()){...
In this case I placed it in the __construct() of the class to return null before it ran bc placing it in the Service Provider file created other unexpected issues. Not elegant but it works seamlessly.
Thank you to @apokryfos for the suggestion on the runningInConsole()
function. Wasn't aware of that one.
If I find other options I'll post them here. Still digging into custom Service Providers more. A very powerful feature of Laravel that I'm just getting into.
Upvotes: 2