>

Yii2使用驼峰命名的款型拜见调控器

- 编辑:金沙国际平台登录 -

Yii2使用驼峰命名的款型拜见调控器

yii2在接纳的时候,访问调节器的时候,假使控制器的称号是驼峰命名法,这访谈的url中要改成横线的方式。举例:

Yii2使用驼峰命名的款型拜候调整器,yii2驼峰

yii2在应用的时候,访问调整器的时候,如若调控器的名称是驼峰命名法,那访问的url中要改成横线的样式。举个例子:

public function actionRoomUpdate()
{
//
}
//访问的时候就要www.test.com/room-update这样访问

多年来在做某路子的直连的时候,他们提供的文书档案上显然提议接口的款型:

图片 1

刚开始认为YII第22中学必将有那般的装置,然后就去google了下,发掘都说非常,本人去看了下,果然,框架之中平昔是写死的:(源码)vendoryiisoftyii2baseController.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;
    }

那点有一点low,然则难点倒十分的小,这几个代码很轻松精通,我们开掘,其实只要在这几个源码的功底上再加多多个else就能够解决,可是照旧不提议直接改源码。

是因为大家的档期的顺序用的事yii2的advanced版本,况且在那之中有多少个项目,还要确认保证其余项目选择正规(也正是独家的调控器才须要选择驼峰命名的措施访问),那也易于:

咱俩得以写个components管理:commoncomponentszController.php

图片 2

<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/10/26
 * Time: 16:50
 */
namespace commoncomponents;
use yiibaseController;
use yiibaseInlineAction;

class zController extends Controller   //这里需要继承自yiibaseController
{
    /**
     * Author:Steven
     * Desc:重写路由,处理访问控制器支持驼峰命名法
     * @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 ,那就足以支撑选取驼峰情势拜谒了,当然这几个的花样非常多,也能够写成叁个调节器,然后别的调整器承接那一个调节器就行了,可是原理是均等的

假使应用?  是内需用驼峰命名情势拜见的调节器中,承继下这么些zController就足以了,

<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/10/18
 * Time: 15:57
 */
namespace backendmoduleshotelcontrollers;
use yiifiltersAccessControl;
use yiifiltersContentNegotiator;
use yiiwebResponse;
use commoncomponentszController;

class QunarController extends zController
{
    public $enableCsrfValidation = false;


    public function behaviors()
    {
        $behaviors = parent::behaviors();
        unset($behaviors['authenticator']);
        $behaviors['corsFilter'] = [
            'class' => yiifiltersCors::className(),
            'cors' => [ // restrict access to
                'Access-Control-Request-Method' => ['*'], // Allow only POST and PUT methods
                'Access-Control-Request-Headers' => ['*'], // Allow only headers 'X-Wsse'
                'Access-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'],
            ],
        ];
        //配置ContentNegotiator支持JSON和XML响应格式
        /*$behaviors['contentNegotiator'] = [
            'class' => ContentNegotiator::className(), 'formats' => [
                'application/xml' => Response::FORMAT_XML
            ]
        ];*/
        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'ips' => ['119.254.26.*', //去哪儿IP访问白名单
                        '127.0.0.1','106.14.56.77','180.168.4.58'  //蜘蛛及本地IP访问白名单
                    ], 'allow' => true,
                ],
            ],
        ];
        return $behaviors;
    }

}

?>

示例:

/**
     * Author:Steven
     * Desc:酒店静态数据接口
     */
    public function actiongetFullHotelInfo()
    {

    }

访问的时候url为www.test.com/getFullHotelInfo

以上.

 Q:2384834530

yii2在运用的时候,访谈调控器的时候,假若调整器的称号是驼峰命名法,那访谈的url中要改成...

public function actionRoomUpdate(){//}
//访问的时候就要www.test.com/room-update这样访问

近期在做某路子的直连的时候,他们提供的文书档案上显明提议接口的样式:

图片 3

刚开始感觉YII第22中学料定有那般的安装,然后就去google了下,开采都说特别,自个儿去看了下,果然,框架之中一向是写死的:vendoryiisoftyii2baseController.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;    }

这一点有一点low,但是难点倒极小,那一个代码很轻巧通晓,我们发掘,其实即便在这几个源码的底子上再拉长三个else就可以化解,不过依旧不提议直接改源码。

鉴于大家的类型用的事yii2的advanced版本,况兼个中有多少个等级次序,还要保证别的品种利用正规(也便是各自的调节器才须要运用驼峰命名的主意访谈),这也轻巧:

咱俩得以写个components管理:commoncomponentszController.php

图片 4

<?php/** * Created by PhpStorm. * User: Steven * Date: 2017/10/26 * Time: 16:50 */namespace commoncomponents;use yiibaseController;use yiibaseInlineAction;class zController extends Controller   //这里需要继承自yiibaseController{    /**     * Author:Steven     * Desc:重写路由,处理访问控制器支持驼峰命名法     * @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 ,那就足以支撑使用驼峰形式拜谒了,当然这些的款式非常多,也得以写成二个控制器,然后别的调节器承袭这些调控器就行了,可是原理是平等的

何以行使? 是需求用驼峰命名情势拜候的调节器中,承接下这几个zController就足以了,

<?php/** * Created by PhpStorm. * User: Steven * Date: 2017/10/18 * Time: 15:57 */namespace backendmoduleshotelcontrollers;use yiifiltersAccessControl;use yiifiltersContentNegotiator;use yiiwebResponse;use commoncomponentszController;class QunarController extends zController{    public $enableCsrfValidation = false;    public function behaviors()    {        $behaviors = parent::behaviors();        unset($behaviors['authenticator']);        $behaviors['corsFilter'] = [            'class' => yiifiltersCors::className(),            'cors' => [ // restrict access to                'Access-Control-Request-Method' => ['*'], // Allow only POST and PUT methods                'Access-Control-Request-Headers' => ['*'], // Allow only headers 'X-Wsse'                'Access-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'],            ],        ];        //配置ContentNegotiator支持JSON和XML响应格式        /*$behaviors['contentNegotiator'] = [            'class' => ContentNegotiator::className(), 'formats' => [                'application/xml' => Response::FORMAT_XML            ]        ];*/        $behaviors['access'] = [            'class' => AccessControl::className(),            'rules' => [                [                    'ips' => ['119.254.26.*', //去哪儿IP访问白名单                        '127.0.0.1','106.14.56.77','180.168.4.58'  //蜘蛛及本地IP访问白名单                    ], 'allow' => true,                ],            ],        ];        return $behaviors;    }}?>

示例:

/**     * Author:Steven     * Desc:酒店静态数据接口     */    public function actiongetFullHotelInfo()    {    }

访问的时候url为www.test.com/getFullHotelInfo

以上.

Q:2384834530

本文由编程发布,转载请注明来源:Yii2使用驼峰命名的款型拜见调控器