我刚刚开始学习Laravel,并从Laracast的基础知识开始。在第13集中,它展示了如何使用构造函数将User
模型注入到UserController
中。
但是,当我尝试使用相同的技术注入View
和Input
模型时,我遇到了一些错误,比如:
Symfony ' Component ' Debug ' Exception ' FatalErrorException (E_ERROR)
Call to undefined method Illuminate'Support'Facades'View::make()
Symfony ' Component ' Debug ' Exception ' FatalErrorException (E_ERROR)
Call to undefined method Illuminate'Support'Facades'Input::all()
当我注入Redirect
模型时,它就像User
模型一样工作。有人能解释一下View
和Input
为什么不起作用吗?如何解决这个问题?
用户控制器:
注意:我评论了不起作用的行,并抛出了错误,比如$this->view->make();
class UserController extends 'BaseController {
protected $user, $redirect, $view, $input;
public function __construct(User $user, Redirect $redirect, View $view, Input $input)
{
$this->user = $user;
$this->redirect = $redirect;
$this->view = $view;
$this->input = $input;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$users = $this->user->all();
return View::make('users.index', ['users' => $users]);
// TODO: Why does below not work?
// return $this->view->make('users.index', ['users' => $users]);
}
/**
* Show the form for creating a net
* @return Response
*/
public function create()
{
return View::make('users.create');
// TODO: Why does below not work?
// return $this->view->make('users.create');
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$input = Input::all();
// TODO: Why does below not work?
// $input = $this->input->all();
if ( ! $this->user->fill($input)->isValid() )
{
return $this->redirect->back()->withInput()->withErrors($this->user->errors);
}
$this->user->save();
return $this->redirect->route('users.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$user = $this->user->find($id);
return View::make('users.show', ['user' => $user]);
// TODO: Why does below not work?
// return $this->view->make('users.show', ['user' => $user]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
}
因为您无法将Laravel外观注入控制器。Laravel中的每个facade都有一些关于如果你想注入它,应该使用什么类的注释。例如:
/**
* @see 'Illuminate'View'Factory
*/
class View extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'view'; }
}
正如您所看到的,有一个附件@see
,它让您知道,如果您想将它注入控制器,您应该使用Illuminate'View'Factory
。