Using Filters

A filter is an entity that converts something from one state to another, and are supported as arguments on almost all getter methods. A filter can be:

  • any valid callback
  • in PHP5.3, a lambda function or closure
  • a T_Filter object

Getter Support

Filtering can be supported on a getter method by adding an optional argument and using the _transform() shortcut:

  1. <?php
  2. class MyUser
  3. {
  4. protected $name;
  5. function __construct($name)
  6. {
  7. $this->name = $name;
  8. }
  9. function getName($filter=null)
  10. {
  11. return _transform($this->name,$filter);
  12. }
  13. }
  14. $u = new MyUser('Rob');
  15. echo $u->getName(); // Rob
  16. echo $u->getName('mb_strtoupper'); // ROB
  17. $fn = function($val){return mb_substr($val,0,1);};
  18. echo $u->getName($fn); // R
  19. $f = new T_Filter_Crypt('mypasswd');
  20. echo $u->getName($f); // <encrypted string>
  21. ?>

Defining Filter Objects

Filtering using callbacks or lambda functions is handy, but for more complex and reusable transformations it is often necessary to define a filter object: a class that implements the T_Filter interface (i.e. has a transform() method).

  1. <?php
  2. class FirstLetter implements T_Filter
  3. {
  4. function transform($val)
  5. {
  6. return mb_substr($val,0,1);
  7. }
  8. }
  9. $f = new FirstLetter();
  10. echo $f->transform('Rob'); // R
  11. $u = new MyUser('Rob');
  12. echo $u->getName($f); // R
  13. ?>

Filter Chains

Depending on how the filter is used, it often useful to allow the filter to be part of a chain.

  1. <?php
  2. $filter = new Filter1(new Filter2);
  3. $filter->transform('something');
  4. // filter 2, and then filter 1 is applied
  5. ?>

Most filters in the library allow a prior filter to be passed into the constructor, and the T_Filter_Skeleton abstract provides a standard template for this functionality.

Reversable Filters

Filters are normally one-way conversions, but for two-way (i.e. reversable) transformations you can implement the T_Filter_Reversable interface and provide both transform() and reverse() methods.

  1. <?php
  2. $f = new T_Filter_Crypt('my-passwd');
  3. $encrypted = $f->transform('data');
  4. echo $f->reverse($encrypted); // data
  5. ?>

Want to see the code?

If you want to poke around the code itself, you can use git to grab yourself a copy.

Reference

If you're already familar with the codebase but simply want to look something up, best to head over to the code reference.

Had enough of an introduction?