2 Replies - 13615 Views - Last Post: 13 April 2012 - 09:33 AM

#1 Bladescope  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 71
  • Joined: 01-September 09

Question - OOP Method Practices

Post icon  Posted 13 April 2012 - 08:51 AM

Hey there,

I've got a question which has been boggling me for a while. Here's an example situation:

class X {

  private $yObj;
  private $zObj;

  public function __construct() {
     $this->yObj = new Y('foo');
     $this->zObj = new Z($this);
  }

}

class Y {

  private $var;

  public function __construct($var) {
     $this->var = $var;
  }

  public function getVar() {
    return $this->var;
  }

}

class Z {
  public function __construct($xObj) {
    // Method to grab the y object's var value..
  }
}

$foo = new X();




Using dependency injection, object z has access to object x's public methods, and wants to retrieve the $var attribute that the y object has.
There are two main methods to go about this I can think of, either:

Implement an operation in class x like so:

public function getVar() {
   return $this->yObj->getVar();
}



and have the y object call that method, or implement an operation in class x like so:

public function getY() {
   return $this->yObj();
}



and have the y object call $xObj->getY()->getVar()

This situation keeps cropping up in my code, and I am wondering which would be the best method of implementation.
For each scenario, the class which is, for this example, labelled class y, only exposes certain operations, all the internal workings are private as expected, so it can't be abused.

Any help or discussion about this question would be greatly appreciated.

Thanks in advance!

-Sean

This post has been edited by Bladescope: 13 April 2012 - 09:34 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Question - OOP Method Practices

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3520
  • View blog
  • Posts: 10,159
  • Joined: 08-June 10

Re: Question - OOP Method Practices

Posted 13 April 2012 - 09:08 AM

hm, if you need Y in Z, why donít you inject it directly? (if that is a class used in many places maybe you need a Service Locator?)
Was This Post Helpful? 1
  • +
  • -

#3 Bladescope  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 71
  • Joined: 01-September 09

Re: Question - OOP Method Practices

Posted 13 April 2012 - 09:33 AM

Injecting it directly also does work, but it means that if you're dealing with multiple 'y' objects, then you need to inject them all. It does help with keeping all of the 'y' objects inside a restricted (dependancy relative) scope though. A very viable solution indeed.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1