PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 22, 2022

[FIXED] What method of modifying find conditions is most readable and preferred?

 April 22, 2022     cakephp, cakephp-2.3, php     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing