Method for grabbing named parameters
Wednesday, January 21st 2009, 3:03am
Topics: Tutorials, CakePHP
Tags: CakePHP, Named, Params
Comments: 2
Permalink -
Tinylink
So I never worked much with named parameters before in CakePHP, but recently I needed a way to filter data. It seemed passing many arguments to the action wasn't the best or correct approach. My initial thought was to find a method that can easily grab the param, but after much searching and looking at the API and Cookbook, no such method exists. The next alternative was doing a long ugly shorthand if statement that looked something like this (assuming our param and URL is /search/filter:username/):
Now seeing that CakePHP is in 1.2 Stable, you would assume they would have a simple method to fix this. But no worries, I have created a method that is very easy to use and add to your application. To add it to your application, you would place it in your AppController file.
The first argument $var would be the name of the param (E.G., "filter" in our example above) and the second argument $default is the value you can return if the param does not exist. To use the method, simply call it from anywhere in your controller like so:
I have also created a second method for grabbing the value of query string param (Example URL: /search/?filter=username). I hope this has been helpful to someone, it has certainly been helpful and easily readable to me.
$filter = (isset($this->params['named']['filter'])) ? $this->params['named']['filter'] : '';
Now seeing that CakePHP is in 1.2 Stable, you would assume they would have a simple method to fix this. But no worries, I have created a method that is very easy to use and add to your application. To add it to your application, you would place it in your AppController file.
/**
* Used to get the value of a named param
* @param mixed $var
* @param mixed $default
* @return mixed
*/
function getNamedParam($var, $default = '') {
return (isset($this->params['named'][$var])) ? $this->params['named'][$var] : $default;
}The first argument $var would be the name of the param (E.G., "filter" in our example above) and the second argument $default is the value you can return if the param does not exist. To use the method, simply call it from anywhere in your controller like so:
$filter = $this->getNamedParam('filter');I have also created a second method for grabbing the value of query string param (Example URL: /search/?filter=username). I hope this has been helpful to someone, it has certainly been helpful and easily readable to me.
/**
* Used to get the value of a get query
* @param mixed $var
* @param mixed $default
* @return mixed
*/
function getQueryParam($var, $default = '') {
return (isset($this->params['url'][$var])) ? $this->params['url'][$var] : $default;
}
2 Comments
Dec 11th 2009, 05:30