When making a Laravel package, how do I register the service provider and alias of dependency packages?

对着背影说爱祢 提交于 2019-12-03 05:16:00

问题


I'm creating a package for Laravel and I've defined the Notification package (https://github.com/edvinaskrucas/notification) as a dependency for my package.

In /workbench/vendor/package/src/composer.json I have:

"require": {
    "php": ">=5.3.0",
    "illuminate/support": "4.1.*",
    "edvinaskrucas/notification": "2.*"
}

I'm then registering the service provider in my package's service provider's register method (not even sure if this is the right way to do this), and the alias using App::alias.

So in /workbench/vendor/package/src/Vendor/Package/PackageServiceProvider.php I have:

public function register()
{
    App::register('Krucas\Notification\NotificationServiceProvider');
    App::alias('Notification','Krucas\Notification\Facades\Notification');
}

But I'm still getting "Class 'Notification' not found" exception when attempting to use Notification::info() in a controller or Notification::showAll() in a view.

How do I properly register service providers for my package's dependencies?


回答1:


I had the same problem. I had a dependency in a package and didn't want to bother the user with these dependencies, for it was a dependency in a dependency. So this is the solution. Hope it will help you!

public function register()
{
    /*
     * Register the service provider for the dependency.
     */
    $this->app->register('LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider');
    /*
     * Create aliases for the dependency.
     */
    $loader = \Illuminate\Foundation\AliasLoader::getInstance();
    $loader->alias('AuthorizationServer', 'LucaDegasperi\OAuth2Server\Facades\AuthorizationServerFacade');
    $loader->alias('ResourceServer', 'LucaDegasperi\OAuth2Server\Facades\ResourceServerFacade');
}



回答2:


You can use the alias() method on the app to register an alias, but I would consider having your package users register aliases and service providers themselves in the install process. It's a good way of keeping track of the external code that you're using, and a nice way of pulling components out to test things.

Personal opinion of course. :)

Dayle




回答3:


During package development you should add your package service provider in composer.json file as in the code below. For additional information please consult at Laravel's Package Discovery.

"extra": {
    "laravel": {
        "providers": [
            "Barryvdh\\Debugbar\\ServiceProvider"
        ],
        "aliases": {
            "Debugbar": "Barryvdh\\Debugbar\\Facade"
        }
    }
},


来源:https://stackoverflow.com/questions/21574413/when-making-a-laravel-package-how-do-i-register-the-service-provider-and-alias

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!