溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在Yii2中使用駝峰命名的形式訪問控制器

發(fā)布時(shí)間:2021-04-15 16:21:01 來源:億速云 閱讀:180 作者:Leah 欄目:開發(fā)技術(shù)

怎么在Yii2中使用駝峰命名的形式訪問控制器?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

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

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

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

怎么在Yii2中使用駝峰命名的形式訪問控制器

剛開始以為YII2中肯定有這樣的設(shè)置,然后就去google了下,發(fā)現(xiàn)都說不行,自己去看了下,果然,框架里面直接是寫死的:(源碼)\vendor\yiisoft\yii2\base\Controller.php

怎么在Yii2中使用駝峰命名的形式訪問控制器

/**
  * 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;
 }

這點(diǎn)有點(diǎn)low,不過問題倒不大,這個(gè)代碼很容易理解,我們發(fā)現(xiàn),其實(shí)如果在這個(gè)源碼的基礎(chǔ)上再加上一個(gè)else就可以搞定,但是還是不建議直接改源碼。

由于我們的項(xiàng)目用的事yii2的advanced版本,并且里面有多個(gè)項(xiàng)目,還要保證其他項(xiàng)目使用正常(也就是個(gè)別的控制器才需要使用駝峰命名的方式訪問),這也容易:

我們可以寫個(gè)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)然這個(gè)的形式很多,也可以寫成一個(gè)控制器,然后其它控制器繼承這個(gè)控制器就行了,但是原理是一樣的

如果使用?  是需要用駝峰命名形式訪問的控制器中,繼承下這個(gè)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()
 {
 }

看完上述內(nèi)容,你們掌握怎么在Yii2中使用駝峰命名的形式訪問控制器的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI