Laravel 5.2

时间:2016-04-23 20:16:09

标签: php laravel dependency-injection

我想知道是否可以根据特定字段进行动态绑定。

示例:

通常,我们可能会向控制器注入一个自定义请求,例如:App\Http\Requests\CustomRequest

但是,我需要根据输入字段实例化另一个请求,例如:

public function someAction(Request $request)
{
   switch($request->input('flag_field')) {
      case 'custom_request_1':
          // find some way to have the CustomRequest1 instance
          break;
      case 'custom_request_2':
          // find some way to have the CustomRequest2 instance
          break;
   }
}

当然,处理它是一种非常难看的方式,我不想这样做。

有没有人知道其他方式?也许像服务绑定之类的东西。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我找到了一个更好的方法来实现它。我更改了接口(Request)的RequestInterface类,并将其绑定在AppServiceProvider寄存器方法中。

控制器类:

public function someAction(RequestInterface $request)
{
}

提供者类:

public function register()
{
    $this->app->bind(RequestInterface::class, function ($app) {
        switch ($app->make('request')->input('flag_field')) {
                case 'custom_request_1':
                    return $app->make(CustomRequest1::class);
                    break;
                case 'custom_request_2':
                    return $app->make(CustomRequest2::class);
                    break;
    });
}