PHP code example of maks757 / yii2-friendly-url

1. Go to this page and download the library: Download maks757/yii2-friendly-url library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

maks757 / yii2-friendly-url example snippets


// 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;
    }
}

'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',],
                    ]
                ],
        ],
    ],
    //...
],

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

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

php composer.phar