
Originally Posted by
dreamscape
If most of the objects you are creating during a request are not even being used, rather than look for ways to persist them, I think I would ask the question, "Why are they even being created at all?". Instead of trying to persist all objects that may or may not be needed, why not only create those objects which are most likely necessary (75% or greater chance of being used for example), and reserve creation of the other objects to when you know they are needed (i.e, right before they are used)?
I agree with that.
As I see it, you can do a collection of objects in one of three ways (assuming, of course, that the objects' data is somehow persisted between requests, which is mandatory in PHP as you so nicely explained):
a) Create all objects at the time of collection's creation and hold them in some sort of array. While perhaps the overhead of creating an object might not be too big here, if the objects are large (perhaps with other objects composed into them) and there's a lot of them it can quickly fill up the memory.
It would look something like this:
PHP Code:
class WidgetCollection
{
private $widgets = array();
public function __construct()
{
foreach ($this->getWidgetsFromDatabase() as $w) {
$this->widgets[] = new Widget($w);
}
}
public doSomethingWithWidgets()
{
foreach ($this->widgets as $w) {
$w->doSomething();
}
}
// ... other code
}
b) Keep only the identifiers of the objects in the collection, loading the source and instantiating the object only when needed:
PHP Code:
class WidgetCollection
{
private $widgetIds = array();
public function __construct()
{
foreach ($this->getWidgetIdsFromDatabase() as $w) {
$this->widgetIds[] = $w;
}
}
public doSomethingWithWidgets()
{
foreach ($this->widgetIds as $w) {
$this->getWidget($w)->doSomething();
}
}
public getWidget($w)
{
$widget = $this->getWidgetDataFromDatabase($w);
return new Widget($widget);
}
// ... other code
}
c) Keep an object that gets to be reused when necessary:
PHP Code:
class WidgetCollection
{
private $widgets = array();
private $widget;
public function __construct()
{
foreach ($this->getWidgetsFromDatabase() as $w) {
$this->widgets[] = $w;
}
$this->widget = new Widget();
}
public doSomethingWithWidgets()
{
foreach ($this->widgets as $w) {
$this->setWidget($w);
$this->widget->doSomething();
}
}
public getWidget($w)
{
$this->widget->set($w);
}
// ... other code
}
The latest seems like a good compromise, because a) it has only one call to the persistance repository (database in this case), b) has the lowest instantiation count (only one) and c) is fairly object-oriented. On the other hand the Widget class has to follow a strict interface, which should include at least a set() method and a constructor with no parameters; i.e. it should be able to exist uninitialized with data, which is not always possible.
Bookmarks