簡體   English   中英

Laravel 5.2中的動態請求綁定

[英]Dynamic request binding in Laravel 5.2

我想知道是否有可能根據特定領域進行動態綁定。

例:

通常,我們可能會將自定義請求注入到控制器中,例如: 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;
   }
}

當然,這是處理它的一種非常丑陋的方法,我不想這樣做。

有人知道其他方式嗎? 也許像服務綁定之類的東西。

提前致謝!

我找到了一種更好的方法。 我更改了接口的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;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM