A couple Cake tricks

posted by: gwoo :: Mar 30th 2006, 02:38

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.

2 comments

bottom

1. Miguel Angelo Benevides :: on Jun 13, 2006 Thanks for these tricks... just a question: in this comment form, what is the purpose of the 'cancel' button? ;)
2. gwoo :: on Jun 15, 2006 mostly for fun I guess. But soon it will work.

add one

 
 
top