【问题标题】:Data mapper and zend framework数据映射器和 zend 框架
【发布时间】:2011-11-29 00:15:30
【问题描述】:

我正在我的 Zend Framework Web 应用程序中实现 Data Mapper 设计模式,一切顺利,我真的很喜欢在 Zend 中使用数据映射器,而不是仅应用 Row Gateway 模式,但我遇到了一个问题我的架构。我不确定如何使用我的数据映射器以 OOP 方式引用和使用外键约束。 所以我有我的模型类、我的 DbTable 类和我的 Mapper 类。我是否应该将所有外键关系放在我的 DbTable 类中,这样我可以使用findDependentRowset() 函数在我的映射器中检索,或者更好的方法是在我的映射器中实例化依赖类。使用 Data Mapper 模式映射外键的最佳 OOP 实践是什么?

【问题讨论】:

  • 如果您有很多阻抗不匹配,请考虑使用 ORM,例如 Doctrine2。
  • 我已经开始使用数据映射器实现项目,我遇到的唯一问题是处理外键映射,如果要实例化对象或让 DbTable 了解数据库架构
  • 我的实现是这样的: Model - 和你说的一样,但是没有任何函数,只有 setter 和 getter 用于访问 Model 属性 DbTable - 这里没有函数,只有 Zend_Db_Table_Abstract 的子类并提供 id 和表 DataMapper 的名称 - 肉 - 在这里我拥有所有功能,我检索 DbTable 类并使用 Model 类设置属性我希望我的系统尽可能松散耦合,所以问题是我的外键我的应用程序中的关系

标签: php oop zend-framework datamapper


【解决方案1】:

我会选择 DataMapper,因为其他两个不应该知道 ID 本身,尽管关系调用者总是需要它。

Model
- Property accessors and private property data holders
- Functions regarding correct usage of model
- Relatioship callers (calls relationship fetches in the DbTable to get parents or children rows)or returns cached data

DbTable
- Provides all static functions used to query data and instanciate the related Models such as :getById, getByName, getByComplexSearch, etc
- Provides all static relationship loaders such as: getParents, getChildrens and any other version you need

DataMapper
- Does the real meat and provides the getObjects method which accepts either a query part or a full query and loads the data into the ModelObjects and reads it back into a update, insert, delete query when needed
- Datamapper should be in charge of checking for relationship faults when inserting, updating or deleting using transactions if in InnoDB.

这有意义吗?

【讨论】:

    【解决方案2】:

    我的系统上曾经有findDependentRowset。但现在不是了!在大多数情况下,这是一种资源浪费。表连接应该在您的 SQL 语句中。

    在这里查看我的答案:Hand made queries vs findDependentRowset

    我离使用 Doctrine 或 Propel 还很远(我从来不需要它)。也许有一天。(现在使用Doctrine 2。所以...我现在建议你也一样)


    旧答案

    在使用 Zend Framework 几年后,我遇到了以下架构:

    1) 我有一个抽象映射器,我的所有映射器都扩展了它:Zf_Model_DbTable_Mapper

    2) 我也有一个抽象模型(域对象),类似于行数据网关,只是它不是网关。这是一个通用域对象:Zf_Model

    3) 在填充对象图(SQL 连接)时,一个映射器委托给负责给定对象的其他映射器。

    示例

    此方法来自抽象映射器:

        public function getById($id) 
        {
    
    
            $tableGateway = $this->getTable();
    
            $row = $tableGateway->fetchRow('id =' . (int) $id);
    
            if (!$row) 
                retur null;
    
            $row = $row->toArray();
    
            $objectName = $this->getDomainObjectName();
            $object = new $objectName($row['id']);
            $object->populate($row);
    
            return $object;    
        }
    

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 2011-10-05
      • 1970-01-01
      • 2012-01-31
      • 2011-03-22
      • 2011-06-18
      • 1970-01-01
      • 2012-10-01
      • 2011-05-12
      相关资源
      最近更新 更多