Search code examples
phpoopseparation-of-concerns

Should an object "load" another object on its own, or have the other passed to it?


Is it a good practice to load another object from within an original object, like so:

Class parent() {

    $child;

    function loadChild() {
        $child = new Child();
        $this->child = $child;
    }
}

or, should the child object always be passed in separately?

Class parent() {

    $child;

    function setChild(child $child) {
        $this->child = $child;
    }
}

$parent = new Parent();
$child = new Child();
$parent->setChild($child);

Which is the better option, more flexible etc?


Solution

  • It depends on the situation.

    The name of the second object suggests that

    1. the Child instance will only be used by the Parent instance
    2. does not need to live longer than the Parent instance

    If this is the case, than the first pattern (Object composition pattern) is the better one.

    If the Child instance is needed/used at other places in you code, the second pattern (Dependency injection) is more appropriate. Dependency Injection is a more flexible pattern, if you are unsure about your use case, you should generally use the Dependency Injection.