在作为依赖项注入之前,对象应该完全完整吗?

时间:2010-06-12 13:57:12

标签: php dependency-injection

这是此问题的扩展:Understanding how to inject object dependencies。由于它有点不同,我想分开它们,希望它更容易回答。此外,这不是一个真正的系统,只是一个我认为我们都熟悉的简化示例。 TIA。 :

DB

threads:thread_id,thread_name等

帖子:post_id,thread_id,post_name,post_contents,post_date,post_user_id等

概述

基本上我正在寻找加载$ post_id的最可维护的方法,让它级联并加载我想知道的其他东西,并且我试图保持控制器的瘦。但是:

  • 我最终有太多的依赖注入
  • 我正在传递已初始化但空的对象
  • 我想限制我传递的参数数量
  • 我可以将$ post( - >很多)注入$ thread(一个&lt ;-),但在那个页面上我不是在看一个帖子,我正在看帖子
  • 我可以将它们组合/注入新对象

详细

如果我将一个物体注入另一个物体,最好是先将物体完全制造出来吗?我试图限制我要传递给页面的参数数量,但我最后得到一个圆圈。

// 1, empty object injected via constructor
$thread = new Thread;
$post = new Post($thread); // $thread is just an empty object
$post->load($post_id); // I could now do something like $post->get('thread_id') to get everything I want in $post

// 2, complete object injected via constructor
$thread = new Thread;
$thread->load($thread_id); // this page would have to have passed in a $thread_id, too
$post = new Post($thread); // thread is a complete object, with the data I need, like thread name
$post->load($post_id);

// 3, inject $post into $thread, but this makes less sense to me, since I'm looking at a post page, not a thread page
$post = new Post(); 
$post->load($post_id); 
$thread = new Thread($post);
$thread->load(); // would load based on the $post->get('post_id') and combine.  Now I have all the data I want, but it's non-intuitive to be heirarchially Thread->Post instead of Post-with-thread-info


// Or, I could inject $post into $thread, but if I'm on a post page,
// having an object with a top level of Thread instead of
// Post-which-contains-thread-info, makes less sense to me.

// to go with example 1
class post
{
    public function __construct(&$thread)
    {
        $this->thread=$thread;
    }

    public function load($id)
    {
        // ... here I would load all the post data based on $id

        // now include the thread data
        $this->thread->load($this->get('thread_id'));

        return $this; 
    }
}

// I don't want to do 

$thread = new Thread;
$post   = new Post;
$post->load($post_id);
$thread->load($post->get('post_id'));

或者,我可以创建一个新对象并将$ post和$ thread注入其中,但随后我的对象具有越来越多的依赖项。

1 个答案:

答案 0 :(得分:0)

这些不是依赖项,只是同一模型的一部分,因此不需要注入任何东西。想想你的模型及其用法。什么是主要实体(构建块) - 帖子或帖子?或者他们同样重要/使用? 您应该只与主实体进行处理(加载/存储),最好使用通常称为Repository的外部类。例如。你可以有方法ThreadRepository :: findById($ id),这就足够了,把剩下的留给存储库内部......在存储库中加载和设置你想要的东西但是永远不要把它暴露给应用程序的其他部分。如果性能问题,您还可以实现某种形式的延迟加载(内部资源加载器,代理模式等)

如果您有空闲时间,请下载并阅读本书(或购买原件): http://www.infoq.com/minibooks/domain-driven-design-quickly 您的编码问题已经解决并在那里得到了很好的解释。

相关问题