当前位置: 首页 > 编程文章 >

Yii Framework 过滤器 Filter 用法详解

Yii Framework 过滤器 Filter 用法详解

作者:许禾时间:2025-09-02 16:32:28浏览:514

Yii Framework 的过滤器(Filter)是一段可在控制器动作执行前后运行的代码,常用于身份验证或性能监控。通过覆盖 CController::filters() 方法返回配置数组,可基于方法或类实例定义过滤器。利用加减号前缀可精确指定过滤器适用的动作范围,其执行遵循链式结构,支持在 preFilter 和 postFilter 阶段介入逻辑处理。

本文目录展开

Yii Framework 过滤器 Filter 用法详解

本文详细解析 Yii Framework 中过滤器的使用机制,旨在为开发者提供实用的参考指南。

首先查阅官方文档,了解过滤器的基本概念、功能作用、规则设定及定义方式。

随后对过滤器的核心特性进行系统性总结。

参考官方文档地址: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,可初始化其属性值,此处 unit 属性将被初始化为 second。

使用加减号前缀可指定过滤器适用的动作范围。在上述代码中,postOnly 仅应用于 edit 和 create 动作,而 PerformanceFilter 应用于除 edit 和 create 之外的所有动作。若未使用加减号,则该过滤器将作用于所有动作。

过滤器的主要功能包括:

对访问者和数据进行过滤,并记录访问操作日志。

具体使用方法分为两种:

一、作为 Controller 的一个方法,方法名必须以 filter 开头。


public function filterAccessControl($filterChain)
{ 
echo "--->filterAccessControl";
  $filterChain->run();
}

二、定义独立的 Filter 类,该类必须继承自 CFilter。

CFilter 基类提供了 preFilter 和 postFilter 等保护方法供重写。


<?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  
 * @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 $filterChain->run() 
   * 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 框架的 PHP 程序设计有所帮助。

上一篇
AngularJS $http POST请求PHP无法接收数据的解决方案

在使用AngularJS v1.5.0-rc.0与PHP开发时,常遇到PHP后台无法通过$_POST接收前端POST数据的问题。这是因为jQuery默认将数据序列化为application/x-www-form-urlencoded格式的字符串,而AngularJS默认发送JSON格式数据。PHP的$_POST仅能解析表单编码数据。可通过引入jQuery序列化参数、使用file_get_contents("php://input")手动解析或修改$httpProvider默认Header三种方式解决。

下一篇
解决XML命名空间导致XPath查询失效的问题 (C#与PHP)

在使用XPath获取XML文档数据时,若节点包含XMLNS属性定义的命名空间,直接编写路径表达式将返回空结果。本文以获取歌曲标题为例,说明如何通过C#的XmlNamespaceManager和PHP的registerXPathNamespace方法注册命名空间前缀,从而正确解析带命名空间的XML结构。

相关文章

更多
Yii框架结合CKEditor实现自定义图片上传功能

本文介绍如何在 Yii Framework 中为 CKEditor 配置并实现自定义图片上传功能。通过设置 filebrowserImageUploadUrl 属性指向控制器动作,利用 CUploadedFile 处理文件保存,并返回符合 CKEditor 规范的回调 HTML,即可在不依赖 CKFinder 的情况下完成图片预览与插入。

2026.08.08 647

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。