Having fun with __call() in Cake

email-addthis printer-addthis favorites-addthis facebook-addthis digg-addthis | Share

16 May 2007 01:00:00
Category: CakePHP

You've probably used Cake's dynamic model method $this->FindBySomeField($arg).

What if instead of rows you want an individual field? What if you could, $this->getSomeFieldFromSomeComparison($argument);

Put this snippet in your app model and you can do both.


function __call($method_name, $params)
{
        
    if(substr($method_name, 0, 3) == 'get')
    {
      $m_name = substr_replace($method_name, '',  0, 3);
      $fields = explode('From', $m_name);
      if(is_array($fields) && !empty($fields))
      {
       $condition_field = Inflector::underscore($fields[1]);
       $value_field = Inflector::underscore($fields[0]);
       $conditions = array($this->name.'.'.$condition_field => $params[0]);
       $results = $this->find($conditions);
       return $results[$this->name][$value_field];
      }
                        
    }
    else
    {
    return parent::__call($method_name, $params);    
    }
}

Now you can run a find like:

$username = $this->getUsernameFromId(12345);

And you'll get a result like: string(3) "PHP"

The only draw back is that you can only run this on PHP5. And if your database fields have the word "from" in them you might have some trouble.

Otherwise enjoy!