액세스 컨트롤러에 Camel Case 명명을 사용하는 Yii2의 분석 예
yii2在使用的时候,访问控制器的时候,如果控制器的名称是驼峰命名法,那访问的url中要改成横线的形式。例如:
} //访问的时候就要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; }}?>
示例:
<span style="color: #008000">/*</span><span style="color: #008000">* * Author:Steven * Desc:酒店静态数据接口 </span><span style="color: #008000">*/</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">function</span><span style="color: #000000"> actiongetFullHotelInfo() { }</span>
위 내용은 액세스 컨트롤러에 Camel Case 명명을 사용하는 Yii2의 분석 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

C++ 함수 이름 지정에서는 가독성을 높이고 오류를 줄이며 리팩토링을 용이하게 하기 위해 매개변수 순서를 고려하는 것이 중요합니다. 일반적인 매개변수 순서 규칙에는 작업-객체, 개체-작업, 의미론적 의미 및 표준 라이브러리 준수가 포함됩니다. 최적의 순서는 함수의 목적, 매개변수 유형, 잠재적인 혼동 및 언어 규칙에 따라 달라집니다.

yii2에서 jquery를 제거하는 방법: 1. AppAsset.php 파일을 편집하고 $dependents 변수의 "yii\web\YiiAsset" 값을 주석 처리합니다. 2. main.php 파일을 편집하고 구성을 "'yii"로 추가합니다. "comComponents" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]" 필드 아래에서 jquery 스크립트를 제거합니다.

Realme 휴대폰에서 폴더를 만드는 단계별 가이드 일상 생활에서 우리는 휴대폰을 사용하여 사진, 비디오, 문서 등 다양한 파일을 저장합니다. 하지만 시간이 지날수록 휴대폰에 저장되는 파일의 개수가 늘어나 휴대폰의 메모리가 부족해지거나 파일 관리에 어려움을 겪을 수 있습니다. 파일을 보다 잘 정리하고 휴대폰 사용의 효율성을 높이기 위해 휴대폰 폴더 설정이 특히 중요해졌습니다. Realme Mobile은 강력한 시스템과 다양한 기능을 갖춘 인기 스마트폰 브랜드입니다. Realme 휴대폰에 폴더를 만들면 사용자가 파일을 더 잘 정리하는 데 도움이 됩니다.

Go 함수 명명 오류 및 대책: 빈 이름을 피하고 설명이 포함된 이름을 사용하세요. 긴 이름을 피하고 약어나 간결한 용어를 사용하십시오. 일관성을 위해 함수 이름에는 소문자를 사용합니다. 코드를 명확하게 유지하려면 밑줄을 사용하지 마세요. 이름이 함수와 일치하고 함수의 기능을 정확하게 반영하는지 확인하세요.

C++ 모두 대문자 명명법은 함수 이름에 모두 대문자를 사용하는 함수 명명 규칙으로, 일반적으로 이름 혼동을 피하기 위해 매크로 정의 및 인라인 함수에 사용됩니다. 문법:(){...}. 예: inlineintADD_NUMBERS(inta,intb){}, 이 함수는 두 숫자의 합을 계산합니다.

이 기사에서는 yii2 프레임워크를 소개하고 몇 가지 CTF 연습을 공유하며 이를 사용하여 yii2 프레임워크를 학습하는 것이 모든 사람에게 도움이 되기를 바랍니다.

제목: 왜 Go 언어를 Go라고 부르나요? Go 언어(Golang이라고도 함)는 Google이 개발한 프로그래밍 언어로, 2009년 처음 출시된 이후 계속 인기가 높아져 네트워크 프로그래밍, 클라우드 컴퓨팅, 빅데이터 등 다양한 분야에서 널리 사용되고 있습니다. 데이터 처리 중입니다. 그런데 왜 "Go"라는 단어를 Go 언어의 이름으로 선택했는지 궁금해하는 사람들이 많습니다. 이번 글에서는 Go 언어의 이름이 "Go"인 이유를 살펴보겠습니다. 우선 Go 언어는 200의 이름을 따서 명명되었습니다.

1. Composer가 포함된 yii2-redis 마스터 브랜치의 Windows 버전을 다운로드해야 합니다. 2. 압축을 풀고 Vendor/yiisoft에 복사합니다. 3. 'yiisoft/yii2-redis'=>array('name'=>'yiisoft 추가 yiisoft /yii2-redis','version'=>'2.0 아래의 Extensions.php로.
