Home Backend Development PHP Tutorial YII Framework的filter过滤器用法分析_php实例

YII Framework的filter过滤器用法分析_php实例

Jun 07, 2016 pm 05:08 PM
filter framework yii filter

本文实例讲述了YII Framework的filter过滤器用法。分享给大家供大家参考,具体如下:

首先看官方给出的说明文档,什么是过滤器,过滤器的作用,过滤器的规则,过滤器的定义方法等等。

然后对过滤器进行一个总结。

http://www.yiiframework.com/doc/guide/1.1/zh_cn/basics.controller

过滤器是一段代码,可被配置在控制器动作执行之前或之后执行。例如, 访问控制过滤器将被执行以确保在执行请求的动作之前用户已通过身份验证;性能过滤器可用于测量控制器执行所用的时间。

一个动作可以有多个过滤器。过滤器执行顺序为它们出现在过滤器列表中的顺序。过滤器可以阻止动作及后面其他过滤器的执行

过滤器可以定义为一个控制器类的方法。方法名必须以 filter 开头。例如,现有的 filterAccessControl 方法定义了一个名为 accessControl 的过滤器。 过滤器方法必须为如下结构:

public function filterAccessControl($filterChain)
{
  // 调用 $filterChain->run() 以继续后续过滤器与动作的执行。
}

Copy after login

其中的 $filterChain (过滤器链)是一个 CFilterChain 的实例,代表与所请求动作相关的过滤器列表。在过滤器方法中, 我们可以调用 $filterChain->run() 以继续执行后续过滤器和动作。

过滤器也可以是一个 CFilter 或其子类的实例。如下代码定义了一个新的过滤器类:

class PerformanceFilter extends CFilter
{
  protected function preFilter($filterChain)
  {
    // 动作被执行之前应用的逻辑
    return true; // 如果动作不应被执行,此处返回 false
  }
  protected function postFilter($filterChain)
  {
    // 动作执行之后应用的逻辑
  }
}

Copy after login

要对动作应用过滤器,我们需要覆盖 CController::filters() 方法。此方法应返回一个过滤器配置数组。例如:

class PostController extends CController
{
  ......
  public function filters()
  {
    return array(
      'postOnly + edit, create',
      array(
        'application.filters.PerformanceFilter - edit, create',
        'unit'=>'second',
      ),
    );
  }
}

Copy after login

上述代码指定了两个过滤器: 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();
}

Copy after login

二定义对立的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) 
  { 
  } 
}

Copy after login

下面举例说明两种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"; 
  } 

Copy after login

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

Copy after login

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',
    ),
  );
}

Copy after login

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 of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Microsoft NET Framework Installation Issues Error Code 0x800c0006 Fix Microsoft NET Framework Installation Issues Error Code 0x800c0006 Fix May 05, 2023 pm 04:01 PM

.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

How to identify Windows upgrade issues using SetupDiag on Windows 11/10 How to identify Windows upgrade issues using SetupDiag on Windows 11/10 Apr 17, 2023 am 10:07 AM

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.

SCNotification has stopped working [5 steps to fix it] SCNotification has stopped working [5 steps to fix it] May 17, 2023 pm 09:35 PM

As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

Microsoft .NET Framework 4.5.2, 4.6, and 4.6.1 will end support in April 2022 Microsoft .NET Framework 4.5.2, 4.6, and 4.6.1 will end support in April 2022 Apr 17, 2023 pm 02:25 PM

Microsoft Windows users who have installed Microsoft.NET version 4.5.2, 4.6, or 4.6.1 must install a newer version of the Microsoft Framework if they want Microsoft to support the framework through future product updates. According to Microsoft, all three frameworks will cease support on April 26, 2022. After the support date ends, the product will not receive "security fixes or technical support." Most home devices are kept up to date through Windows updates. These devices already have newer versions of frameworks installed, such as .NET Framework 4.8. Devices that are not updating automatically may

How to solve the '[Vue warn]: Failed to resolve filter' error How to solve the '[Vue warn]: Failed to resolve filter' error Aug 19, 2023 pm 03:33 PM

Methods to solve the "[Vuewarn]:Failedtoresolvefilter" error During the development process using Vue, we sometimes encounter an error message: "[Vuewarn]:Failedtoresolvefilter". This error message usually occurs when we use an undefined filter in the template. This article explains how to resolve this error and gives corresponding code examples. When we are in Vue

KB5012643 for Windows 11 breaks .NET Framework 3.5 apps KB5012643 for Windows 11 breaks .NET Framework 3.5 apps May 09, 2023 pm 01:07 PM

It's been a week since we talked about the new safe mode bug affecting users who installed KB5012643 for Windows 11. This pesky issue didn't appear on the list of known issues Microsoft posted on launch day, thus catching everyone by surprise. Well, just when you thought things couldn't get any worse, Microsoft drops another bomb for users who have installed this cumulative update. Windows 11 Build 22000.652 causes more problems So the tech company is warning Windows 11 users that they may experience problems launching and using some .NET Framework 3.5 applications. Sound familiar? But please don't be surprised

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

Vue error: The filter in filters cannot be used correctly, how to solve it? Vue error: The filter in filters cannot be used correctly, how to solve it? Aug 26, 2023 pm 01:10 PM

Vue error: The filter in filters cannot be used correctly, how to solve it? Introduction: In Vue, filters are a commonly used function that can be used to format or filter data. However, during use, sometimes we may encounter problems with not being able to use the filter correctly. This article will cover some common causes and solutions. 1. Cause analysis: The filter is not registered correctly: Filters in Vue need to be registered before they can be used in templates. If the filter is not successfully registered,

See all articles