php – Zend Framework findBy magic method? – Education Career Blog

Instead of using $this->fetchAll('email = ?',$email)->current() inside the model class, is there a way to do $this->fetchByEmail($email) or $this->findByEmail($email) ?

There’s already a magic method like this for Zend_Log, where instead of $myLogger->log("Something went wrong",Zend_Log::CRIT) you just write $myLogger->crit("Something went wrong") and it automagically gets mapped ( via some funky reflection in the __call() method ).

Does anybody know if there is something like that in any of the Zend_Db classes, or am I going to have to write something to do this for me?


For the particular functionality that you want, you’ll need to build a custom function. Honestly, the logic behind the magic __call() function isn’t all that difficult.

Something like this should do the trick:

public function __call($function, $args)
    // Expects findBy to be the first part of the function
    $criteria = substr($function, 6);
    $criteria = strtolower($criteria);

    $select = $this->select()
                ->where($criteria . ' = ?', $args);

Obviously if you want it to handle more complex cases like arrays or multiple criteria parameters, you would need to implement better checking but this should provide the basic idea.


According to the documentation you have to do it by yourself

So I suggest create your own or use the one posted by gabriel1836

Leave a Comment