Yii not detecting camel case actions

走远了吗. 提交于 2019-12-13 14:22:19

问题


Yii is giving me 404 Error if I declare an action like this:

SiteController.php

public function actionRegisterUser()

This is how I call it in the main.php

 ['label' => 'Register User', 'url' => ['/site/RegisterUser']],

I tried several different combinations. The only combination that will work is this naming convention in both places:

 public function actionRegisteruser

 'url' => ['/site/registeruser']

I used to work on another Yii project (Yii 1.0) and I could name my actions in camel case and call them without any problem. Do I need to turn on some sort of setting to do this?

I also tried playing with the rules of the Controller but that didn't solve anything.


回答1:


In some cases you need camelcase link. For example, for SEO purposes (keep inbound links). You could create rewrite rule on web server side or add inline rule to URL manager on app side. Example:

'urlManager' => [
    'rules' => [
        '<controller:RegisterUser>/<action:\w+>'=>'register-user/<action>',
    ],
],

Also it's possible to write custom URL rule. Example:

namespace app\components;

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

class CarUrlRule extends Object implements UrlRuleInterface
{

    public function createUrl($manager, $route, $params)
    {
        if ($route === 'car/index') {
            if (isset($params['manufacturer'], $params['model'])) {
                return $params['manufacturer'] . '/' . $params['model'];
            } elseif (isset($params['manufacturer'])) {
                return $params['manufacturer'];
            }
        }
        return false;  // this rule does not apply
    }

    public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();
        if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
            // check $matches[1] and $matches[3] to see
            // if they match a manufacturer and a model in the database
            // If so, set $params['manufacturer'] and/or $params['model']
            // and return ['car/index', $params]
        }
        return false;  // this rule does not apply
    }
}

And use the new rule class in the [[yii\web\UrlManager::rules]] configuration:

[
    // ...other rules...

    [
        'class' => 'app\components\CarUrlRule', 
        // ...configure other properties...
    ],
]



回答2:


You need to specify your action like this ['/site/register-user']. As documentation says about Inline Actions:

index becomes actionIndex, and hello-world becomes actionHelloWorld



来源:https://stackoverflow.com/questions/32068995/yii-not-detecting-camel-case-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!