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. Codeforces Round #385 (Div. 2)A B C 模拟 水 并查集

    A. Hongcow Learns the Cyclic Shift time limit per test 2 seconds memory limit per test 256 megabytes ...

  2. Ubuntu下Sublime Text 2优化配置

    以前经常用Notepad++,最近因为需要长期在Linux环境下进行C开发,就使用了sublime Text 2,这里就不介绍基本的了主要针对我使用的经验中进行一些总结. 1.pacage contr ...

  3. TC规则

    633人阅读   TC规则涉及到 队列(QUEUE) 分类器(CLASS) 过滤器(FILTER),filter划分的标志位可用U32或iptables的set-mark来实现 ) 一般是" ...

  4. for程序员:这些你可能遇到的职场难题,我们帮你整理好了答案

    “迷茫”是当下青年谈论的最多的词汇之一,无论高矮胖瘦富穷美丑,每个人都有自己独特的难题.造成“迷茫”的原因有很多种,比如生存压力,情感问题,以及困扰着相当一部分人的职场焦虑.今天这篇关于“职场迷茫”的 ...

  5. JS中的匿名函数自执行、函数声明与函数表达式

    先看一段jQuery源码中匿名函数自执行的例子: (function( window, undefined ) { // jquery code })(window); 另外一种常见的写法: +fun ...

  6. kvm虚拟机

    ###查看虚拟机的状态 [root@fgeserver2 ~]# virsh list --all Id Name State------------------------------------- ...

  7. fmt:formatNumber use locale display negative currency in -$xxx.xx format in JSTL

    First, we want to know our own locale,how to display the locale in a JSTL? <c:out value="${p ...

  8. c# 重载运算符(ovveride operator)踩坑记,关于null比对

    场景描述: 需要比对两个版本的对应对象是否完全一致(每个属性值一致),不一致的导出报表颜色标识,以便提醒后续使用报表人员. 实现思路: 对象重载ToString方法,另实现一比对基类(为了通用)重载= ...

  9. 移动Web界面样式-CSS3

    CSS2.1发布至今已经有7年的历史,在这7年里,互联网的发展 已经发生了翻天覆地的变化.CSS2.1有时候难以满足快速提高性能.提升用户体验的Web应用的需求.CSS3标准的出现就是增强CSS2.1 ...

  10. uoj311 【UNR #2】积劳成疾

    传送门:http://uoj.ac/problem/311 [题解] 这题的期望dp好神奇啊(可能是我太菜了) 由于每个位置都完全一样,所以我们设$f_{i,j}$表示审了连续$i$个位置,最大值不超 ...