Instantiate an object on request or on load using the delegator design pattern
Just looking for varying opinions and reasoning on this:
I want to maintain separate database tables for the delegated class should I:
A) Store the ID of the delegated objects record and initiate it on request like so ...
class Book {
private $Name;
private $Color_ID;
public
function getColor() {
return new Color($this - > Color_ID);
}
//etc
}
class Color {
private $Color_ID;
private $Color_Name;
public
function __construct($Color_ID) {
//Get from DB
}
//etc
}
B) Initiate and store the object on the parent initiation:
class B开发者_StackOverflowook {
private $Name;
private $Color;
public
function __construct() {
//Get $Color_ID from Books table
$this - > Color = new Color($Color_ID);
}
public
function getColor() {
return $Color;
}
//etc
}
class Color {
private $Color_ID;
private $Color_Name;
public
function __construct($Color_ID) {
//Get from DB
}
//etc
}
If I get lots of requests for the color object am I better to store it to save on DB reads? Is increased memory usage a good trade off? Thoughts..
Have a look at the lazy loading pattern.
http://en.wikipedia.org/wiki/Lazy_loading
http://martinfowler.com/eaaCatalog/lazyLoad.html
and probably identity map too:
http://martinfowler.com/eaaCatalog/identityMap.html
精彩评论