简体   繁体   中英

Laravel 5.2.x test if vendor exists

Which is the best way to check if a vendor exists in our Laravel project?

My solution:

$foo = 'Foo\Foo';

if (class_exists($foo)) {  
    // class exists
}

Is there a better solution? A Laravel method that I don't know?

Thanks!

That's the right way of doing, there's no function in Laravel for that.

But the most correct way would be checking the existence of the class using the full namespace, something like:

$foo = 'Symfony\Component\HttpFoundation\Request';
if (class_exists($foo)) {
    // class exists
}

I don't really think there's a truly best way - that is to say that there's no nice API for it that I know of.

However, using non-Laravel ways, you can either inspect the Composer installed.json file (which I have done in the past, located at vendor/composer/installed.json ) or, as you say, class existence detection.

Using a Laravel way, if you know the 3rd-party library is specifically a Laravel one with a service provider or otherwise registers something in the IoC container, you can check there - either look at config('app.providers') to see if it contains the service provider class you expect, or see if app('the.binding.name') returns something you expect (or use $app->bound('the.binding.name') maybe).

Even better, if it's a driver, for example a DB engine, you could query the DB manager to see if the driver is registered. That's probably your best way, but does rather depend on the 3rd-party library you want to detect.

I think that you should try it in laravel's way using the app container like this:

try {
    app($foo);
} catch (\ReflectionException $e) {
    // here you know that class dosen't exists
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM