A free and open-source book on Zend Framework for beginners


8.3. Instantiating a Filter

In Zend Framework 3, you can use several methods of creating a filter:

Next, we will cover these three methods in more details.

8.3.1. Method 1: Instantiating a Filter Manually

As we previously said, a filter in general can be used not only with forms but also for filtering an arbitrary data. To do that, you simply create an instance of the filter class, configure the filter by using the methods it provides, and call the filter() method on the filter.

For example, let's consider the usage of the StringTrim filter which removes the white space characters from the beginning and the end of a string.

The StringTrim filter is useful for filtering user-entered string data (E-mail addresses, user names, etc.) because site visitors tend to make typos in those data. For example, a user may unintentionally enter a trailing space in an E-mail field, thus making an E-mail invalid. With the StringTrim filter, you will easily cope with such input errors and improve user experience.

The methods provided by the filter are listed in table 8.2:

Table 8.2. Public methods of the StringTrim filter
Method name Description
__construct($charlistOrOptions) Constructs the filter. Accepts the list of options.
filter($value) Removes the predefined characters from the beginning and the end of the string.
setCharList($charList) Defines the list of characters to strip off.
getCharList() Returns the list of characters to strip off.

As you can see from the table, the StringTrim filter, in addition to the filter() method, provides the constructor method which you can (optionally) pass with the complete list of options to initialize the filter, and the setCharList() and getCharList() methods which can be used for setting specific filter options.

All standard filters have the constructor method (optionally) accepting an array of options for configuring the filter when instantiating it manually.

Below, we provide two code examples showing equivalent methods of manually creating an instance of the StringTrim filter, setting its options, and filtering a value.

Example 1. Passing options to the constructor method.

<?php
// Optionally, define a short alias for the filter class name.
use Zend\Filter\StringTrim;

// Create an instance of the filter, passing options to the constructor.
$filter = new StringTrim(['charlist'=>"\r\n\t "]);

// Perform the trimming operation on the string.
$filteredValue = $filter->filter(' name@example.com  ');

// The expected output of the filter is the 'name@example.com' string.

In the code above, we create the StringTrim filter object with the help of the new operator (line 6). We pass the array of options to the constructor to set the list of characters the filter will remove (here, we tell the filter to remove the new line characters, the tabulation character, and the space character). Actually, passing the array of options to this filter can be omitted because the filter already has some default character list to strip off.

In line 9, we call the filter() method and pass it the string value " name@example.com " to be trimmed. The expected output of this call is the "name@example.com" string.

Example 2. Without passing options to the constructor.

<?php
// Optionally, define a short alias for the filter class name.
use Zend\Filter\StringTrim;

// Create an instance of the filter.
$filter = new StringTrim();

// Specify which characters to remove.
$filter->setCharList("\r\n\t ");

// Perform the trimming operation on the string
$filteredValue = $filter->filter(' name@example.com  ');

// The expected output of the filter is the 'name@example.com' string

In the code above, we create the StringTrim filter object with the help of the new operator (line 6).

In line 9, we (optionally) call the StringTrim filter's setCharList() method to set the list of characters the filter will remove (here, we tell the filter to remove the new line characters, the tabulation character, and the space character). This call is optional because the filter already has some default character list for stripping off.

And, in line 12, we call the filter() method and pass it the string value " name@example.com " to be trimmed. The expected output of this call is the "name@example.com" string.

8.3.2. Method 2: Constructing a Filter with StaticFilter

An alternative way of manual filter instantiation is by using the StaticFilter class. The StaticFilter class is some kind of a "proxy" designed for automatic filter instantiation, configuration, and execution. For example, let's consider how to create the same StringTrim filter, configure it, and call its filter() method:

<?php
// Create and execute the StringTrim filter through the StaticFilter proxy.
$filteredValue = \Zend\Filter\StaticFilter::execute(' name@example.com  ', 
                        'StringTrim', ['charlist' => "\r\n\t "]);
						
// The expected output of the filter is the 'name@example.com' string.

The StaticFilter class provides the execute() static method, which takes three arguments: the input value, the name of the filter to apply, and the array of filter-specific options.

In line 3, we call the execute() method to automatically create the StringTrim filter, call its setCharList() method, and pass the input value to its filter() method. This is very useful because it can be accomplished in a single line of code.

8.3.3. Method 3: Constructing a Filter From Array

When using filters with form's validation rules, you typically do not construct a filter object explicitly as we did in the previous section; instead, you pass an array configuration to the factory class, which automatically constructs the filter for you and (optionally) configures it. We already saw how this works when adding validation rules for the feedback form in Collecting User Input with Forms.

For example, let's show how to construct the same StringTrim filter with the help of the factory:

<?php
// It is assumed that you call the following code inside of the form model's
// addInputFilter() method.

$inputFilter->add([
  // ...  
  'filters'  => [
    [
      'name' => 'StringTrim',
      'options' => [
        'charlist' => "\r\n\t "
      ]	  
    ],
  ],                
  // ...
];

In the code above, we call the add() method provided by the InputFilter container class (line 5). The add() method takes an array which has the filters key. You typically register the filters under that key (line 7). Filters registered under that key are inserted in a filter chain in the order they appear in the list.

A filter configuration typically consists of the name (line 9) and options (line 10). The name is a fully qualified filter class name (e.g., Zend\Filter\StringTrim) or its short alias (StringTrim). The options is an array consisting of filter-specific options. When the factory class instantiates the filter, it passes the list of options to the filter's constructor method, and the constructor initializes the filter as needed.


Top