2009-02-03 17 views
1

有沒有辦法如何使用Zend_Db關係來設置相關對象? 我在尋找類似下面的代碼:使用關係在Zend_Db_Table_Row中設置

$contentModel = new Content();   
$categoryModel = new Category(); 

$category = $categoryModel->createRow(); 
$category->setName('Name Category 4'); 

$content = $contentModel->createRow(); 
$content->setTitle('Title 4'); 

$content->setCategory($category); 
$content->save(); 

這提供小型圖書館: http://code.google.com/p/zend-framework-orm/

是否有人有這種經驗? ZF沒有類似的計劃嗎?還是有更好的使用? (我不wnat使用ORM的學說或外在的東西)

感謝

回答

1

我總是覆蓋和Zend_Db_Table類和一個Zend_Db_Table_Row用我自己的子類。在我Db_Table I類有:

protected $_rowClass = 'Db_Table_Row'; 

在我Db_Table_Row我有以下__get()和__set()函數:

public function __get($key) 
{ 
    $inflector = new Zend_Filter_Word_UnderscoreToCamelCase(); 

    $method = 'get' . $inflector->filter($key); 

    if(method_exists($this, $method)) { 
     return $this->{$method}(); 
    } 

    return parent::__get($key); 
} 

public function __set($key, $value) 
{ 
    $inflector = new Zend_Filter_Word_UnderscoreToCamelCase(); 

    $method = 'set' . $inflector->filter($key); 

    if(method_exists($this, $method)) 
     return $this->{$method}($value); 

    return parent::__set($key, $value); 
} 

Bascially,只是告訴全班同學尋找所謂的getFoo方法( )和setFoo()或其他。只要你自己寫下自己的邏輯,你幾乎可以自己組建自己的領域。在你的情況下,也許:

public function setCategory($value) 
{ 
    $this->category_id = $value->category_id; 
} 
+0

嗨,謝謝你的回答,但我不需要setter只爲值,或者定義自己的函數。 $ content-> setCategory($ category); $ content-> save(); 這提供了在相關表中創建新行並將其綁定到相關外鍵 – 2009-02-03 16:08:53

3

我設計並實現了Zend Framework中的表關係代碼。

外鍵(在您的示例中爲$content->category)包含其引用的父行中的主鍵的值。在您的示例中,$category不包含主鍵值,因爲您尚未保存它(假設它使用自動遞增pseudokey)。直到填充它的外鍵,你不能保存$content行,所以參照完整性滿足:

$contentModel = new Content();     
$categoryModel = new Category(); 

$category = $categoryModel->createRow(); 
$category->setName('Name Category 4'); 

$content = $contentModel->createRow(); 
$content->setTitle('Title 4'); 

// saving populates the primary key field in the Row object 
$category->save(); 

$content->setCategory($category->category_id); 
$content->save(); 

它這樣做無濟於事,到行對象傳遞給setCategory()如果它沒有主鍵填充。如果它沒有要引用的有效主鍵值,則$content->save()將失敗。

由於無論如何您都需要填寫主鍵字段,所以當您撥打setCategory()時,訪問該字段並不困難。