Yii2 uses the camper name to access the controller.

Source: Internet
Author: User

Yii2 uses the camper name to access the controller.

When yii2 is in use, if the Controller name is the hump name method when accessing the controller, the access url should be changed to a horizontal line. For example:

Public function actionRoomUpdate (){//}
// Access the website at www.test.com/room-update.

Recently, during direct connection to a channel, the document they provided clearly states the interface form:

At first, I thought that YII2 had such a configuration. Then I went to google and found that I couldn't do it. I checked it myself. As a result, the framework was directly written to death: (source code) \ 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 will use the configuration declared there to create the action object.     * If not, it will look for a controller method whose name is in the format of `actionXyz`     * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that     * method will be created and returned.     * @param string $id the action ID.     * @return Action the newly created action instance. Null if the ID doesn't resolve into 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 InlineAction($id, $this, $methodName);                }            }        }        return null;    }

This is a bit low, but the problem is not big. This code is easy to understand. We found that if we add an else on the basis of this source code, we can do it, however, it is not recommended to directly change the source code.

Because the advanced version of yii2 is used in our project, and there are multiple projects in it, it is also easy to ensure that other projects are in normal use (that is, some controllers need to use the camper name for access:

We can write a components for processing: \ common \ components \ zController. php

<? Php/*** Created by PhpStorm. * User: Steven * Date: * Time: */namespace common \ components; use \ yii \ base \ Controller; use yii \ base \ InlineAction; class zController extends Controller // here you need to inherit from \ yii \ base \ Controller {/*** Author: Steven * Desc: rewrite route, the Access Controller supports the camper Method * @ param string $ id * @ return null | object | InlineAction */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 InlineAction ($ id, $ this, $ methodName );}}}Else {$ methodName = 'action '. $ 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 ;}}

OK, which supports access in the form of hump. Of course, there are many forms. You can also write them as a controller. Then other controllers can inherit this controller, but the principle is the same.

If you use? Is the Controller that needs to be accessed in the form of a camper name. Just inherit this zController,

<? Php/*** Created by PhpStorm. * User: Steven * Date: * Time: */namespace backend \ modules \ hotel \ controllers; use yii \ filters \ AccessControl;Use yii \ filters \ ContentNegotiator;Use yii \ web \ Response;Use common \ components \ zController;Class QunarController extendsZController{Public $ enableCsrfValidation = false; public function behaviors () {$ behaviors = parent: behaviors (); unset ($ behaviors ['authenticator']); $ behaviors ['corsfilter'] = ['class' => \ yii \ filters \ Cors: className (), 'cors '=> [// restrict access to 'access-Control-Request-method' => [' * '], // Allow only POST and PUT methods 'access-Control-Request-headers' => ['*'], // Allow only Headers 'x-Wsse ''Acc Ess-Control-Allow-Credentials '=> true, // Allow OPTIONS caching 'access-Control-Max-age' => 3600, // Allow the X-Pagination-Current-Page header to be exposed to the browser. 'access-Control-Expose-headers' => ['x-Pagination-Current-page'],],]; // configure ContentNegotiator to support JSON and XML response formats/* $ behaviors ['contentnegotiator'] = ['class' => contentNegotiator: className (), 'formats' => ['application/xml' => Response: FORMAT_XML]; */$ behaviors ['access'] = ['class' => AccessControl: className (), 'rules' => [['ips '=> ['123. 254. 26. * ', // IP address to which to access the White List' 127. 0.0.1 ', '2017. 14.56.77 ', '2017. 168.4.58 '// spider and local IP address access whitelist], 'allow' => true,]; return $ behaviors ;}}?>

Example:

/*** Author: Steven * Desc: Hotel static data interface */public function actiongetfull1_info (){}
 
The url is www.test.com/getfull1_info.

Above.

Q: 2384834530

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.