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. python基础----递归函数(二分法、最大深度递归)

    递归函数 定义:在函数内部,可以调用其他函数.如果一个函数在内部调用自身本身,这个函数就是递归函数. #例子1 # age()=age()+ n= age(n)=age(n-)+ # age()=ag ...

  2. 如何在 ASP.NET 应用程序中实现模拟用户身份(在ASP.NET中以管理员身份运行网站)

    前言 在实际的项目开发中,我们可能会需要调用一些非托管程序,而有些非托管程序需要有更高的身份权限才能正确执行.本文介绍了如何让IIS承载的ASP.NET网站以特定的账户执行,比如Administrat ...

  3. NYOJ--139

    原题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=139 分析:cantor展开,康托展开用于计算一个排列的序数.公式为: X=a[n]*n! ...

  4. 字符串hash的学习部分 可以算是模板?

    资料来自于http://www.bilibili.com/video/av7230433/ 定义这个字符串为s ①单hash hash[i] = (hash[i - 1] * p + idx(s[i] ...

  5. 动态规划:LIS优化

    对于1D/1D动态规划来说,理论时间复杂度都是O(n^2)的,这种动态规划一般都可以进行优化,贴一篇文章 https://wenku.baidu.com/view/e317b1020740be1e65 ...

  6. CF835 D DP

    所有所有阶回文串的个数.对于一个k阶回文串,定义为:它的左右两侧相同且是k-1阶回文串 显然高阶回文串由低阶构成,那么枚举长度,从左到右遍历,dp[l][r]代表从l到r串最大的阶数,cnt[i]记录 ...

  7. Mysql通过show processlist排查数据库执行慢

    RDS for MySQL使用的是InnoDB引擎.不同于MyISAM引擎只提供表锁,InnoDB提供不同级别的锁.但是在我们日常的操作过程中经常由于对数据库不当的SQL操作导致出现长时间的锁,造成其 ...

  8. PHP扩展开发--02.包裹第三方的扩展

    背景 也许最常见的PHP扩展是那些包裹第三方C库的扩展.这些扩展包括MySQL或Oracle的数据库服务库,libxml2的 XML技术库,ImageMagick 或GD的图形操纵库. 在本节中,我们 ...

  9. [转]FILE的用法

    #include <stdio.h> int main() { char c; ; FILE *file; file = fopen("test.txt", " ...

  10. 【CodeForces】908 E. New Year and Entity Enumeration

    [题目]E. New Year and Entity Enumeration [题意]给定集合T包含n个m长二进制数,要求包含集合T且满足以下条件的集合S数:长度<=m,非和与的结果都在集合中. ...