【问题标题】:dependency injection in lumen流明中的依赖注入
【发布时间】:2020-01-20 00:53:04
【问题描述】:

我正在尝试理解 lumen 中的依赖注入

我要添加用户服务

{
    protected $userService;
    public function __construct(UserService $userService, $config)
    {
        $this->userService = $userService;
    }

在这里应用它: 控制台/命令/Command2.php

    $server = app(Server::class, [$config]);

遇到错误

在 Container.php 第 993 行: 类 App\SocketServer\Server 中无法解析的依赖解析 [Parameter #1 [ $config ]]

【问题讨论】:

    标签: php dependency-injection lumen


    【解决方案1】:

    可以在服务提供者中配置带参数的依赖关系。可以通过运行生成一个服务提供者:

    php artisan make:provider UserServiceProvider
    

    修改UserServiceProvider.php文件中的设置方法

        public function register()
        {
            $this->app->singleton(UserService::class, function ($app) {
                $config = ['debug' => true];
                return new UserService($config);
            });
        }
    

    config/app.php注册:

    'providers' => [
        // Other Service Providers
    
        App\Providers\UserServiceProvider::class,
    ],
    

    然后 Laravel 就可以注入依赖了:

        protected $userService;
        public function __construct(UserService $userService)
        {
            $this->userService = $userService;
        }
    

    【讨论】:

    • 它的流明,朋友.. 下一刻 - 我的 UserService 没有 __construct 功能,所以我怀疑 UserService($config) 工作正常......
    • 这也适用于流明lumen.laravel.com/docs/6.x/providers :) @Dimas
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2014-06-12
    相关资源
    最近更新 更多