YII Framework的filter过滤器用法分析,yiifilter
YII Framework的filter过滤器用法分析,yiifilter
本文实例讲述了YII Framework的filter过滤器用法。分享给大家供大家参考,具体如下:
首先看官方给出的说明文档,什么是过滤器,过滤器的作用,过滤器的规则,过滤器的定义方法等等。
然后对过滤器进行一个总结。
http://www.yiiframework.com/doc/guide/1.1/zh_cn/basics.controller
过滤器是一段代码,可被配置在控制器动作执行之前或之后执行。例如, 访问控制过滤器将被执行以确保在执行请求的动作之前用户已通过身份验证;性能过滤器可用于测量控制器执行所用的时间。
一个动作可以有多个过滤器。过滤器执行顺序为它们出现在过滤器列表中的顺序。过滤器可以阻止动作及后面其他过滤器的执行
过滤器可以定义为一个控制器类的方法。方法名必须以 filter 开头。例如,现有的 filterAccessControl 方法定义了一个名为 accessControl 的过滤器。 过滤器方法必须为如下结构:
public function filterAccessControl($filterChain) { // 调用 $filterChain->run() 以继续后续过滤器与动作的执行。 }
其中的 $filterChain (过滤器链)是一个 CFilterChain 的实例,代表与所请求动作相关的过滤器列表。在过滤器方法中, 我们可以调用 $filterChain->run() 以继续执行后续过滤器和动作。
过滤器也可以是一个 CFilter 或其子类的实例。如下代码定义了一个新的过滤器类:
class PerformanceFilter extends CFilter { protected function preFilter($filterChain) { // 动作被执行之前应用的逻辑 return true; // 如果动作不应被执行,此处返回 false } protected function postFilter($filterChain) { // 动作执行之后应用的逻辑 } }
要对动作应用过滤器,我们需要覆盖 CController::filters() 方法。此方法应返回一个过滤器配置数组。例如:
class PostController extends CController { ...... public function filters() { return array( 'postOnly + edit, create', array( 'application.filters.PerformanceFilter - edit, create', 'unit'=>'second', ), ); } }
上述代码指定了两个过滤器: postOnly 和 PerformanceFilter。 postOnly 过滤器是基于方法的(相应的过滤器方法已在 CController 中定义); 而 performanceFilter 过滤器是基于对象的。路径别名application.filters.PerformanceFilter 指定过滤器类文件是protected/filters/PerformanceFilter。我们使用一个数组配置 PerformanceFilter ,这样它就可被用于初始化过滤器对象的属性值。此处 PerformanceFilter 的 unit 属性值将被初始为 second。
使用加减号,我们可指定哪些动作应该或不应该应用过滤器。上述代码中, postOnly 应只被应用于 edit 和create 动作,而 PerformanceFilter 应被应用于 除了 edit 和 create 之外的动作。 如果过滤器配置中没有使用加减号,则此过滤器将被应用于所有动作。
过滤器功能:
用于对访问者和数据的过滤和对访问操作的记录
使用方法:
一作为controller的一个方法。方法名以filter开头。
public function filterAccessControl($filterChain) { echo "--->filterAccessControl"; $filterChain->run(); }
二定义对立的filter类,要求extends CFilter。
CFilter
<?php /** * CFilter is the base class for all filters. * * A filter can be applied before and after an action is executed. * It can modify the context that the action is to run or decorate the result that the * action generates. * * Override {@link preFilter()} to specify the filtering logic that should be applied * before the action, and {@link postFilter()} for filtering logic after the action. * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id: CFilter.php 2799 2011-01-01 19:31:13Z qiang.xue $ * @package system.web.filters * @since 1.0 */ class CFilter extends CComponent implements IFilter { /** * Performs the filtering. * The default implementation is to invoke {@link preFilter} * and {@link postFilter} which are meant to be overridden * child classes. If a child class needs to override this method, * make sure it calls <code>$filterChain->run()</code> * if the action should be executed. * @param CFilterChain $filterChain the filter chain that the filter is on. */ public function filter($filterChain) { if($this->preFilter($filterChain)) { $filterChain->run(); $this->postFilter($filterChain); } } /** * Initializes the filter. * This method is invoked after the filter properties are initialized * and before {@link preFilter} is called. * You may override this method to include some initialization logic. * @since 1.1.4 */ public function init() { } /** * Performs the pre-action filtering. * @param CFilterChain $filterChain the filter chain that the filter is on. * @return boolean whether the filtering process should continue and the action * should be executed. */ protected function preFilter($filterChain) { return true; } /** * Performs the post-action filtering. * @param CFilterChain $filterChain the filter chain that the filter is on. */ protected function postFilter($filterChain) { } }
下面举例说明两种filter规则的使用:
SiteController.php
<?php class SiteController extends Controller { public function init() { //$this->layout='mylayout'; } public function filters() { return array( 'AccessControl - create', array( 'application.filters.MyFilter + create', ), ); } public function filterAccessControl($filterChain) { echo "--->filterAccessControl"; $filterChain->run(); } public function actionCreate() { echo "--->create action"; } public function actionPrint() { echo "--->print action"; }
/www/yii_dev/testwebap/protected# tree
.
├── commands
│ ├── shell
│ ├── TestCommand.php
│ └── TestCommand.php~
├── components
│ ├── Controller.php
│ └── UserIdentity.php
├── config
│ ├── console.php
│ ├── main.php
│ └── test.php
├── controllers
│ ├── post
│ │ └── UpdateAction.php
│ ├── SiteController.php
│ ├── TestTestController.php
│ └── UserController.php
├── filters
│ └── MyFilter.php
MyFilter.php
<?php class MyFilter extends CFilter { protected function preFilter ($filterChain) { // logic being applied before the action is executed echo "-->MyFilter-->pre"; return true; // false if the action should not be executed } protected function postFilter ($filterChain) { echo "-->MyFilter-->post"; } }
http://www.localyii.com/testwebap/index.php?r=site/print
--->filterAccessControl--->print action
http://www.localyii.com/testwebap/index.php?r=site/create
-->MyFilter-->pre--->create action-->MyFilter-->post
public function filters() { return array( 'AccessControl - create', array( 'application.filters.MyFilter + create,print', ), ); }
http://www.localyii.com/testwebap/index.php?r=site/print
--->filterAccessControl-->MyFilter-->pre--->print action-->MyFilter-->post
以上可以看到filter的具体执行流程。
在filters中有-、+
具体功能是
+表示仅仅作用于这一些action
-后边跟action名称列表。表示排除在外。
如果没有-、+则会应用的所有的action
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
您可能感兴趣的文章:
- 简介PHP的Yii框架中缓存的一些高级用法
- 深入解析PHP的Yii框架中的缓存功能
- PHP的Yii框架中View视图的使用进阶
- PHP的Yii框架中Model模型的学习教程
- 详解PHP的Yii框架中的Controller控制器
- Yii数据库缓存实例分析
- Yii开启片段缓存的方法
- 详解PHP的Yii框架中组件行为的属性注入和方法注入
- 详解在PHP的Yii框架中使用行为Behaviors的方法
- YII Framework学习之request与response用法(基于CHttpRequest响应)

핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

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

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

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

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

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

뜨거운 주제











.NET Framework 4는 개발자와 최종 사용자가 Windows에서 최신 버전의 애플리케이션을 실행하는 데 필요합니다. 그러나 .NET Framework 4를 다운로드하고 설치하는 동안 많은 사용자가 설치 프로그램이 중간에 중지되고 "오류 코드 0x800c0006으로 인해 다운로드에 실패했기 때문에 .NET Framework 4가 설치되지 않았습니다"라는 오류 메시지가 표시된다고 불평했습니다. 장치에 .NETFramework4를 설치하는 동안에도 이 문제가 발생한다면 올바른 위치에 있는 것입니다.

Windows 11 또는 Windows 10 PC에 업그레이드 또는 업데이트 문제가 있을 때마다 일반적으로 실패의 실제 원인을 나타내는 오류 코드가 표시됩니다. 그러나 오류 코드가 표시되지 않고 업그레이드나 업데이트가 실패하면 혼란이 발생할 수 있습니다. 편리한 오류 코드를 사용하면 문제가 어디에 있는지 정확히 알 수 있으므로 문제를 해결할 수 있습니다. 하지만 오류 코드가 나타나지 않기 때문에 문제를 식별하고 해결하기가 어렵습니다. 단순히 오류의 원인을 찾는 데 많은 시간이 걸립니다. 이 경우 오류의 실제 원인을 쉽게 식별하는 데 도움이 되는 Microsoft에서 제공하는 SetupDiag라는 전용 도구를 사용해 볼 수 있습니다.
![SCNotification이 작동을 멈췄습니다. [수정을 위한 5단계]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Windows 사용자는 컴퓨터를 시작할 때마다 SCNotification이 작동을 중지했습니다. 오류가 발생할 수 있습니다. SCNotification.exe는 권한 오류 및 네트워크 오류로 인해 PC를 시작할 때마다 충돌이 발생하는 Microsoft 시스템 알림 파일입니다. 이 오류는 문제가 있는 이벤트 이름으로도 알려져 있습니다. 따라서 이를 SCNotification의 작동이 중지된 것으로 표시되지 않고 버그 clr20r3으로 표시될 수 있습니다. 이 기사에서는 SCNotification이 작동을 중지하여 다시 귀찮게 하지 않도록 수정하기 위해 취해야 할 모든 단계를 살펴보겠습니다. SCNotification.e는 무엇입니까

Microsoft.NET 버전 4.5.2, 4.6 또는 4.6.1을 설치한 Microsoft Windows 사용자가 Microsoft에서 향후 제품 업데이트를 통해 프레임워크를 지원하도록 하려면 최신 버전의 Microsoft Framework를 설치해야 합니다. Microsoft에 따르면 세 가지 프레임워크 모두 2022년 4월 26일에 지원이 중단됩니다. 지원 날짜가 종료되면 해당 제품은 "보안 수정 또는 기술 지원"을 받을 수 없습니다. 대부분의 가정용 장치는 Windows 업데이트를 통해 최신 상태로 유지됩니다. 이러한 장치에는 .NET Framework 4.8과 같은 최신 버전의 프레임워크가 이미 설치되어 있습니다. 자동으로 업데이트되지 않는 장치는
!['[Vue 경고]: 필터를 확인하지 못했습니다' 오류 해결 방법](https://img.php.cn/upload/article/000/887/227/169243040583797.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
"[Vuewarn]:Failedtoresolvefilter" 오류를 해결하는 방법 Vue를 사용하여 개발 프로세스를 진행하는 동안 "[Vuewarn]:Failedtoresolvefilter"라는 오류 메시지가 나타나는 경우가 있습니다. 이 오류 메시지는 일반적으로 템플릿에서 정의되지 않은 필터를 사용할 때 발생합니다. 이 문서에서는 이 오류를 해결하는 방법을 설명하고 해당 코드 예제를 제공합니다. 우리가 Vue에 있을 때

Windows 11용 KB5012643을 설치한 사용자에게 영향을 미치는 새로운 안전 모드 버그에 대해 이야기한 지 일주일이 지났습니다. 이 성가신 문제는 Microsoft가 출시일에 게시한 알려진 문제 목록에 나타나지 않아 모두를 놀라게 했습니다. 글쎄, 상황이 더 이상 악화될 수 없다고 생각했을 때 Microsoft는 이 누적 업데이트를 설치한 사용자에게 또 다른 폭탄을 떨어뜨렸습니다. Windows 11 빌드 22000.652로 인해 더 많은 문제 발생 따라서 기술 회사는 Windows 11 사용자에게 일부 .NET Framework 3.5 응용 프로그램을 시작하고 사용하는 데 문제가 발생할 수 있다고 경고합니다. 익숙한 것 같나요? 하지만 놀라지 마세요.

Vue 오류: 필터의 필터를 올바르게 사용할 수 없습니다. 어떻게 해결합니까? 소개: Vue에서 필터는 데이터 형식을 지정하거나 필터링하는 데 사용할 수 있는 일반적으로 사용되는 기능입니다. 하지만 사용 중에 필터를 제대로 사용하지 못하는 문제가 발생할 수 있습니다. 이 문서에서는 몇 가지 일반적인 원인과 해결 방법을 다룹니다. 1. 원인 분석: 필터가 올바르게 등록되지 않았습니다. Vue의 필터를 템플릿에서 사용하려면 먼저 등록해야 합니다. 필터가 성공적으로 등록되지 않은 경우,

클라우드 컴퓨팅 기술이 지속적으로 발전하면서 데이터 백업은 모든 기업이 반드시 해야 할 일이 되었습니다. 이러한 맥락에서 가용성이 높은 클라우드 백업 시스템을 개발하는 것이 특히 중요합니다. PHP 프레임워크 Yii는 개발자가 고성능 웹 애플리케이션을 빠르게 구축하는 데 도움이 되는 강력한 프레임워크입니다. 다음은 Yii 프레임워크를 사용하여 고가용성 클라우드 백업 시스템을 개발하는 방법을 소개합니다. 데이터베이스 모델 설계 Yii 프레임워크에서 데이터베이스 모델은 매우 중요한 부분입니다. 데이터 백업 시스템에는 많은 테이블과 관계가 필요하기 때문에
