A couple Cake tricks
Well, I dont know if anyone has thought of similar tricks, but in an effort to write more I have two quickies.
The first has to do with parameters passed in the url. Let's say sometimes you dont want to deal with the order of your parameters that cake expects. Instead you want /controller/action/month/05/id/1. So, here I want the first param to be the key and the next one to be the value.
I put this in my app controller.
function assocParse()
{
if(is_array($this->passed_args))
{
$args = $this->passed_args;
for ($l = 0, $c = count($args); $l < $c; $l++)
{
if ($l+1 < count($args))
{
$a[$args[$l]] = $args[$l+1];
}
else
{
$a[$args[$l]] = null;
}
$l++;
}
return $a;
}
}
Now I can use this method in a before filter or just call it in my controller method.
function beforeFilter()
{
$this->passed_args = $this->assocParse();
}
Back to our example, /controller/action/month/05/id/1, we now have
$this->passed_args['month'] === '05'
$this->passed_args['id'] === '1'
Ok, so thats a potentially useful trick for urls. I have another one for Dynamic model binding.
Lets say that I want Post hasMany Comment, but i only need it once in a while. Ther may be no point to actually creating the association by default, so I do not put it as a property of the model class.
Instead, I make a little wrapper...
function bindComment($conditions = null, $order = null, $limit = '5', $page = '1')
{
$this->bindModel(array(
'hasMany' => array(
'Comment' =>
array('className' => 'Comment',
'conditions' => $conditions,
'order' => $order,
'limit' => $limit,
'foreignKey' => 'post_id',
'dependent' => true,
'exclusive' => false,
'finderSql' => '',
'counterSql' => ''
)
)
)
);
}
Now in my PostsController method I can call $this->Post->bindComment(); and have the association built on the fly. I can add the option parameters so that my association can return different things based on the way it is called.
Anyway, hopefully these help someone.
Happy baking.
us
gwoo's posts (22)
seth's posts (21)
Nate's posts (0)
subscribe

archives
June 2007 (1)
May 2007 (2)
March 2007 (1)
November 2006 (1)
October 2006 (2)
August 2006 (3)
July 2006 (1)
June 2006 (2)
May 2006 (1)
April 2006 (5)
March 2006 (11)
February 2006 (4)
January 2006 (4)







