使用Zend_Model_Mappers和Zend_Db_Table_Abstract的单个模型的多个表

时间:2011-10-23 22:03:31

标签: php model-view-controller zend-framework zend-db

不确定我最近是否在stackoverflow上问了太多问题,但我觉得Zend Framework文档令人震惊。看起来这些例子非常模糊,与现实世界中使用的一样。他们鼓励使用框架来整理和组织代码,然后不提及应如何遵循它: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 ......我一直在关注他们的入门指南,我有以下模型:UserUserMapper。 我的数据库中的每个表都有DbTables,如:UserUserProfile

所以我喜欢你注册时的功能,你建立一个User对象,然后在mapper上调用save,它将对象写入数据库,但问题是,其中一些用户进入了用户配置文件表。留言簿应用程序中的示例是,在UserMapper中,您只需拉入一个表(用户)并写入...我的意思是我可以做类似的事情:

// 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);

但这似乎有点...... hacky。处理多个表的实际推荐方法是什么?

另外,如果我有自定义查询...我是否打算将它们放入创建的DbTable类或UserMapper类中?我真的没看到扩展DbTable实际上是为了什么。所有指南都说要做到这一点并没有真正解释为什么你这样做的好处/原因/用途。

谢谢,Dom

2 个答案:

答案 0 :(得分:1)

首先,你不能在SO上问太多问题。那是网站存在的,没有问题=没有答案=没有。 :)

您的usermapper类可以包含$user$userProfile属性以及register()方法。然后,register方法从这些表中访问所需的方法。下面的示例代码是基本的,不会按原样运行,但它为您提供了一般的想法。

它不是继承一个类的属性和方法,而是使用组合来访问多个类。换句话说,这个类'有'Zend_Db_Tables而不是'是'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);
    }  
}

答案 1 :(得分:0)

您的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);

与其他方法中的其他相互作用相似。

相关问题