【问题标题】:Checking for duplicate values in a Model class检查模型类中的重复值
【发布时间】:2011-01-11 02:32:25
【问题描述】:

我有一个模型,Entity,我构建了一个 EntityMapper 和一个 Entity 类(我只是在学习使用 Zend Framework 并按照教程进行操作)。 Entity 类有一个 setName 方法,我想要它做的是检查数据库中是否有另一个同名的“实体”,在这种情况下抛出异常或其他东西。

所以,如果我理解正确,数据库调用应该只在 Mapper 类中。那么,在setName 内部,我应该这样做:

$entity = new Application_Model_EntityMapper();
if ($entity->checkDuplicateName($name, $this->_id))
  $this->_name = $name;
else
  throw new Exception(...);
return $this;

并将实际执行查询的代码放在 Mapper 类的新方法中? (当然,如果“实体”是新的或者它已经有一个 id,那么查询应该是不同的,但这不是我的问题的重点)。

我知道我可以通过多种方式做到这一点,但我的目标是尽可能地适应框架的约定。

【问题讨论】:

    标签: zend-framework zend-db


    【解决方案1】:

    由于保存是 Mapperobject 的职责,我将验证添加到您的映射器类的保存例程中。 我不明白你的不同班级各自的职责,所以我会解释一下我的:

    -Application_Model_Entity是一个纯数据结构,这个类没有依赖
    -Application_Model_EntityMapper 拥有与 dbrms 对话的权利,将转换记录中的实体,反之亦然。它“拥有” ActiveRecord (DbTable) 类 -Application_Model_DbTable_Entity 是 ActiveRecord 类,它扩展自 Zend_DbTable_Abstract 并且能够对 DB 进行查询,它只被 Mapper 使用。

    $entity = new Application_Model_Entity();
    $entity->setName('something which already exists');
    
    $mapper = new Application_Model_EntityMapper();
    $mapper->save($entity); // throws Exception
    
    // works with: 
    class Application_Model_EntityMapper
    {
        /** @var Application_Model_DbTable_Entity */
        private $dbTable;
    
        ...
    
        public function save(Application_Model_Entity $entity)
        {
            $doValidation = ! $entity->getId(); // no id means not in db yet
            if ( $doValidation )
            {
                $hasDuplicatesValidator = new Zend_Validate_Db_RecordExists(
                    'table' => 'entity',
                    'field' => 'name'
                );
                $hasDuplicates = $hasDuplicatesValidator->isValid($entity->getName());
                if ( $hasDuplicates )
                {
                    throw new Exception('There is already a record in the db with this name!');
                }
            }
            // go on and save
            $this->dbTable->save($entity);
        }
    }
    

    我希望代码能够自我解释。 这是我能找到的最“zendish”的方式,希望这可以帮助您前往 zf 社区:)

    链接到manual for Zend_Validate_*

    【讨论】:

    • 补充一点信息:Model/Mapper/ActiveRecord 的结构与 ZendFramework 的“快速入门”教程中使用的完全相同。
    【解决方案2】:

    我发现在setName 中进行该检查会导致它在每次从数据库加载记录时运行查询(不好),所以我将对checkDuplicateName 的调用移至save 的方法映射器类。 (checkDuplicateName 也在 Mapper 类中,现在作为私有方法)

    我仍然很想知道这是否是在 Zend Framework 中执行此类操作的标准方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多