Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Check this <a href="https://stackoverflow.com/questions/1733582/pass-functions-to-a-class/1733729#1733729">question</a> and the answer is:</p> <blockquote> <p>As of PHP5.3 you could use <a href="http://tinyurl.com/94hjvo" rel="nofollow noreferrer">closures or functors</a> to pass methods around. Prior to that, you could write an anonymous function with <a href="http://php.net/manual/en/function.create-function.php" rel="nofollow noreferrer">create_function()</a>, but that is rather awkward.</p> </blockquote> <p>But what you are trying to achieve is best solved by passing Filter Objects to your renderer though. All filters should use the same method, so you can use it in a Strategy Pattern way, e.g. write an interface first:</p> <pre><code>interface Filter { public function filter($value); } </code></pre> <p>Then write your filters implementing the interface</p> <pre><code>class TruncateFilter implements Filter { protected $_maxLength; public function __construct($maxLength = 50) { $this-&gt;_maxLength = (int) $maxLength; } public function filter($value) { return substr(0, $this-&gt;_maxLength, $value) . '&amp;hellip;'; } } </code></pre> <p>Give your ObjectTable a method to accept filters</p> <pre><code>public function addFilter($field, Filter $filter) { if(in_array($field, $this-&gt;fields)) { $this-&gt;_filters[$field][] = $filter; } return $this; } </code></pre> <p>And when you do your ObjectTable instantiation, use</p> <pre><code>$ot = new ObjectTable(); $ot-&gt;objects = $some_objects; $ot-&gt;fields = array('id','name','description','image'); $ot-&gt;addFilter('description', new TruncateFilter) -&gt;addFilter('name', new TruncateFilter(10)) -&gt;addFilter('image', new ThumbnailFilter); </code></pre> <p>Then modify your render() method to check if there is any Filters set for the fields you are rendering and call the filter() method on them.</p> <pre><code>public function render() { foreach($this-&gt;fields as $field) { $fieldValue = // get field value somehow if(isset($this-&gt;filters[$field])) { foreach($this-&gt;filters[$field] as $filter) { $fieldValue = $filter-&gt;filter($fieldValue) } } // render filtered value } } </code></pre> <p>This way you can add infinite filters.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload