yii2在使用的时候,访问控制器的时候,如果控制器的名称是驼峰命名法,那访问的url中要改成横线的形式。例如:

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

最近在做某渠道的直连的时候,他们提供的文档上明确指出接口的形式:

刚开始以为YII2中肯定有这样的设置,然后就去google了下,发现都说不行,自己去看了下,果然,框架里面直接是写死的:(源码)\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;
}

这点有点low,不过问题倒不大,这个代码很容易理解,我们发现,其实如果在这个源码的基础上再加上一个else就可以搞定,但是还是不建议直接改源码。

由于我们的项目用的事yii2的advanced版本,并且里面有多个项目,还要保证其他项目使用正常(也就是个别的控制器才需要使用驼峰命名的方式访问),这也容易:

我们可以写个components处理:\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\InlineAction; class zController extends Controller //这里需要继承自\yii\base\Controller
{
/**
* 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 backend\modules\hotel\controllers;
use yii\filters\AccessControl;
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' => [ // 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

以上.

Yii2使用驼峰命名的形式访问控制器的更多相关文章

  1. Yii2.0 高级版修改默认访问控制器

    frontend->config->main-local.php $config = [ 'defaultRoute' => 'index/index',//修改默认访问控制器 'c ...

  2. thinkphp5.0解决控制器驼峰命名时提示找不到类名

    今天碰到了一个比较坑爹的问题,我的控制器的名字是用驼峰命名的,但是却给我报错,如下: 怎么解决呢? 看我的视图,同样是驼峰命名,此时只要将其改为auth_group这样的方式就可以了. 注意:url地 ...

  3. yii2.0配置以pathinfo的形式访问

    yii2.0默认的访问形式为:dxr.com/index.php?r=index/list,一般我们都会配置成pathinfo的形式来访问:dxr.com/index/list,这样更符合用户习惯. ...

  4. yii2.0 访问控制器下的方法时出现 Object Not Found! 解决办法

    yii2.0  访问控制器下的方法时出现 Object Not Found! 时 可以查看(apache)  入口文件index.php 的同级有没有 .htaccess 文件 没有.htaccess ...

  5. java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)

    java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...

  6. java jvm学习笔记十一(访问控制器)

     欢迎装载请说明出处: http://blog.csdn.net/yfqnihao/article/details/8271665 这一节,我们要学习的是访问控制器,在阅读本节之前,如果没有前面几节的 ...

  7. SpringBoot Mybatis的驼峰命名

    开启驼峰命名的方法 第一种方式: 可以在配置类中进行配置.配置的Demo如下: @Bean(name="sqlSessionFactory") public SqlSessionF ...

  8. java下划线与驼峰命名互转

    方式一: 下划线与驼峰命名转换: public class Tool { private static Pattern linePattern = Pattern.compile("_(\\ ...

  9. ABAP开发环境终于支持以驼峰命名法自动格式化ABAP变量名了

    Jerry进入SAP成都研究院前,一直是用C/C++开发,所以刚接触ABAP,对于她在某些语法环境下大小写敏感,某些环境下不敏感的特性很不适应.那时候Jerry深深地怀念之前在C/C++编程时遵循的驼 ...

随机推荐

  1. 【数学】【P5077】 Tweetuzki 爱等差数列

    Description Tweetuzki 特别喜欢等差数列.尤其是公差为 \(1\) 且全为正整数的等差数列. 显然,对于每一个数 \(s\),都能找到一个对应的公差为 \(1\) 且全为正整数的等 ...

  2. C之Volatile关键字的介绍与使用20170724

    volatile 的意思是“易失的,易改变的”. 一.volatile的引入 这个限定词的含义是向编译器指明变量的内容可能会由于其他程序的修改而变化.通常在程序中申明了一个变量时,编译器会尽量把它存放 ...

  3. jar包下载地址(fasterxml.jackson)

    jar包下载地址(fasterxml.jackson) Home » com.fasterxml.jackson » core jar包下载地址 https://mvnrepository.com/a ...

  4. bzoj 2929 [Poi1999]洞穴攀行 网络流

    2929: [Poi1999]洞穴攀行 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 499  Solved: 295[Submit][Status][ ...

  5. (转)JAVA 十六个常用工具类

    一. org.apache.commons.io.IOUtils closeQuietly 关闭一个IO流.socket.或者selector且不抛出异常.通常放在finally块 toString ...

  6. VS工程使用Git时的过滤文件

    1.解决方案必须保留的文件sln和suo,需要过滤的文件为sdfVisual Studio.NET采用两种文件类型(.sln和.suo)来存储特定于解决方案的设置,它们总称为解决方案文件.为解决方案资 ...

  7. 学习 C++的用途,(前辈总结)

    C++准确说是一门中级语言,介于汇编和高级语言之间吧,要求程序员了解计算机的内部数据存储.个人认为,作为学生还是花功夫学C++,因为<设计模式><数据结构>这些课程基本上还是C ...

  8. [Luogu 1196] NOI2002 银河英雄传说

    [Luogu 1196] NOI2002 银河英雄传说 话说十六年前的 NOI 真简单... 我一开始还把题看错了- 题意:一群人,每个人各自成一队,每次命令让两队首位相接合成一队,每次询问问你某两个 ...

  9. JS中client/offset/scroll等的宽高解析

    原文地址:→传送门 window相关宽高属性 1. window.outerHeight (窗口的外层的高度) / window.outerWidth (窗口的外层的宽度) window.outerH ...

  10. jQuery面向对象的写法

    定义的写法 //构造函数 function test(){ //construct code } //初始化方法 test.prototype.init = function(){ //init co ...