佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Yii2使用駝峰命名的形式訪問控制器的示例代碼

Yii2使用駝峰命名的形式訪問控制器的示例代碼

熱門標(biāo)簽:服務(wù)器配置 Linux服務(wù)器 團(tuán)購網(wǎng)站 科大訊飛語音識別系統(tǒng) 銀行業(yè)務(wù) Mysql連接數(shù)設(shè)置 電子圍欄 阿里云

yii2在使用的時候,訪問控制器的時候,如果控制器的名稱是駝峰命名法,那訪問的url中要改成橫線的形式。例如:

public function actionRoomUpdate()
{
//
}
//訪問的時候就要www.test.com/room-update這樣訪問

最近在做某渠道的直連的時候,他們提供的文檔上明確指出接口的形式:

剛開始以為YII2中肯定有這樣的設(shè)置,然后就去google了下,發(fā)現(xiàn)都說不行,自己去看了下,果然,框架里面直接是寫死的:(源碼)\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,不過問題倒不大,這個代碼很容易理解,我們發(fā)現(xiàn),其實如果在這個源碼的基礎(chǔ)上再加上一個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 ,這就可以支持使用駝峰形式訪問了,當(dāng)然這個的形式很多,也可以寫成一個控制器,然后其它控制器繼承這個控制器就行了,但是原理是一樣的

如果使用?  是需要用駝峰命名形式訪問的控制器中,繼承下這個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響應(yīng)格式
  /*$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:酒店靜態(tài)數(shù)據(jù)接口
  */
 public function actiongetFullHotelInfo()
 {
 }

訪問的時候url為www.test.com/getFullHotelInfo

總結(jié)

以上所述是小編給大家介紹的Yii2使用駝峰命名的形式訪問控制器,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

您可能感興趣的文章:
  • 詳解PHP的Yii框架中的Controller控制器
  • Yii2創(chuàng)建控制器(createController)方法詳解
  • yii2控制器Controller Ajax操作示例
  • Yii2使用$this->context獲取當(dāng)前的Module、Controller(控制器)、Action等
  • Yii2設(shè)置默認(rèn)控制器的兩種方法
  • Yii控制器中操作視圖js的方法
  • Yii控制器中filter過濾器用法分析
  • Yii2使用駝峰命名的形式訪問控制器(實例講解)
  • Yii2框架控制器、路由、Url生成操作示例
  • yii2 在控制器中驗證請求參數(shù)的使用方法
  • Yii 框架控制器創(chuàng)建使用及控制器響應(yīng)操作示例

標(biāo)簽:江蘇 棗莊 衡水 大理 廣元 衢州 蚌埠 萍鄉(xiāng)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Yii2使用駝峰命名的形式訪問控制器的示例代碼》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    孝昌县| 垫江县| 桂东县| 万州区| 沧源| 普格县| 密云县| 开鲁县| 孟州市| 浦东新区| 偃师市| 东港市| 湘乡市| 礼泉县| 兴隆县| 益阳市| 林州市| 南澳县| 郁南县| 双峰县| 乌什县| 永川市| 固始县| 广汉市| 宣恩县| 定陶县| 太原市| 延边| 怀集县| 余庆县| 永和县| 青州市| 河间市| 囊谦县| 平泉县| 兖州市| 墨玉县| 建昌县| 海南省| 琼结县| 昭苏县|