排序/每页逻辑在基于 Yii2 的应用程序中属于什么位置


Where does the sorting/per-page logic belong in Yii2 based application?

我在 Yii2 中有一个控制器,它将产品目录显示为产品列表。产品目录具有一个控件(选择),用于设置排序(受欢迎程度、价格等)和每页条目(12、24 等)。

有几条逻辑,我试图将它们放在正确的层中:

    可能的
  1. 排序列列表和可能的每页值列表
  2. 默认
  3. 排序列和默认每页值
  4. 从请求中获取参数(即 $_GET['sort']),如果请求为空,则回退到默认值

在 Yii2 中实际上有一个 View 对象,所以也许其中一些需要进入它?

在 Yii2 中,ModelNameSearch.php 负责处理这个问题。这就是我设置这一切的方式(不完全是,但这是简单的版本):

在控制器中

/**
 * Sets the pagination for the list
 * @return mixed
 */
public function actionPagination()
{
    TagSearch::setPerPage(Yii::$app->request->queryParams['records']);
    $this->redirect(['index']);
}

在标签搜索中

    public function setPerPage($recordPerPage)
    {
        Yii::$app->session->set(self::className() . 'Pagination', $recordPerPage);
    }
    public function getPerPage()
    {
        return Yii::$app->session->get(self::className() . 'Pagination', 25),
    }
.....................
    public function search($params)
    {
..............................
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => self::getPerPage()
            ],
        ]);
......................
}

在视图中,请随意做一个

<?= Html::dropDownList('pagination', TagSearch::getPerPage(), ['10' => '10 per page', '25' => '25 per page', '50' => '50 per page', '100' => '100 per page'], ['class' => "form-control input-sm pagination", 'data-change'=> Url::toRoute('pagination')]) ?>

并添加一个

$('select.pagination').on('change', function() {
    document.location.href = $(this).attr('data-change') + '?records=' + $(this).val();
});

我需要自己查看变量的命名,上面的代码中可能存在错误(我写的是复制粘贴和更改的),但你明白了。