【发布时间】: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: ';
}
...
有没有一种方法可以使用模型设置构造函数注入(有效)并设置方法注入,而无需在构造函数中注入模型集?
【问题讨论】:
-
这只是针对这个控制器还是您想要将它添加到更多/所有控制器中?