Mike S wrote:
I have an application that suffers from my amateur coding
inefficiencies, and I am trying to clean a few things up. I have an
extremely database intensive object, which I have tried breaking into
smaller child objects to reduce database queries when they aren't
needed.
I currently have something that looks a bit like this:
class Object {
function Object() {
$this->attribute1 = dbQuery("foo");
$this->attribute2 = "bar";
$this->child = new SomeOtherObject($attribute1);
}
}
$foo = new Object();
if ($foo->attribute1 == "X") echo $foo->child->attributeA;
Because every page load does not require $foo->child to be populated,
is there a way to only establish the child object if it is referenced?
Where is a good place to read about dealing with child objects?
This is something known as lazy instanciation, if I remember well
(please someone correct me if I'm wrong...).
One simple way to do it is :
class Obj {
var $_child; /* private */
function Obj() {
$this->_child = null;
}
function getChild() {
if ($this->_child == null) {
$this->_child = new SomeChildObject($whatever);
}
return $this->_child;
}
}
$foo = new Obj();
if ($someCondition) {
$bar = &$foo->getChild();
echo $bar->someAttribute;
}
If you know in advance which attributes of _child you may want to
access, you can even make Obj a facade for _child :
class Obj {
var $_child; /* private */
function Obj() {
$this->_child = null;
}
/* private */
function _getChild() {
if ($this->_child == null) {
$this->_child = new SomeChildObject($whatever);
}
return $this->_child;
}
function getSomeAttributeX() {
$child = &$this->_getChild();
return $child->someAttributeX;
}
function getSomeAttributeY() {
$child = &$this->_getChild();
return $child->someAttributeY;
}
}
$foo = new Obj();
if ($someCondition) {
echo = $foo->getSomeAttributeX();
}
BTW, note that directly accessing an object's attribute may be a Bad
Thing(tm) in oop - if the implementation change, all client code is
broken. So do this only if you're API is really stable, or if you have
complete control over client code and are prepared to eventually
refactor all this code (more simply put : avoid doing so unless you
really know you can do it).
HTH
Bruno