Yii2使用驼峰命名的形式访问控制器
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使用驼峰命名的形式访问控制器的更多相关文章
- Yii2.0 高级版修改默认访问控制器
frontend->config->main-local.php $config = [ 'defaultRoute' => 'index/index',//修改默认访问控制器 'c ...
- thinkphp5.0解决控制器驼峰命名时提示找不到类名
今天碰到了一个比较坑爹的问题,我的控制器的名字是用驼峰命名的,但是却给我报错,如下: 怎么解决呢? 看我的视图,同样是驼峰命名,此时只要将其改为auth_group这样的方式就可以了. 注意:url地 ...
- yii2.0配置以pathinfo的形式访问
yii2.0默认的访问形式为:dxr.com/index.php?r=index/list,一般我们都会配置成pathinfo的形式来访问:dxr.com/index/list,这样更符合用户习惯. ...
- yii2.0 访问控制器下的方法时出现 Object Not Found! 解决办法
yii2.0 访问控制器下的方法时出现 Object Not Found! 时 可以查看(apache) 入口文件index.php 的同级有没有 .htaccess 文件 没有.htaccess ...
- java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)
java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...
- java jvm学习笔记十一(访问控制器)
欢迎装载请说明出处: http://blog.csdn.net/yfqnihao/article/details/8271665 这一节,我们要学习的是访问控制器,在阅读本节之前,如果没有前面几节的 ...
- SpringBoot Mybatis的驼峰命名
开启驼峰命名的方法 第一种方式: 可以在配置类中进行配置.配置的Demo如下: @Bean(name="sqlSessionFactory") public SqlSessionF ...
- java下划线与驼峰命名互转
方式一: 下划线与驼峰命名转换: public class Tool { private static Pattern linePattern = Pattern.compile("_(\\ ...
- ABAP开发环境终于支持以驼峰命名法自动格式化ABAP变量名了
Jerry进入SAP成都研究院前,一直是用C/C++开发,所以刚接触ABAP,对于她在某些语法环境下大小写敏感,某些环境下不敏感的特性很不适应.那时候Jerry深深地怀念之前在C/C++编程时遵循的驼 ...
随机推荐
- Redis基操
Redis key-value类型的缓存数据库 指定IP和端口连接redis: ./redis-cli -h ip -p port Redis基本操作命令 命令 返回值 简介 ping PONG 测试 ...
- 04-树4. Root of AVL Tree-平衡查找树AVL树的实现
对于一棵普通的二叉查找树而言,在进行多次的插入或删除后,容易让树失去平衡,导致树的深度不是O(logN),而接近O(N),这样将大大减少对树的查找效率.一种解决办法就是要有一个称为平衡的附加的结构条件 ...
- poj3254 Corn Fields
orn Fields Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 17989 Accepted: 9474 Descr ...
- HDU1536:S-Nim(sg函数)
S-Nim Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submi ...
- bash shell输出颜色
http://note.youdao.com/noteshare?id=9de6d5fac6380447df112dff5bc404a1
- C++ ------ 互斥锁、原子操作的性能测试
atomic原子操作:是在新标准C++11,引入了原子操作的概念,并通过这个新的头文件提供了多种原子操作数据类型,例如,atomic_bool,atomic_int等等 测试程序 #include & ...
- PHP_INT_SIZE
PHP_INT_SIZE:表示整数integer值的字长 PHP_INT_MAX:表示整数integer值的最大值 注: 输出下32位中PHP_INT_SIZE:4,PHP_INT_MAX:21474 ...
- java中16进制转换10进制
java中16进制转换10进制 public static void main(String[] args) { String str = "04e1"; String myStr ...
- 图:centrality
[定义]Centrality:图中每个节点v的相对重要度c(v),重要度是什么可根据具体应用定义. [估计方法] Degree centrality Betweenness centrality Cl ...
- [USACO07FEB] Lilypad Pond
https://www.luogu.org/problem/show?pid=1606 题目描述 FJ has installed a beautiful pond for his cows' aes ...