2

Is the following implementation in PHP correct?

I focused on what they say about the lifetime of dependencies:

“Aggregation implies that an aggregate object and its owner have identical lifetimes.“

The implementation of acquaintance:

    class B {}
    class A
    {
        /**
         * @var B
         */
        private $b;

        // $b can be injected to $a via a constructor
        public function __construct(B $b)
        {
            $this->b = $b;

            // this is not possible and would be an aggregation relationship
            // $this->b = new B();
        }

        // $b can also be injected to $a via a setter
        public function setB(B $b)
        {
            $this->b = $b;
        }
    }

The implementation of aggregation:

    class B {}
    class A
    {
        /**
         * @var B
         */
        private $b;

        // $b is instantiated in the constructor (the lifetime of $b is the same as of $a)
        public function __construct()
        {
            $this->b = new B();
        }
    }

1 Answer 1

2

Thinking about lifetimes is not that relevant in PHP because the language has automatic memory management. That is more of a C++ thing.

Your second solution is aggregation-ish because the B object doesn't have to exist beyond the A object's lifetime. But if the B object were accessible externally, some external code could hold on to the B reference and extend its lifetime. This can be the case in your first solution because the object is provided externally. However, depending on how they are intended to be used, either of the approaches could be an example of aggregation.

The important parts of the GoF book are not so much the definition of aggregation but the parts where they describe general principles for solving problems through object-oriented techniques.

2
  • Thank you for this very useful answer! Would you say that we can implement acquaintance and aggregation but that we can do it in various ways? Does this seem correct to you? Commented Apr 7, 2019 at 15:26
  • 2
    @MichaelKäfer Generally yes, but I'd rather say that you'd use terms like “aggregation” to describe some relationship, and that you wouldn't necessarily try to implement a particular kind of relationship.
    – amon
    Commented Apr 7, 2019 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.