如何自动将帖子的类别添加到网址?

时间:2017-03-26 15:21:04

标签: php yii yii2 url-routing

在Yii2中我有博客文章,每个都有1个类别。规则如此:

'rules' => [
    '<category_slug>/<article_slug>' => 'article/view',
],

控制器:

public function actionView($category_slug, $article_slug)
{
    ...
}

类别存储在params.php

<?php
return [
    'categories' => [
        [
            'id' => 1,
            'name' => 'First category',
            'slug' => 'first_category',
        ],
        ...
    ],
];

Url to article:

Url::to(['article/view', 'category_slug' => $model->category_slug, 'article_slug' => $model->article_slug])

问题:是否可以将类别slug自动添加到Url::to?我的意思是,您只需要使用Url::to参数创建article_slug。我想最好的解决办法是以某种方式更改网址规则,但具体如何?

'rules' => [
    '<Yii::$app->MyFunction->GetCategorySlugByArcticleId(..)>/<article_slug>' => 'article/view',
],

1 个答案:

答案 0 :(得分:0)

这应该很简单。

选项一:扩展Url-Helper

只需按以下方式扩展Url-Helper

class MyUrl extends \yii\helpers\Url
{

    //extending regular `to`-method
    public static function to($url = '', $scheme = false)
    {
        //check if url needs completion and meets preconditions
        if (is_array($url) && strcasecmp($url[0], 'article/view') === 0 && isset($url['article_slug']) && !isset($url['category_slug'])) {
            //add category slug if missing...assuming you have a relation from article to category and category having a property `slug`
            $url['category_slug'] = $article->category->slug;
        }

        return parent::to($url, $scheme);
    }

    //...or custom method for your case which is even more convenient
    public static function toArticle($article, $scheme=false)
    {
        //article could be an article model itself or an id
        $articleModel = $article instanceof Article ? $article : Article::findOne($article);
        return parent::to([
            'article/view',
            'article_slug'=>$articleModel->slug,
            'category_slug'=>$articleModel->category->slug,
        ], $scheme);
    }

}

现在你所要做的就是使用那个类而不是常规的Url - 助手!

选项二:在文章模型中添加方法

只需添加如下方法:

class Article extends \yii\db\ActiveRecord
{
    //...

    public function link($scheme=false)
    {
        return Url::to([
            'article/view',
            'article_slug'=>$this->slug,
            'category_slug'=>$this->category->slug,
        ], $scheme);
    }

    //...
}

如果您需要更多信息,请告诉我们!