下面小编就为大家带来一篇Yii2使用驼峰命名的形式访问控制器(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

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

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

刚开始以为YII2中肯定有这样的设置,然后就去google了下,发现都说不行,自己去看了下,果然,框架里面直接是写死的:(源码)\vendor\yiisoft\yii2\base\Controller.php

  1. /**
  2. * Creates an action based on the given action ID.
  3. * The method first checks if the action ID has been declared in [[actions()]]. If so,
  4. * it will use the configuration declared there to create the action object.
  5. * If not, it will look for a controller method whose name is in the format of `actionXyz`
  6. * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
  7. * method will be created and returned.
  8. * @param string $id the action ID.
  9. * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
  10. */
  11. public function createAction($id)
  12. {
  13. if ($id === '') {
  14. $id = $this->defaultAction;
  15. }
  16. $actionMap = $this->actions();
  17. if (isset($actionMap[$id])) {
  18. return Yii::createObject($actionMap[$id], [$id, $this]);
  19. } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
  20. $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
  21. if (method_exists($this, $methodName)) {
  22. $method = new \ReflectionMethod($this, $methodName);
  23. if ($method->isPublic() && $method->getName() === $methodName) {
  24. return new InlineAction($id, $this, $methodName);
  25. }
  26. }
  27. }
  28. return null;
  29. }

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

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

我们可以写个components处理:\common\components\zController.php

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Steven
  5. * Date: 2017/10/26
  6. * Time: 16:50
  7. */
  8. namespace common\components;
  9. use \yii\base\Controller;
  10. use yii\base\InlineAction;
  11. class zController extends Controller //这里需要继承自\yii\base\Controller
  12. {
  13. /**
  14. * Author:Steven
  15. * Desc:重写路由,处理访问控制器支持驼峰命名法
  16. * @param string $id
  17. * @return null|object|InlineAction
  18. */
  19. public function createAction($id)
  20. {
  21. if ($id === '') {
  22. $id = $this->defaultAction;
  23. }
  24. $actionMap = $this->actions();
  25. if (isset($actionMap[$id])) {
  26. return \Yii::createObject($actionMap[$id], [$id, $this]);
  27. } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
  28. $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
  29. if (method_exists($this, $methodName)) {
  30. $method = new \ReflectionMethod($this, $methodName);
  31. if ($method->isPublic() && $method->getName() === $methodName) {
  32. return new InlineAction($id, $this, $methodName);
  33. }
  34. }
  35. } else {
  36. $methodName = 'action' . $id;
  37. if (method_exists($this, $methodName)) {
  38. $method = new \ReflectionMethod($this, $methodName);
  39. if ($method->isPublic() && $method->getName() === $methodName) {
  40. return new InlineAction($id, $this, $methodName);
  41. }
  42. }
  43. }
  44. return null;
  45. }
  46. }

这就可以支持使用驼峰形式访问了,当然这个的形式很多,也可以写成一个控制器,然后其它控制器继承这个控制器就行了,但是原理是一样的

如果使用? 是需要用驼峰命名形式访问的控制器中,继承下这个zController就可以了,

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Steven
  5. * Date: 2017/10/18
  6. * Time: 15:57
  7. */
  8. namespace backend\modules\hotel\controllers;
  9. use yii\filters\AccessControl;
  10. use yii\filters\ContentNegotiator;
  11. use yii\web\Response;
  12. use common\components\zController;
  13. class QunarController extends zController
  14. {
  15. public $enableCsrfValidation = false;
  16. public function behaviors()
  17. {
  18. $behaviors = parent::behaviors();
  19. unset($behaviors['authenticator']);
  20. $behaviors['corsFilter'] = [
  21. 'class' => \yii\filters\Cors::className(),
  22. 'cors' => [ // restrict access to
  23. 'Access-Control-Request-Method' => ['*'], // Allow only POST and PUT methods
  24. 'Access-Control-Request-Headers' => ['*'], // Allow only headers 'X-Wsse'
  25. 'Access-Control-Allow-Credentials' => true, // Allow OPTIONS caching
  26. 'Access-Control-Max-Age' => 3600, // Allow the X-Pagination-Current-Page header to be exposed to the browser.
  27. 'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
  28. ],
  29. ];
  30. //配置ContentNegotiator支持JSON和XML响应格式
  31. /*$behaviors['contentNegotiator'] = [
  32. 'class' => ContentNegotiator::className(), 'formats' => [
  33. 'application/xml' => Response::FORMAT_XML
  34. ]
  35. ];*/
  36. $behaviors['access'] = [
  37. 'class' => AccessControl::className(),
  38. 'rules' => [
  39. [
  40. 'ips' => ['119.254.26.*', //去哪儿IP访问白名单
  41. '127.0.0.1','106.14.56.77','180.168.4.58' //蜘蛛及本地IP访问白名单
  42. ], 'allow' => true,
  43. ],
  44. ],
  45. ];
  46. return $behaviors;
  47. }
  48. }
  49. ?>
  1. /**
  2. * Author:Steven
  3. * Desc:酒店静态数据接口
  4. */
  5. public function actiongetFullHotelInfo()
  6. {
  7. }

更多相关文章

  1. android中各种permissiond详解
  2. Android(安卓)Virtual Device Manager 创建虚拟机出现SDK Manage
  3. android java.net.ConnectException: Connection 127.0.0.1:8080
  4. android中访问时的localhost问题
  5. Android文件访问权限问题
  6. 【demo记录】极光推送(android app访问服务器,服务器推送信息到新a
  7. 访问器属性原理及获取DOM元素方法
  8. android 基于百度地图api获取经纬度
  9. Nginx禁止ip访问或非法域名访问

随机推荐

  1. Android 学习记录-ImageView显示格式
  2. Android虚拟机大屏幕设置
  3. android - JNI NewStringUTF字串的釋放
  4. 全网最全的Android资源汇总
  5. Android中后台显示悬浮窗口的方法
  6. Android(安卓)Fragment 你应该知道的一切
  7. 系出名门Android(4) - 活动(Activity),
  8. 更新Android SDK Tools, revision 7报错
  9. 从零开始学习android
  10. Android(安卓)Studio 生成Jar包