【发布时间】:2015-01-16 00:37:32
【问题描述】:
我正在构建一个电视节目 netflix-esque 项目,其中有一个 Shows 页面,我想按格式过滤该页面。每个节目都包含可以有电视、dvd 和 bd 格式的剧集。
目前我正在使用扩展基础 ShowsController 的单独路由和控制器进行过滤。
Route::get('shows/view/{type}', ['as' => 'shows.viewtype', 'uses' => 'ShowsController@viewType',]);
Route::get('shows/bluray',['as' => 'shows.bluray','uses' => 'ShowsBlurayController@index']);
Route::get('shows/dvd',['as' => 'shows.dvd','uses' => 'ShowsDVDController@index']);
Route::get('shows/tv',['as' => 'shows.tv','uses' => 'ShowsTVController@index']);
格式控制器之一的示例
class ShowsBlurayController extends ShowsController
{
public function index()
{
// Set user state for browsing bluray
Session::push('user.showtype', 'bluray');
$shows = $this->show->getBlurayPaginated(16);
return $this->getIndexView(compact('shows'));
}
}
我使用getIndexView() 方法(在ShowsController 中)来确定2 个可用视图之一:poster 和list。
public function getIndexView($shows)
{
$viewType = get_session_or_cookie('show_viewtype', 'list');
if ($viewType == 'posters') {
return View::make('shows.index', $shows)
->nest('showsView', 'shows.partials.posters', $shows);
} else {
return View::make('shows.index', $shows)
->nest('showsView', 'shows.partials.list', $shows);
}
}
节目是根据剧集过滤的:
public function getBlurayPaginated($perPage)
{
return $this->getByFormat('BD')->with('tagged')->paginate($perPage);
}
private function getByFormat($format)
{
return $this->show->whereHas('episodes', function ($q) use ($format) {
$q->whereHas('format', function ($q) use ($format) {
$q->where('format', '=', $format);
});
});
}
问题是我想以一种干净的方式做到这一点。当用户选择一种格式时,将应用该过滤器。目前所有这些都分散在控制器中,不太有意义。
我也想过在routes.php做这样的事情:
Route::get('shows/format/{format}',['as' => 'shows.format','uses' => 'ShowsController@index']);
然后处理索引中的过滤,但这似乎也是一个奇怪的地方。
这种方法确实有效,但我不想以后用它搞砸自己。我正在计划一个简单的搜索,应该将过滤器考虑在内。
换句话说,我如何组织代码以使从数据库中获取数据时会考虑已设置的过滤器? (可能是会话状态?)
【问题讨论】:
-
你能再澄清一点吗?有没有报错?
-
@MD.AtiqurRahman 没有错误。它工作正常,只是不可扩展且不干燥
-
看看下面的答案,希望能解决你的问题。