Quantcast
Channel: Live News for Yii Framework
Viewing all articles
Browse latest Browse all 2941

[extension] maks757/yii2-friendly-url

$
0
0

Friendly url

  1. Installation
  2. Usage
  3. Model
  4. Configuration
  5. View
  6. Action from Product Controller

Friendly url for your library or module

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist maks757/yii2-friendly-url "*"

or add

"maks757/yii2-friendly-url": "*"

to the require section of your composer.json file.

Usage

Model

// implements IUrlRules !!!
class ProductModel extends \yii\db\ActiveRecord implements maks757\friendly\components\IUrlRules
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'products';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //...
            // seo data
            [['seoUrl', 'seoTitle', 'seoDescription', 'seoKeywords'], 'string']
        ];
    }
    
    // Exemple: $key = 'my-first-product' -> return id
    /**
     * @param mixed $key
     * @return boolean|integer model id
     */
    public function fiendKey($key)
    {
        $model = ProductModel::findOne(['seoUrl' => $key]);
        return empty($model) ? false : $model->id;
    }

    // Exemple: $id = 10 -> return seoUrl
    /**
     * @param integer $id
     * @return string
     */
    public function seoUrl($id)
    {
        return ProductModel::findOne($id)->seoUrl;
    }
}

Configuration

'components' => [
    //...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            'news' => 'product/show',
            [
                    'class' => \maks757\friendly\UrlRules::className(),
                    'action' => 'product/show', // View 'product/show' or news
                    'controller_and_action' => 'product/show', // Action news show
                    //param: (action_key) - Action param get product id
                    //param: (url_key) - // View set product id
                    'routes' => [
                        ['model' => \common\models\ProductGroupModel::class, 'url_key' => 'group_id', 'action_key' => 'group',],
                        ['model' => \common\models\ProductModel::class, 'url_key' => 'product_id', 'action_key' => 'product',],
                    ]
                ],
        ],
    ],
    //...
],

View

<a href="Url::toRoute(['/product/show', 'group_id' => $group, 'product_id' => $product->id])">Go to product</a>

example url: https://tise/product/show/water/colla<br> water = group seo url
colla = product seo url

Action from Product Controller

public function actionShow($group, $product)
{
    //...
}

Viewing all articles
Browse latest Browse all 2941

Trending Articles