[英]Laravel 4: Inject view model into Controller
我剛剛開始學習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
不起作用嗎? 以及如何解決這個問題?
UserController:
注意:我注釋了無效的行並拋出了錯誤,如$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中的每個立面都有一些注釋,說明如果要注入它,應該使用什么類。 例如:
/**
* @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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.