【问题标题】:How to use dependency injection with routes in laravel如何在 laravel 中对路由使用依赖注入
【发布时间】:2020-04-01 18:34:00
【问题描述】:

如何配置路由实例(Illuminate/Support/Facades/Route.php)通过DI使用已经注册的服务?

例如我注册我的单身:

$this->app->singleton('api_controller', function ($app) {
    return new Controller('config_value');
});

还有控制器本身:

class ApiController extends Controller
{
   private $configValue;

   public function __construct(string $configValue)
   {
      $this->configValue = $configValue;
   }

   public function getConfigValue()
   {
       return $this->configValue;
   }
}

然后声明路由:

Route::get('config-value', 'ApiController@getConfigValue')->name('getConfigValue');

但是在调用 API 之后,Route 会启动新的 ApiController 实例,而不是我声明为单例的实例,因此不会将 config_value 传递给控制器​​。是否可以配置Route实例?

尝试了应用实例的替代路由,但似乎没有找到 api_controller 服务:

Route::get('config-value', function () { return app('api_controller')->getConfigValue(); })->name('getConfigValue');

In Container.php line 752:

  Class api_controller does not exist

【问题讨论】:

    标签: laravel laravel-5 dependency-injection routes


    【解决方案1】:

    似乎实现这一点的唯一方法是使用自动连接(而不是通过自定义服务 ID 声明,这会限制您进行多实例配置)。它还需要明确的defer false 才能覆盖新实例。

    protected $defer = false;
    $this->app->singleton(Controller::class, function ($app) {
        return new Controller('config_value');
    });
    

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多