>  기사  >  php教程  >  Zend Framework 필터 Zend_Filter 사용법에 대한 자세한 설명

Zend Framework 필터 Zend_Filter 사용법에 대한 자세한 설명

高洛峰
高洛峰원래의
2017-01-06 09:39:161262검색

이 기사의 예에서는 Zend Framework 필터 Zend_Filter의 사용법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

소개: 필터는 입력된 콘텐츠를 필터링하고, 필터링 규칙을 충족하지 않는 콘텐츠를 제거하고, 나머지 콘텐츠를 반환하는 프로세스입니다.

Zend에는 필터링 기능을 구현하는 Zend_Filter 컴포넌트가 있습니다. 일반 필터를 구현하기 위한 인터페이스를 제공하는 Zend_Filter_Interface 하위 클래스가 있습니다.

필터 클래스를 구현하려면 이 인터페이스에 filter()라는 메서드를 구현해야 합니다.

다음은 Zend_Filter에 정의된 필터를 사용하는 방법을 예시를 통해 보여줍니다. 이 예시는 문자를 소문자로 변환하는 기능을 구현하는 방법을 보여줍니다.

코드:

<?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);

결과:

콘텐츠: ABCDefGH
필터링 후: abcdefgh
내용: 난징을 사랑해요
필터링 후: 난징을 사랑해요

왜 이렇게 마법 같은 걸까요? 내부 구조를 탐구하고 싶게 만드네요! 내부 작동 원리를 연구해 보겠습니다.

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

연구:

소스 코드의 의미는 아마도 Zend_Filter_Interface 인터페이스를 먼저 구현하는 것일 것입니다.

개인 변수 $_encoding을 정의합니다. 초기 값은 null입니다. 일반적으로 개인 변수는 _underscore로 시작합니다.

그런 다음 생성자를 통해 초기화 작업을 수행하고 인코딩을 설정합니다.

이 인코딩 속성의 목적은 정확히 모르겠습니다. 어쨌든 소스 코드에는 많은 코드가 작성되어 있습니다.

클래스에는 세 가지 메소드가 있는데, 하나는 setEncoding, 하나는 getEncoding, 주요 기능은 필터입니다. 인코딩을 위해 작성된 두 가지 방법이 있습니다.

생성자에서 setEncoding 메소드를 사용하려면 $this->setEncoding()을 사용하면 됩니다. 그런 다음 개인 속성의 값을 설정할 수 있습니다.

그런 다음 private 속성의 내용에 따라 문자를 소문자로 만드는 데 사용할 방법을 선택합니다.

놔두세요, 이 카테고리에는 고려할 사항이 정말 충분합니다. 실제로 핵심 코드는 strtolower((string) $value)라는 두 문장뿐입니다.

이 수업은 멋지네요. 저는 사유 재산을 절대 사용하지 않습니다. 고려된 문제는 저자의 문제만큼 포괄적이지 않으며 다양한 검증과 다양한 상황이 고려됩니다. 예를 들어

생성자가 문제를 얼마나 포괄적으로 고려하는지를 보면 알 수 있습니다.

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;]);
}

전체적으로 감탄할만합니다.

필터 체인에 대해 이야기해 보겠습니다. 그 기능은 여러 필터를 직렬로 연결하여 함께 사용하는 것입니다. 필터 체인은 여러 필터를 연결한 것입니다. 지정된 콘텐츠를 필터링할 때

각 필터는 순서대로 필터링 또는 변환 작업을 수행합니다. 모든 필터링 작업이 완료되면 필터 체인은 최종 필터링된 결과를 반환합니다.

재밌을 것 같네요!

구체적인 구현 단계는 무엇입니까?

먼저 Zend_Filter 클래스에 대한 개체를 인스턴스화한 다음 인스턴스의 addFilter() 메서드를 통해 필터 체인에 필터를 추가합니다.

다음 예에서는 필터 체인을 사용하여 데이터의 다중 필터링 및 변환을 수행하는 방법을 보여줍니다.

코드:

<?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>";

결과:

콘텐츠: 12345asdf67asdfasdf
필터링 후: ASDFASDFASDF
내용: #$%^!@fffff
필터링 후 결과: FFFFF
내용: Welcome to Bei Jing
필터링 후 결과: WELCOME TO BEI JING

분석:

여기의 알파는 매우 강력합니다. 숫자와 특수 문자는 물론 공백까지 필터링할 수 있습니다. 다행스럽게도 초기화 중에 " " 매개변수를 추가하여 공백이 유지되었습니다.

왜 이렇게 마법 같은 걸까요?

핵심 코드입니다

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

분석: 여기서 내용이 필터링되면 문자나 공백이 아닌 경우 모두 필터링됩니다. 제거됩니다. 사용된 PHP 메소드는 preg_replace입니다. 또한 정규 표현식이 사용됩니다. [^a-zA-Z]는 이 이외의 다른 문자를 나타냅니다.

여기서 $whiteSpace 멤버 속성은 초기화 중에 설정됩니다. 구체적인 코드는 다음과 같습니다.

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

two 공백 허용 여부를 설정하고 공백 허용 여부를 가져오는 메서드입니다.

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

분석해 보니 일반 필터링만 사용하는 것만으로도 구조가 더 잘 이해되는 것 같습니다. 동시에, AllowWhiteSpace 속성은 공간 필터링 여부를 제어하는 ​​데 사용됩니다.

방금 두 개의 필터를 소개했는데, 하나는 StringToUpper이고 다른 하나는 Alpha입니다.

첫 번째는 숫자와 문자가 아닌 콘텐츠를 필터링하는 Alnum입니다. filter() 메서드를 실행하면 순수한 숫자와 문자 콘텐츠가 반환됩니다. 이는 Zend_Filter_Alpha(문자가 아닌 필터링)와 Zend_Filter_Digits의 조합입니다. (숫자가 아닌 값 필터링) 결합.

구체적인 예를 들진 않겠습니다. 모두 비슷합니다.

내부 구조를 살펴보겠습니다.

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

정규식을 통해 문자, 숫자 이외의 내용을 필터링합니다.

다음은 HtmlEntities HTML 필터입니다.

코드:

<?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>";

결과:

Zend Framework过滤器Zend_Filter用法详解

결과를 통해 html 콘텐츠를 원본 코드로 복원하는 것을 확인할 수 있습니다. 이 필터는 htmlentities 함수를 캡슐화한 것이므로 이 함수의 규칙을 따릅니다. 즉, "8c151ce0f2c54695a0a3e047cb5d0d3d"를 각각 ">"로 변환하면

의 해당 HTML 콘텐츠가 원래 형식으로 표시됩니다.

이 기사가 Zend Framework 프레임워크를 기반으로 하는 모든 사람의 PHP 프로그래밍에 도움이 되기를 바랍니다.

Zend Framework 필터 Zend_Filter 사용법에 대한 자세한 설명은 PHP 중국어 홈페이지를 참고해주세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.