Yii2 驼峰命名控制器访问配置方法
使用 Yii2 框架时,若控制器名称采用驼峰命名法,默认的 URL 访问路径会将其转换为横线分隔的形式。例如:
public function actionRoomUpdate()
{
//
}
//访问的时候就要www.test.com/room-update这样访问
近期在处理某渠道直连业务时,对方文档明确指定了接口的调用格式:

起初认为 Yii2 内置了相关配置选项,经搜索确认无果后查阅源码,发现框架内部逻辑是硬编码实现的。具体位置位于:\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;
}
虽然这种设计略显局限,但解决起来并不复杂。分析源码可知,只需在此基础上增加一个 else 分支即可满足需求,不过强烈建议不要直接修改框架核心代码。
鉴于项目采用 Yii2 Advanced 架构且包含多个子应用,为确保其他项目正常运行,仅对个别需要驼峰访问的控制器进行特殊处理更为稳妥:
可以通过编写自定义组件来实现:\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;
}
}</code></pre>
完成上述配置后,即可支持驼峰形式的 URL 访问。当然,实现方式多样,也可以定义一个基类控制器供其他控制器继承,其核心原理相同。
具体使用方法为:在需要使用驼峰命名访问的控制器中,继承该 zController 类即可。
<pre class="brush:php;"><code class="language-php">
<?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 中使用驼峰命名形式访问控制器的方法,希望能对大家有所帮助。如有任何疑问,欢迎留言交流,小编会及时回复。感谢大家对本站的支持!