使用视图合成器自动用数据填充视图:
首先为任何URI 创建一个路由模式,例如user/13 或user/15 像这样(在routes.php 文件中):
// Composers will be used only for this url pattern, i.e. "user/13" or "user/15"
Route::when('user/*', 'prepareView');
然后像这样创建prepareView 过滤器:
Route::filter('prepareView', function($route, $request) {
// Register your three view composers
View::composers(array(
// Call the "postsViewComposer" method from
// ViewComposers for "posts.show" view
'ViewComposers@postsViewComposer' => 'posts.show',
// Call the "videsViewComposer" method from
// ViewComposers for "videos.show" view
'ViewComposers@videsViewComposer' => 'videos.show',
// Call the "itemsViewComposer" method from
// ViewComposers for "items.show" view
'ViewComposers@itemsViewComposer' => 'items.show',
));
});
然后在app/viewcomposers文件夹中创建ViewComposers类:
class ViewComposers {
public function postsViewComposer($view)
{
// Get user id, for example, 15
$id = Route::current()->parameter('id');
// Then use it to retrieve the model
$author = User::find($id);
return $view->with('author', $author);
}
public function videsViewComposer($view)
{
// Logic for this view composer
}
public function itemsViewComposer($view)
{
// Logic for this view composer
}
}
最后,您需要在composer.json 文件中的autoload->classmap 中添加新的class,例如:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
// ...
"app/viewcomposers"
]
最后,只需从项目根目录中的command prompt/terminal 运行composer dump-autoload。而已。现在,每当请求具有任何id 的任何用户的URI 时,那些view composers 将运行以准备视图。