Search code examples
phpurlyii2yii2-basic-app

Yii2. Apply Custom URL rule class


I have created a custom URL rule and want to put some logic there, but parseRequest and createUrl methods are not executing.

<?php
namespace app\components;

use yii\base\Object;
use yii\web\UrlRuleInterface;

/**
 * {@inheritDoc}
 */
class CustomUrlRule extends Object implements UrlRuleInterface
{
    /**
     * {@inheritDoc}
     */
    public function createUrl($manager, $route, $params)
    {
        echo __METHOD__;
        die();
    }

    /**
     * {@inheritDoc}
     * @throws \yii\base\InvalidConfigException
     */
    public function parseRequest($manager, $request)
    {
        echo __METHOD__;
        die();
    }
}

And then write it in UrlManager $rules

    'enablePrettyUrl'     => true,
    'showScriptName'      => false,
    'enableStrictParsing' => true,
    'rules'               => [
        'class'   => 'app\components\CustomUrlRule',
    //other rules...

]

But the code is not executing. I can still a page of my app. How to apply my useless CustomUrlRule?


Solution

  • Proper UrlManager example configuration is:

    'rules' => [
        ['class' => 'MyUrlRule', 'pattern' => '...', 'route' => 'site/index', ...],
        // ...
    ]
    

    You need to wrap this in another array.

    Edit: You don't have to extend yii\web\UrlRule instead of yii\base\Object as I posted before, just proper interface is required.