Generally I have 3 classes, a container that holds an array of items and a special object that is another property of the container class. What I need to do is access the special object from an item object within the container. I see 2 ways of achieving this.
class Container {
protected $object;
protected $items = [];
public function __construct() {
$this->object = new SpecialObject;
}
public function setItem($index, Item $item) {
$this->items[$index] = $item;
}
public function getItem($index) {
return $this->items[$index];
}
}
class Item {
protected $container;
public function __construct(Container $container) {
$this->container = $container;
}
public function action() {
$this->container->object;
}
}
Or
class Container {
protected $object;
protected $items = [];
public function __construct() {
$this->object = new SpecialObject;
Registry::set('SpecialObject', $this->object);
}
public function setItem($index, Item $item) {
$this->items[$index] = $item;
}
public function getItem($index) {
return $this->items[$index];
}
}
class Item {
public function action() {
Registry::get('SpecialObject');
}
}
With the first example the problem I'm concerned about is that there will be a reference within each Item object pointing to the container, which is not only redundant but if an item switches containers (for some reason, not intended) it will have a wrong container reference and could lead to trouble. The second one however implies that there will only be one instance of Container, which may not and probably will not be the case. I think there is no fool-proof way to grab the container of an item but what would you suggest is the "best" way to achieve this in terms of performance and avoiding bugs?
Item
need to know, in whichContainer
is it stored? You are creating a circular dependency, which in some cases might be a good design, in your case it screams bad implementation. If you need theSpecialObject
in yourItem
class, set it into theItem
using a method and manipulate it that way.Item
had aSpecialObject
reference, but it is just giving me the sensation of bad implementation. I think the items should not store references to anything they should just be able to get the object from the container they currently reside in.