2009-02-04 47 views
2

而不是在模型類中使用$this->fetchAll('email = ?',$email)->current(),有沒有辦法做$this->fetchByEmail($email)$this->findByEmail($email)Zend Framework findBy魔法?

目前已經是一個神奇的方法,像這樣Zend_Log,其中,代替$myLogger->log("Something went wrong",Zend_Log::CRIT)你只寫$myLogger->crit("Something went wrong"),它自動地被映射(通過在__call()方法一些時髦的反射)。

有沒有人知道在Zend_Db類中是否有類似的東西,或者我會不得不寫一些東西來爲我做這件事?

回答

5

對於您想要的特定功能,您需要構建自定義功能。老實說,魔術__call()函數背後的邏輯並不是那麼困難。

像這樣的東西應該做的伎倆:

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() 
       ->from($this->_name) 
       ->where($criteria . ' = ?', $args); 
} 

顯然,如果你想讓它處理更復雜的情況下,像數組或多個標準參數,你就需要實現更完善的檢查,但這應該提供的基本理念。