YII2 instance analysis of Access controller using hump named form

Source: Internet
Author: User
Tags yii
Yii2 in use, when accessing the controller, if the name of the controller is the hump naming method, the URL of the visit should be changed to the form of horizontal lines. For example:

}//access to www.test.com/room-update such access

When you recently made a direct connection to a channel, they provided a document that clearly indicated the form of the interface:

Just started to think that YII2 must have such a setting, and then went to Google, found that all said no, they went to see the next, sure enough, the framework is directly written dead: (source) \vendor\yiisoft\yii2\base\controller.php

/** * Creates an action based on the given action ID. * The method first checks if the action ID has been declared in [[Actions ()]].     If So, * It'll use the configuration declared there to create the action object.  * If not, it'll look for a controller method whose name was in the format of ' actionxyz ' * where ' Xyz ' stands for the The action ID.     If found, an [[Inlineaction]] representing that * method would be created and returned.     * @param string $id the action ID. * @return action The newly created action instance.     Null if the ID doesn ' t resolve to any action.        */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) {            $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 inlineacti                On ($id, $this, $methodName);    }}} return null; }

This is a bit low, but the problem is not big, this code is very easy to understand, we found that, in fact, if the basis of the source and then add an else can be done, but still do not recommend directly to change the source.

Because of the advanced version of YII2 for our project, and the fact that there are several projects in it, it is also easy to ensure that other projects are used normally (that is, individual controllers need to be accessed using the Hump name).

We can write a deal: \common\components\zcontroller.php

<?php/** * Created by Phpstorm. * User:steven * DATE:2017/10/26 * time:16:50 */namespace common\components;use \yii\base\controller;use yii\base\Inline Action;class Zcontroller extends Controller//Here need to inherit from \yii\base\controller{/** * author:steven * Desc: rewrite route, handle The access controller supports the Hump naming method * @param string $id * @return null|object| Inlineaction */Public Function createaction ($id) {if ($id = = =) {$id = $this->defaulta        ction;        } $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) { $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, $th                is, $methodName);            }}}} else {$methodName = ' action '. $id;                if (Method_exists ($this, $methodName)) {$method = new \reflectionmethod ($this, $methodName); if ($method->ispublic () && $method->getname () = = = $methodName) {return new inlineacti                On ($id, $this, $methodName);    }}} return null; }}

OK, this can support the use of hump form access, of course, this is a lot of form, can also be written as a controller, and then other controllers inherit the controller on the line, but the principle is the same

If you use ? is a controller that needs to be accessed with the name of the hump, inherited under this Zcontroller,

<?php/** * Created by Phpstorm. * User:steven * DATE:2017/10/18 * time:15:57 */namespace backend\modules\hotel\controllers;use yii\filters\AccessContr Ol;use yii\filters\contentnegotiator;use yii\web\response;use Common\components\zcontroller;class QunarController    Extends zcontroller{public $enableCsrfValidation = false;        Public Function Behaviors () {$behaviors = Parent::behaviors ();        unset ($behaviors [' authenticator ']); $behaviors [' corsfilter '] = [' class ' + \yii\filters\cors::classname (), ' Cors ' = [//Restric                T access to ' access-control-request-method ' = [' * '],//Allow only POST and PUT methods ' Access-control-request-headers ' = [' * '],//Allow only Headers ' X-wsse ' Access-control-allow-credenti Als ' = True,//Allow OPTIONS caching ' access-control-max-age ' = 3600,//Allow the X-PAGINATION-CU      Rrent-page header to being exposed to the browser.          ' Access-control-expose-headers ' = [' x-pagination-current-page '],],; Configuration Contentnegotiator supports JSON and XML response formats/* $behaviors [' contentnegotiator '] = [' class ' + Contentnegotiato        R::classname (), ' formats ' = [' application/xml ' = ' response::format_xml]];*/                $behaviors [' access '] = [' class ' = = Accesscontrol::classname (), ' rules ' = [ [' ips ' = [' 119.254.26.* ',//Go to IP access Whitelist ' 127.0.0.1 ', ' 106.14.56.77 ', ' 180.16        8.4.58 '//Spiders and local IP access whitelist], ' allow ' (= True,],],];    return $behaviors; }}?>

Example:

/* *     * author:steven     * Desc: hotel static Data Interface     */ public     function  Actiongetfullhotelinfo ()    {    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.