search
HomeBackend DevelopmentPHP TutorialYII Framework的filter过滤器用法分析_php实例

本文实例讲述了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

<&#63;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

<&#63;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

<&#63;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程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在 Windows 11/10 上使用 SetupDiag 识别 Windows 升级问题如何在 Windows 11/10 上使用 SetupDiag 识别 Windows 升级问题Apr 17, 2023 am 10:07 AM

每当您的Windows11或Windows10PC出现升级或更新问题时,您通常会看到一个错误代码,指示故障背后的实际原因。但是,有时,升级或更新失败可能不会显示错误代码,这时就会出现混淆。有了方便的错误代码,您就可以确切地知道问题出在哪里,因此您可以尝试修复。但是由于没有出现错误代码,因此识别问题并解决它变得极具挑战性。这会占用您大量时间来简单地找出错误背后的原因。在这种情况下,您可以尝试使用Microsoft提供的名为SetupDiag的专用工具,该工具可帮助您轻松识别错误背后的真

Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Apr 17, 2023 pm 02:25 PM

已安装Microsoft.NET版本4.5.2、4.6或4.6.1的MicrosoftWindows用户如果希望Microsoft将来通过产品更新支持该框架,则必须安装较新版本的Microsoft框架。据微软称,这三个框架都将在2022年4月26日停止支持。支持日期结束后,产品将不会收到“安全修复或技术支持”。大多数家庭设备通过Windows更新保持最新。这些设备已经安装了较新版本的框架,例如.NETFramework4.8。未自动更新的设备可能

php如何使用Yii3框架?php如何使用Yii3框架?May 31, 2023 pm 10:42 PM

随着互联网的不断发展,Web应用程序开发的需求也越来越高。对于开发人员而言,开发应用程序需要一个稳定、高效、强大的框架,这样可以提高开发效率。Yii是一款领先的高性能PHP框架,它提供了丰富的特性和良好的性能。Yii3是Yii框架的下一代版本,它在Yii2的基础上进一步优化了性能和代码质量。在这篇文章中,我们将介绍如何使用Yii3框架来开发PHP应用程序。

如何使用PHP框架Yii开发一个高可用的云备份系统如何使用PHP框架Yii开发一个高可用的云备份系统Jun 27, 2023 am 09:04 AM

随着云计算技术的不断发展,数据的备份已经成为了每个企业必须要做的事情。在这样的背景下,开发一款高可用的云备份系统尤为重要。而PHP框架Yii是一款功能强大的框架,可以帮助开发者快速构建高性能的Web应用程序。下面将介绍如何使用Yii框架开发一款高可用的云备份系统。设计数据库模型在Yii框架中,数据库模型是非常重要的一部分。因为数据备份系统需要用到很多的表和关

Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Yii2 vs Phalcon:哪个框架更适合开发显卡渲染应用?Jun 19, 2023 am 08:09 AM

在当前信息时代,大数据、人工智能、云计算等技术已经成为了各大企业关注的热点。在这些技术中,显卡渲染技术作为一种高性能图形处理技术,受到了越来越多的关注。显卡渲染技术被广泛应用于游戏开发、影视特效、工程建模等领域。而对于开发者来说,选择一个适合自己项目的框架,是一个非常重要的决策。在当前的语言中,PHP是一种颇具活力的语言,一些优秀的PHP框架如Yii2、Ph

Yii框架中的数据查询:高效地访问数据Yii框架中的数据查询:高效地访问数据Jun 21, 2023 am 11:22 AM

Yii框架是一个开源的PHPWeb应用程序框架,提供了众多的工具和组件,简化了Web应用程序开发的流程,其中数据查询是其中一个重要的组件之一。在Yii框架中,我们可以使用类似SQL的语法来访问数据库,从而高效地查询和操作数据。Yii框架的查询构建器主要包括以下几种类型:ActiveRecord查询、QueryBuilder查询、命令查询和原始SQL查询

Symfony vs Yii2:哪个框架更适合开发大型Web应用?Symfony vs Yii2:哪个框架更适合开发大型Web应用?Jun 19, 2023 am 10:57 AM

随着Web应用需求的不断增长,开发者们在选择开发框架方面也越来越有选择的余地。Symfony和Yii2是两个备受欢迎的PHP框架,它们都具有强大的功能和性能,但在面对需要开发大型Web应用时,哪个框架更适合呢?接下来我们将对Symphony和Yii2进行比较分析,以帮助你更好地进行选择。基本概述Symphony是一个由PHP编写的开源Web应用框架,它是建立

yii如何将对象转化为数组或直接输出为json格式yii如何将对象转化为数组或直接输出为json格式Jan 08, 2021 am 10:13 AM

yii框架:本文为大家介绍了yii将对象转化为数组或直接输出为json格式的方法,具有一定的参考价值,希望能够帮助到大家。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.