将我的模型与Doctrine2中的实体分开的最佳做法是什么?

时间:2014-02-14 14:56:06

标签: php doctrine-orm

好的,所以现在我最终决定在我的新Zend2项目中使用Doctrine2 ORM,我有一个关于将Model和Entity类分开的最佳设计实践的问题。我询问实体和模型之间有什么区别,我明白这一点。我的服务层也与Repository类连接正常。我要问的是,当我有一个带有一些业务逻辑的Model类时,让我们说Document类,然后DocumentEntity表示它的持久性,并且只是想让它们分开,所以例如,这是我的实体:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="DocumentRepo")
 * @ORM\Table(name="document")
 */
class DocumentEntity {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @ORM\Column(type="guid")
     */
    protected $guid;

    /**
     * @ORM\Column(length=64)
     */
    protected $name;

    // more stuff below...
}

现在,我的Model类中包含许多业务逻辑,我希望将它们分开:

class Document implements SomeImportantInterface, AnotherImportantInterface {

    public function doSomeImportantStuff() {
    }

    public function doEvenMoreImportantStuff() {
    }
}

最后,服务类:

class DocumentService  {
    const DOCUMENT_ENTITY = 'DocumentEntity';

    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager) {
        $this->em = $entityManager;
    }


    public function getDocument($guid) {
        $documentEntity = $this->em->getRepository(self::DOCUMENT_ENTITY)->findByGuid($guid);

        return; //what? I want here Document to be returned, not the DocumentEntity..
    }

    public function createDocument() {
        return new Document();
    }

    public function saveDocument(Document $document) {
        // Document -> DocumentEntity

        // $documentEntity = ...?
        //$this->em->persist($entityDocument);
        //$this->em->flush();
    }
}

正如您所看到的,计划是拥有应用程序唯一关心的Document对象(可通过Service访问),而不是DocumentEntities。我想到了两种可能的方法:

  • 将DocumentEntity保留为Document
  • 中的属性
  • 使Document扩展DocumentEntity

或者,也许我只是在这里错过了一些东西,并且只是错误的结束?期待听到您的意见!

1 个答案:

答案 0 :(得分:0)

您的实体应扩展模型类。您的应用程序需要通过存储库接口完成所有模型交互。

DomainModel
    DocumentDomainModel
    DocumentDomainModelInterface
    DocumentDomainModelRepositoryInterface (get/create/save)

DoctrineEntity
    DocumentDoctrineEntity extends DocumentDomainModel
    DocumentDoctrineRepository implements DocumentDomainModelRepositoryInterface

这也使您可以灵活地实现其他存储库,例如在内存中用于测试。