3

我正在摆弄一个 MVC 框架,我偶然发现了一个我不知道如何解决的问题。

我想为DomainObjectFactory我的应用程序的模型层创建一个,但是,每个域对象都会有一组不同的参数,例如:

  • 人员 - $id、$name、$age。
  • 帖子 - $id、$author、$title、$content、$comments
  • 评论 - $id, $author, $content

等等。我怎样才能轻松地告诉我的工厂我需要什么样的对象?

我想出了几个选择:

  • 传递一个数组——我不喜欢这个,因为你不能依赖构造函数的契约来告诉对象他的工作需要什么。
  • 制作DomainObjectFactory一个接口,并制作具体的类 - 有问题,因为要制作大量的工厂!
  • 使用反射 - 服务定位器多吗?我不知道,在我看来就是这样。

我可以在这里使用一个有用的设计模式吗?还是其他一些聪明的解决方案?

4

1 回答 1

3

为什么要初始化一个分配了所有属性的域对象?

相反,只需创建一个空的Domain Object。您可以在工厂检查它是否有prepare()执行方法。哦.. 如果您使用的是DAO,而不是直接与Mappers交互,您可能希望在您的域对象中构造和注入适当的DAO

值的分配应该只发生在Service中。通过使用普通的二传手。

一些例子:

检索现有文章

public function retrieveArticle( $id )
{
    $mapper = $this->mapperFactory->create('Article');
    $article = $this->domainFactory->create('Article');
    
    $article->setId( $id );
    $mapper->fetch( $article );
    $this->currentArticle = $article;
}

发表新评论

public function addComment( $id, $content )
{

    $mapper = $this->mapperFactory->create('article');
    $article = $this->domainFactory->create('Article');
    $comment = $this->domainFactory->create('Comment');

    $comment->setContent( $content );
    $comment->setAuthor( /* user object that you retrieved from Recognition service */ );

    $article->setId( $id );
    $article->addComment( $comment );
    // or you might retrieve the ID of currently view article
    // and assign it .. depends how you build it all
    
    $mapper->store( $article ); // or 
}

传递用户输入

public function getArticle( $request )
{
    $library = $this->serviceFactory->build('Library');
    $library->retrieveArticle( $request->getParameter('articleId'));
}
于 2013-01-20T14:03:38.947 回答