【问题标题】:How can I Make a Successful Domain Object Factory in PHP如何在 PHP 中创建成功的域对象工厂
【发布时间】:2013-01-03 13:56:27
【问题描述】:

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

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

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

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

我想出了几个选择:

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

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

【问题讨论】:

    标签: php oop model-view-controller design-patterns domain-object


    【解决方案1】:

    为什么要初始化一个分配了所有属性的Domain Object

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

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

    一些例子:

    检索现有文章

    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'));
    }
    

    【讨论】:

    • 所以你是说我应该生成空域对象,让我的数据映射器单独填充它们?如何处理用户输入?
    • 工厂放行时DO为空。您为其分配一些条件,然后获取值..或存储它们。
    • 但是,您将如何处理用户输入?制作自己的 DM 听起来不对
    • 我不确定这是否正确,但我的Front Controller 捕获用户输入(通常来自 POST 数组,但也可能来自其他输入),并创建一个包含输入数据的 Request 对象由用户,然后传递到适当的控制器(基于请求的操作)。
    • @tereško 在代码示例中,您使用了映射器/域工厂的 [create] 方法和服务工厂的 [build] 方法。这是故意的(服务“构建”做了不同的事情?)还是同一件事的不同名称?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2010-11-21
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多