Yii2如何使用駝峰命名的形式來存取控制器的執行個體

來源:互聯網
上載者:User
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.