B
B
bogdaniy2015-01-31 12:32:14
Yii
bogdaniy, 2015-01-31 12:32:14

Why can't CamelCase be used in the action name in Yii2?

In yii2, for some reason, it was decided to strictly limit the naming of the action in the form of "action", "camel-case-action",
https://github.com/yiisoft/yii2/issues/289
And to change this you need in your base controller override the createAction method
https://github.com/yiisoft/yii2/commit/d8bc962cabe...
Which is rather dumb, since all code may stop working when updating dependencies.
This looks especially strange when developing Rest Api.
/auth/sign-in
/entity/move-to-group

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zohei, 2015-07-30
@Zohei

This was done for the sake of SEO.
However, I myself had to strain myself when transferring the project from yii1 to yii2.
I didn’t manage to google the solution, so I’m posting my quick crutch.
I just overridden the createAction method in the controller I needed by adding upper case to the regular expression:

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 \yii\base\InlineAction($id, $this, $methodName);
                }
            }
        }
        return null;
    }

The original method in the link https://github.com/yiisoft/yii2/blob/master/framew...
Fortunately, I had CamelCase in places that are not critical for SEO, such as api or personal account, so I don’t care about possible problems with SEO.

L
lebedyncrs, 2015-01-31
@lebedyncrs

Most likely this is a mini bug that the developers have not yet corrected. But in the future version I think they will fix it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question