yii2 控制器里 action 大小寫組合造成的路由問題


yii1中, 若存在如下控制器

class BindController extends CController {

    public function actionGetMobilePhone () {
        // some code...
    }

}

那么, 通過訪問 http://your-domain-name/bind/getMobilePhone  就可以訪問到

以上代碼如果在yii2中, 訪問的時候, 就需要 http://your-domain-name/bind/get-mobile-phone 通過這種方式來訪問, 因為yii2中改寫了 createAction 方法

yii1中的 createAction 

    public function createAction($actionID)
    {
        if($actionID==='')
            $actionID=$this->defaultAction;
        if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
            return new CInlineAction($this,$actionID);
        else
        {
            $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
            if($action!==null && !method_exists($action,'run'))
                throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
            return $action;
        }
    }

yii2中的 createAction

    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-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $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;
    }

紅色的注釋就是yii1 與 yii2 中組合方法名的區別,  yii1中只是簡單的組合.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM