【问题标题】:Laravel constructor and method injectionLaravel 构造函数和方法注入
【发布时间】:2019-08-03 10:48:22
【问题描述】:

我在为控制器中的构造函数和方法设置注入时遇到问题。

我需要实现的是能够设置一个全局控制器变量,而无需在控制器方法上注入相同的变量。

从下面的路线;

Route::group(['prefix' => 'test/{five}'], function(){
    Route::get('/index/{admin}', 'TestController@index');
});

我希望构造函数接收这五个,而管理员可以使用该方法。 下面是我的控制器;

class TestController extends Controller
{
    private $five;

    public function __construct(PrimaryFive $five, Request $request)
    {
        $this->five = $five;
    }

    public function index(Admin $admin, Request $request)
    {
        dd($request->segments(), $admin);
        return 'We are here: ';
    }
...

当我运行我正在考虑使用的上述内容时,我在 index 方法上遇到错误:

Symfony\Component\Debug\Exception\FatalThrowableError 抛出消息“传递给 App\Http\Controllers\TestController::index() 的参数 1 必须是 App\Models\Admin 的实例,给定字符串”

以下工作,但我不需要在该方法中注入 PrimaryFive。

class TestController extends Controller
{
    private $five;

    public function __construct(PrimaryFive $five, Request $request)
    {
        $this->five = $five;
    }

    public function index(PrimaryFive $five, Admin $admin, Request $request)
    {
        dd($request->segments(), $five, $admin);
        return 'We are here: ';
    }
...

有没有一种方法可以使用模型设置构造函数注入(有效)并设置方法注入,而无需在构造函数中注入模型集?

【问题讨论】:

  • 这只是针对这个控制器还是您想要将它添加到更多/所有控制器中?

标签: php laravel laravel-5


【解决方案1】:

您可以这样做的一种方法是使用controller middleware

public function __construct()
{
    $this->middleware(function (Request $request, $next) {

        $this->five = PrimaryFive::findOrFail($request->route('five'));

        $request->route()->forgetParameter('five');

        return $next($request);
    });
}

以上假设PrimaryFive是一个Eloquent模型。

这意味着为控制器设置了$this->five,但是,由于我们使用的是forgetParameter(),它将不再传递给您的控制器方法。


如果您专门使用Route::model() or Route::bind() 来解析您的five 段,那么您可以直接从$request->route('five') 检索实例,即:

$this->five = $request->route('five');

【讨论】:

    【解决方案2】:

    错误是因为您无法通过路线传递模型。它应该是 /index/abc/index/123 之类的东西。

    你可以使用下面的索引函数

    public function index($admin,Request $request){}
    

    【讨论】:

      【解决方案3】:

      这肯定会对你有所帮助。

      Route::group(['prefix' => 'test/{five}'], function () {
          Route::get('/index/{admin}', function ($five, $admin) {
              $app = app();
              $ctr = $app->make('\App\Http\Controllers\TestController');
              return $ctr->callAction("index", [$admin]);
          });
      });
      

      另一种从路由调用控制器的方法。您可以控制要从路由传递到控制器的内容

      【讨论】:

        猜你喜欢
        • 2016-08-11
        • 1970-01-01
        • 2015-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 2011-04-02
        • 2018-11-25
        相关资源
        最近更新 更多