如何在post方法控制器laravel中输入提示/注入两个不同的类?

时间:2018-03-14 09:30:17

标签: laravel

<?php
namespace App\Http\Controllers;

use Psr\Http\Message\ServerRequestInterface;
use Illuminate\Http\Request;

class BuyerController
{
   public function saveBuyer(Request $request,ServerRequestInterface $request )
   {
        //this is POST request controller (trying to inject 2 classes , is this possible?)
   }
}

是否可能或者为post方法控制器laravel注入两个不同的类,即Request和ServerRequestInterface?

1 个答案:

答案 0 :(得分:1)

use Illuminate\Http\Request;
use Psr\Http\Message\ServerRequestInterface;

class BuyerController
{
     protected $serverRequest; // this attribute will use for injected by ServerRequestInterface Class

     public function __construct(ServerRequestInterface $serverRequest)
     {
         $this->serverRequest = $serverRequest; //injecting ServerRequestInterface to this attribute 
     }

     public function saveBuyer(Request $request)
     {
        // $this->serverRequest (injected by ServerRequestInterface Class) 
        // $request (injected by Request Class)
        // now can use $this->serverRequest (for ServerRequestInterface Class) and $request (for Request Class)
        dd($this->serverRequest,$request);
     }
}

您只能在函数中注入Request类和模态类。还有一种方法可以在控制器中注入类和接口。

将您的ServerRequestInterface $request移至__contruct()