I had a need to define a query condition that was available globally in cakePHP. I needed to make sure that I had it when any model called for it. I’m getting into building Fat Boy models now (like chris) and decided that this was one bit I could let leak over into the beforeFilter in the app_controller.
So, when a person hits any page on the site, my app_controller makes sure the viewer of the site meets a few criteria and then defines the condition if it isn’t already set:
if(!defined('CONDITION')) { define('CONDITION', $this->Session->read('CONDITION_VAR')); }
Now, this might be something that a proper ACL/ARO/ACO scheme could solve, but if it was that easy, why would I make it any harder on myself?
Now, in my model I set an “equal to” condition. You could make this condition anything (“is not”, “is greater than”, whatever…)
function beforeFind($queryData)
{
$queryData['ModelName']['propertyName'] = CONDITION;
return $queryData;
}
That’ll take care of any of the find or read functions that you’ll be calling from your controller. What about saving new data? Just set that propertyName in the beforeSave, no need to pollute your controller with that kind of thing. (Again, this is an “equal to” case, so I just end up setting the “propertyName” to the condition. Other case might need some work.)
function beforeSave()
{
if(isset($this->data['ModelName']))
{
$this->data['ModelName']['propertyName'] = CONDITION;
}
return parent::beforeSave();
}
On a side note, I would appreciate a better (built-in) way to pass data between a controller and the models it interacts with.
Sphere: Related Content
Thanks, cool article. :) Already tried it out with one of my applications. I believe there was a similar article on http://php-coding-practices.com
Can’t quite remember, though.
Thank you.
Ryan Cheek May 2, 08:42 AM #