I came up with a nifty function while working on the pagination library for my framework and the next version of this blog. The following function isn't actually the same one I use in the framework, but a generalized all-encompassing solution.
The problem I had was that I needed the pagination class to generate a uniform route/path for the urls so that the pagination links--eg: first, prev, 1, 2 ... next, last--would all work in the same way. One thing I realized that I didn't want to do was put the url into the template because that meant having to repeat the format several times over. It also meant that dealing with the previous and next page links would be tricky because I don't want to let them get out of bounds.
Here is the function as I made it in the Pager class. Notice how $path becomes a bit of generated php string concatenation and how I insert it into the create_function. Also notice how the $page in the create_function is then substituted into that string concatenation where there was one the %page% token in the $path variable.
/**
* Set the format for the path for each page. A path should be supplied to
* this function and wherever the person wants the page number to appear
* in the path, they need only put a %page%
*/
public function setPath($path = '') {
// get rid of any quotes in the path... too bad for people who for
// some reason would do this.
$path = preg_replace("~['\"]*~", "", $path);
// replace the token with what will be executed php
$path = str_replace("%page%", "'. \$page .'", $path);
// create a function so that substitution of the page number into the
// path is as easy as calling the lambda
$this->path_format = create_function('$page', "return vk_url(vk_path('{$path}'));");
return $this;
}
Here is the generalized function that I derived from this:
function lambda_filter($format, $filter) {
if(!is_array($filter)) {
$filter = array($filter);
}
$args = '';
$letter = 'a';
$sep = '';
foreach($filter as $f) {
$args .= $sep . '$'. $letter++;
$sep = ',';
}
return create_function($args, 'return str_replace('. var_export($filter, TRUE) .', array('. $args .'), "'. str_replace('"', '\"', $format) .'");');
}
$fn = lambda_filter("/page/%page%/", '%page%');
echo $fn(1);
// output: /page/1/
If you read through that function, you will notice that the second parameter to lambda_filter can also be an array of tokens to substitute in to the format string. Here's an example of how that can be used.
$fn = lambda_filter("/%year%/%month%/%day%/", array('%year%', '%month%', '%day%'));
echo $fn('2007', '07', '08');
// output: /2007/07/08/
Obviously that format of token doesn't need to be used. Any format of token can be used.
- Uncategorized by Peter Goodman on Jul 8, 2007 @ 10:16pm

