0

Okay, I may be just over complicating things in my head or just completely missing something; but I'm not too sure.

I have a class called Opportunity as well as a class called Activity.

An Opportunity will have many many Activities along with it.

There is no reason why an Activity needs to access Opportunity methods/properties as an activity is a one to many relationship between an opportunity and is a totally different object than an opportunity. But an Activity can not exist without being linked to an Opportunity.

Is this a child parent relationship or does Activity need to extend the Opportunity Class?

How does inheritance work with this example?

Brady Liles
  • 713
  • 7
  • 13

2 Answers2

2

You are talking about the Composite pattern, your class Opportunity is composed by one or several Activities.

Is this a child parent relationship or does Activity need to extend the Opportunity Class?

Is not a child parent relationship because there is no hierarchy between them, Activities does not need to use or reimplement any Opportunity method nor attribute. Activities are simply a part of the Opportunity. So no, Activity does not need to extend the Opportunity Class.

javier_domenech
  • 5,995
  • 6
  • 37
  • 59
1

You don't have to make them a parent - child relationship. In fact, if anything, it sounds like you need dependency injection instead

class Activity {
    /** @var \Opportunity */
    protected $opportunity;

    public function __construct(\Opportunity $opportunity) {
        $this->opportunity = $opportunity;
    }

    public function run() {
        $this->opportunity->doSomething();
    }
}
$activity = new \Activity($opportunity); // Pass an instance of Opportunity here

This way, you have to have your Opportunity class and Activity has access to it but it can only use the methods it needs. No worries about inheritance.

Community
  • 1
  • 1
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • You're right. Dependency injection is exactly what I was looking for. I was making things too complicated on myself. Thank you! – Brady Liles Jun 02 '15 at 22:12