使用Zend_Model_Mappers和Zend_Db_Table_Abstract为单个模型创建多个表


Multiple Tables for a single Model using Zend_Model_Mappers and Zend_Db_Table_Abstract

不确定我最近是否在stackoverflow上问了太多问题,但我觉得Zend框架文档令人震惊。这些例子似乎很模糊,一点也不像现实世界中使用的。他们鼓励使用框架来编写整洁和有组织的代码,但没有提到应该如何遵循框架:D

无论如何!在我目前迁移到Zend的旧应用程序中,我有一个名为register的函数,如:

function register($username, $password, $email, $etc) {
    // Do stuff
    // Insert $email and other stuff into `user_profile` table
    // Insert $username and $password into the `user` table
}

但是现在和Zend…我一直在按照他们的留言簿教程开始,我有以下模型:User, UserMapper。我有DbTables的每一个表在我的数据库中,像这样:User, UserProfile .

我喜欢注册时的功能,你建立一个User对象然后调用mapper上的save它将对象写入数据库但问题是,一些用户片段会进入用户配置表。留言簿应用程序的示例是,在UserMapper中,您只拉入一个表(User)并向其写入…我的意思是我可以这样写:

// Insert or Update data to user table
$this->getDbTable()->insert($user_data);
// Insert or Update User Profile data
$this->setDbTable('UserProfile');
$this->getDbTable()->insert($user_profile);

但这似乎有点…出租汽车司机。实际推荐的处理多个表的方法是什么?

另外,如果我有自定义查询…我是要把它们放入创建的DbTable类还是UserMapper类?我不知道扩展DbTable到底是干什么的。指南只是说去做,并没有真正解释你为什么这么做的好处/原因/用途。

谢谢,Dom

首先,你不能问太多关于SO的问题。这就是这个网站存在的意义,没有问题=没有答案=没有SO。:)

你的usermapper类可以有$user$userProfile属性和register()方法。然后register方法从这些表中访问它需要的方法。下面的示例代码是基本的,不能按原样工作,但它给了您一个大致的概念。

与继承一个类的属性和方法不同,它使用组合来访问多个类。换句话说,这个类'has' Zend_Db_Tables而不是'is ' Zend_Db_Table。希望区别是清楚的,并且您可以看到这种工作方式的一些优势。

在你的控制器中:-

public function indexAction() {
    $userMapper = new Application_Model_Usermapper();
    $userMapper->register($username, $password, $email, $etc);
}

在你的模型中(我还没有开始使用名称间距,对不起):-

class Application_Model_Usermapper
{
    private $user;
    private $userProfile;
    public function __construct()
    {
        $config = array(
            'name'      => 'userTable',
            'primary'   => 'userid'
        );
        $this->user = new Zend_Db_Table($config);
        $config = array(
            'name'      => 'userProfileTable',
            'primary'   => 'userid'
        );
        $this->userProfile = new Zend_Db_Table($config);
    }
    public function register($username, $password, $email, $etc)
    {
        $this->user->insert($userdata);
        $this->userProfile->insert($userProfileData);
    }  
}

您的Mapper类需要与多个表对话,因此您需要多个set/getDbTable方法,例如:

public function setUserDbTable($dbTable) {}    
public function getUserDbTable() {}
public function setUserProfileDbTable($dbTable) {}    
public function getUserProfileDbTable() {}

那么在你的其他方法中,你可以使用相应的表,例如:

$this->getUserDbTable()->insert($userData);
$this->getUserProfileDbTable()->insert($userProfileData);

对于其他方法中的其他交互也是如此。