Yii2 routing when using CamelCase action names

前端 未结 2 508
悲哀的现实
悲哀的现实 2020-12-10 13:09

If you have say the following controller structure



        
相关标签:
2条回答
  • 2020-12-10 13:12

    You can make your own Basecontroller and overwrite createAction with a pattern allow uppercase like

    preg_match('/^[a-zA-Z0-9\\-_]

     public function createAction($id)
    {
        if ($id === '') {
            $id = $this->defaultAction;
        }
    
        $actionMap = $this->actions();
        if (isset($actionMap[$id])) {
            return Yii::createObject($actionMap[$id], [$id, $this]);
        } elseif (preg_match('/^[a-zA-Z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
            $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
            if (method_exists($this, $methodName)) {
                $method = new \ReflectionMethod($this, $methodName);
                if ($method->isPublic() && $method->getName() === $methodName) {
                    return new InlineAction($id, $this, $methodName);
                }
            }
        }
    
        return null;
    }
    
    0 讨论(0)
  • 2020-12-10 13:35

    I was thrown a little about this change too, but eventually I found it makes the URL easier to read. I was unsure about having a case sensitive route in Yii1, in Yii2 I do not have this problem (or impression of a problem) anymore.

    I am not sure about the exact reason, but I can tell you that for SEO it is better to have - separating words instead of having 1 big word.

    When I rewrote an application in yii2, I put in the url manager all the old routes that i need to maintain.

            'urlManager' => [
                'class' => 'yii\web\UrlManager',
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => [
    .................................................
                    'site/registerInterest' => 'site/register-interest',
    .................................................
    
                ],
            ],
    

    So my old links work now just fine. You can also put a 301 redirect in .htaccess if you want from the old routes to the new ones to keep the SEO juice.

    0 讨论(0)
提交回复
热议问题