Issue
I often create small functions in my Models and Behaviors that add extra conditions to the array
of a find operation in CakePHP, and I keep thinking of three possible was of implementing those functions. It seems to always come down to three possible code patterns.
I'll demonstrate these three patterns using the a function called limitErrorCount
that will add an extra rule for find queries.
Pattern #1: Argument and Return
public function limitErrorCount(array $conditions)
{
$conditions['AND'][] = 'Document.errors <'=>10;
return $conditions;
}
$conditions = array(....);
$conditions = limitErrorCount($conditions);
$records = $this->find('all',$conditions);
Pattern #2: Pass By Reference
public function limitErrorCount(array &$conditions)
{
$conditions['AND'][] = 'Document.errors <'=>10;
return $conditions;
}
$conditions = array(....);
limitErrorCount($conditions);
$records = $this->find('all',$conditions);
Pattern #3: Return and Merge
public function limitErrorCount()
{
$conditions = array('AND'=>array('Document.errors <'=>10));
return $conditions;
}
$conditions = array(....);
$conditions = Hash::merge($conditions,limitErrorCount());
$records = $this->find('all',array('conditions'=>$conditions));
All three patterns work.
I am wondering which method is best out of the three, and maybe some expert PHP insight as to why it's better.
Solution
nice idea, I would like to see implement it in a chain-able way like in jQuery
$cnd = $this->Document->filterFreshOnes()->filterStarred()->filterByDaysAge('3');
$res = $this->Document->find('all', array('conditions'=>$cnd);
but that will require holding it in the model variable, which may backfire in cases where you forgot there is already some filter already... ;(
Answered By - ptica Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.