Home  >  Article  >  php教程  >  Detailed explanation of Zend Framework filter Zend_Filter usage

Detailed explanation of Zend Framework filter Zend_Filter usage

高洛峰
高洛峰Original
2017-01-06 09:39:161260browse

The example in this article describes the usage of Zend Framework filter Zend_Filter. Share it with everyone for your reference, the details are as follows:

Introduction: Filter is the process of filtering the input content, removing the content that does not meet the filtering rules, and returning the remaining content.

There is a Zend_Filter component in Zend to implement the filtering function. There is a Zend_Filter_Interface subclass, which provides an interface for implementing general filters.

To implement the filter class, you need to implement a method named filter() in this interface.

The following uses an example to demonstrate how to use the filter defined in Zend_Filter. This example demonstrates how to implement the function of converting letters to lowercase.

Code:

<?php
require_once &#39;Zend/Filter/StringToLower.php&#39;;  //加载子类
$filter = new Zend_Filter_StringToLower;    //实例化对象
$temp1 = "ABCDefGH";              //定义待过滤内容
$temp2 = "我爱Nan Jing";
echo "内容:".$temp1."<p>经过滤后为:";
echo $filter->filter($temp1);
echo "<p>";
echo "内容:".$temp2."<p>经过滤后为:";
echo $filter->filter($temp2);

Result:

Content: ABCDefGH
After filtering: abcdefgh
Content: I love Nan Jing
After filtering: I love nan jing

Why is it so magical? It makes me want to explore its internal structure! Let’s study its internal working principle.

class Zend_Filter_StringToLower implements Zend_Filter_Interface
{
  /**
   * Encoding for the input string
   *
   * @var string
   */
  protected $_encoding = null;
  /**
   * Constructor
   *
   * @param string|array|Zend_Config $options OPTIONAL
   */
  public function __construct($options = null)
  {
    if ($options instanceof Zend_Config) {
      $options = $options->toArray();
    } else if (!is_array($options)) {
      $options = func_get_args();
      $temp  = array();
      if (!empty($options)) {
        $temp[&#39;encoding&#39;] = array_shift($options);
      }
      $options = $temp;
    }
    if (!array_key_exists(&#39;encoding&#39;, $options) && function_exists(&#39;mb_internal_encoding&#39;)) {
      $options[&#39;encoding&#39;] = mb_internal_encoding();
    }
    if (array_key_exists(&#39;encoding&#39;, $options)) {
      $this->setEncoding($options[&#39;encoding&#39;]);
    }
  }
  /**
   * Returns the set encoding
   *
   * @return string
   */
  public function getEncoding()
  {
    return $this->_encoding;
  }
  /**
   * Set the input encoding for the given string
   *
   * @param string $encoding
   * @return Zend_Filter_StringToLower Provides a fluent interface
   * @throws Zend_Filter_Exception
   */
  public function setEncoding($encoding = null)
  {
    if ($encoding !== null) {
      if (!function_exists(&#39;mb_strtolower&#39;)) {
        require_once &#39;Zend/Filter/Exception.php&#39;;
        throw new Zend_Filter_Exception(&#39;mbstring is required for this feature&#39;);
      }
      $encoding = (string) $encoding;
      if (!in_array(strtolower($encoding), array_map(&#39;strtolower&#39;, mb_list_encodings()))) {
        require_once &#39;Zend/Filter/Exception.php&#39;;
        throw new Zend_Filter_Exception("The given encoding &#39;$encoding&#39; is not supported by mbstring");
      }
    }
    $this->_encoding = $encoding;
    return $this;
  }
  /**
   * Defined by Zend_Filter_Interface
   *
   * Returns the string $value, converting characters to lowercase as necessary
   *
   * @param string $value
   * @return string
   */
  public function filter($value)
  {
    if ($this->_encoding !== null) {
      return mb_strtolower((string) $value, $this->_encoding);
    }
    return strtolower((string) $value);
  }
}

Study:

The meaning of the source code is probably to implement the Zend_Filter_Interface interface first.

Define a private variable $_encoding. The initial value is null. Generally, private variables start with _underscore.

Then perform initialization work through the constructor and set the encoding.

As for the purpose of this encoding attribute, I don't know clearly. Anyway, a lot of source code has been written for it.

There are three methods in the class, one is setEncoding, one is getEncoding, and a main function filter. There are two methods written for encoding.

To use the setEncoding method in the constructor, just use $this->setEncoding(). Then you can set the value of the private attribute.

Then choose what method to use to make letters lowercase based on the content of the private attribute.

Let me go, there are really enough things to consider in this category. In fact, the core code is just those two sentences, strtolower((string) $value).

This class is cool, I have never used private properties. The issues considered are not as comprehensive as the author's, with various verifications and various situations considered. For example,

You can see from the constructor how comprehensively he considers the problem.

if ($options instanceof Zend_Config) {
  $options = $options->toArray();
} else if (!is_array($options)) {
  $options = func_get_args();
  $temp  = array();
  if (!empty($options)) {
    $temp[&#39;encoding&#39;] = array_shift($options);
  }
  $options = $temp;
}
if (!array_key_exists(&#39;encoding&#39;, $options) && function_exists(&#39;mb_internal_encoding&#39;)) {
  $options[&#39;encoding&#39;] = mb_internal_encoding();
}
if (array_key_exists(&#39;encoding&#39;, $options)) {
  $this->setEncoding($options[&#39;encoding&#39;]);
}

Generally speaking, it is worthy of admiration.

Let’s talk about the filter chain. Its function is to connect multiple filters in series and use them together. A filter chain is a connection of multiple filters. When filtering the specified content,

Each filter will perform filtering or conversion operations in its order. When all filtering operations are completed, the filter chain returns the final filtered results.

Sounds interesting!

What are the specific implementation steps?

First instantiate an object for the class Zend_Filter, and then add a filter to the filter chain through the addFilter() method of the instance.

The following example demonstrates how to use filter chains to perform multiple filtering and transformation of data.

Code:

<?php
require_once &#39;Zend/Filter.php&#39;;         //加载Zend_Filter类
require_once &#39;Zend/Filter/Alpha.php&#39;;      //加载Zend_Filter_Alpha子类
require_once &#39;Zend/Filter/StringToUpper.php&#39;;  //加载Zend_Filter_StringToUpper子类
$filterChain = new Zend_Filter();        //创建过滤器链
$filterChain ->addFilter(new Zend_Filter_Alpha(" "))
  ->addFilter(new Zend_Filter_StringToUpper());//向过滤器链中添加过滤器
$temp1 = "12345asdf67asdfasdf";
$temp2 = "#$%^!@fffff";
$temp3 = "Welcome to Bei Jing";
echo "内容:".$temp1."<p>经过过滤后为:";
echo $filterChain->filter($temp1);
echo "<p>";
echo "内容:".$temp2."<p>经过过滤后为:";
echo $filterChain->filter($temp2);
echo "<p>";
echo "内容:".$temp3."<p>经过过滤后为:";
echo $filterChain->filter($temp3);
echo "<p>";

Result:

Content: 12345asdf67asdfasdf
After filtering: ASDFASDFASDF
Content: #$%^!@fffff
After filtering, it is: FFFFF
Content: Welcome to Bei Jing
After filtering, it is: WELCOME TO BEI JING

Analysis:

The Alpha here is very powerful. It can filter numbers and special characters, even spaces. Fortunately, I added a parameter " " during initialization, so that the spaces were retained.

Why is it so magical?

This is the core code

public function filter($value)
{
    $whiteSpace = $this->allowWhiteSpace ? &#39;\s&#39; : &#39;&#39;;
    if (!self::$_unicodeEnabled) {
      // POSIX named classes are not supported, use alternative a-zA-Z match
      $pattern = &#39;/[^a-zA-Z&#39; . $whiteSpace . &#39;]/&#39;;
    } else if (self::$_meansEnglishAlphabet) {
      //The Alphabet means english alphabet.
      $pattern = &#39;/[^a-zA-Z&#39; . $whiteSpace . &#39;]/u&#39;;
    } else {
      //The Alphabet means each language&#39;s alphabet.
      $pattern = &#39;/[^\p{L}&#39; . $whiteSpace . &#39;]/u&#39;;
    }
    return preg_replace($pattern, &#39;&#39;, (string) $value);
}

Analysis: The content is filtered here. If it is not letters or spaces, all will be removed. The php method used is preg_replace. In addition, regular expressions are used. [^a-zA-Z] represents other characters besides this.

The $whiteSpace member attribute here is set during initialization. The specific code is as follows:

public function __construct($allowWhiteSpace = false)
{
    if ($allowWhiteSpace instanceof Zend_Config) {
      $allowWhiteSpace = $allowWhiteSpace->toArray();
    } else if (is_array($allowWhiteSpace)) {
      if (array_key_exists(&#39;allowwhitespace&#39;, $allowWhiteSpace)) {
        $allowWhiteSpace = $allowWhiteSpace[&#39;allowwhitespace&#39;];
      } else {
        $allowWhiteSpace = false;
      }
    }
    $this->allowWhiteSpace = (boolean) $allowWhiteSpace;
    if (null === self::$_unicodeEnabled) {
      self::$_unicodeEnabled = (@preg_match(&#39;/\pL/u&#39;, &#39;a&#39;)) ? true : false;
    }
    if (null === self::$_meansEnglishAlphabet) {
      $this->_locale = new Zend_Locale(&#39;auto&#39;);
      self::$_meansEnglishAlphabet = in_array($this->_locale->getLanguage(),
      array(&#39;ja&#39;, &#39;ko&#39;, &#39;zh&#39;)
      );
    }
}

In addition, there are two methods To set whether spaces are allowed and to get whether spaces are allowed.

/**
* Returns the allowWhiteSpace option
*
* @return boolean
*/
public function getAllowWhiteSpace()
{
    return $this->allowWhiteSpace;
}
/**
* Sets the allowWhiteSpace option
*
* @param boolean $allowWhiteSpace
* @return Zend_Filter_Alpha Provides a fluent interface
*/
public function setAllowWhiteSpace($allowWhiteSpace)
{
    $this->allowWhiteSpace = (boolean) $allowWhiteSpace;
    return $this;
}

After analyzing it, we seem to have a better understanding of its structure, which is just using regular filtering. At the same time, the attribute allowWhiteSpace is used to control whether to filter spaces.

I just introduced two filters, one is StringToUpper and the other is Alpha. Here are some other filters.

The first is Alnum, which filters non-numeric and non-letter content. Executing the filter() method will return pure numeric and letter content. It is the combination of Zend_Filter_Alpha (filtering non-letters) and Zend_Filter_Digits (filtering non-numeric values) Union.

I won’t give specific examples, they are all similar.

Let’s take a look at its internal structure,

public function filter($value)
{
    $whiteSpace = $this->allowWhiteSpace ? &#39;\s&#39; : &#39;&#39;;
    if (!self::$_unicodeEnabled) {
      // POSIX named classes are not supported, use alternative a-zA-Z0-9 match
      $pattern = &#39;/[^a-zA-Z0-9&#39; . $whiteSpace . &#39;]/&#39;;
    } else if (self::$_meansEnglishAlphabet) {
      //The Alphabet means english alphabet.
      $pattern = &#39;/[^a-zA-Z0-9&#39; . $whiteSpace . &#39;]/u&#39;;
    } else {
      //The Alphabet means each language&#39;s alphabet.
      $pattern = &#39;/[^\p{L}\p{N}&#39; . $whiteSpace . &#39;]/u&#39;;
    }
    return preg_replace($pattern, &#39;&#39;, (string) $value);
}

Filters content other than letters and numbers through regular rules.

The following is the HtmlEntities HTML filter.

Code:

<?php
require_once &#39;Zend/Filter/Htmlentities.php&#39;;
$filter = new Zend_Filter_HtmlEntities();
$temp1 = "<img src = &#39;./1.png&#39; width=&#39;100px&#39;>";
$temp2 = "<button>aaa</button>";
$temp3 = "<h1>Welcome to Bei Jing</h1>";
echo "内容:".$temp1."<p>经过过滤为:";
echo $filter->filter($temp1);
echo "<p>";
echo "内容:".$temp2."<p>经过过滤为:";
echo $filter->filter($temp2);
echo "<p>";
echo "内容:".$temp3."<p>经过过滤为:";
echo $filter->filter($temp3);
echo "<p>";

Result:

Zend Framework过滤器Zend_Filter用法详解

Through the results, we can see that it restores the html content to the original code. Since this filter is an encapsulation of the function htmlentities, it follows the rules of this function. That is, convert "d21bf6265d53cdd4dcff18f6785f8fb4" into "d21bf6265d53cdd4dcff18f6785f8fb4" respectively. After such conversion,

the corresponding HTML content becomes a string displayed in its original format. .

I hope this article will be helpful to everyone’s PHP programming based on the Zend Framework framework.

For more detailed usage of Zend Framework filter Zend_Filter and related articles, please pay attention to the PHP Chinese website!

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