I'm trying to put several class instances (header, body, sidebar) inside another class instance (page). I figured out a way to do it but I'm not sure it's the best way - perhaps someone here can advise me.
All of my classes require at least two "calls" (if that's the right term). One to instantiate them (and in some cases, via constructors, set up initial parameters), a second to execute them and compile their results into an html template.
For instance:
class Body {
var $formatted_body;
function Body() {
// set initial parameters
}
function GenerateBody() {
// run a number of other functions to come up with
// the remaining parameters for the page
// read in body_template.html
// swap in parameters for placeholders in the template
$this->formatted_body = // template with parameters set
}
}
I have another class that takes all the formatted sections, combines them with an HTML template and outputs that to the browser
class Page {
var $head;
var $body;
var $sidebar;
function GeneratePage() {
// create array of the three page sections
// open the html template for the page
// go thru the template and swap each array element in for its placeholder
// echo the populated template to the browser
}
}
Calling the whole thing, I say:
$page =& new Page();
$head =& new Head();
$head->GenerateHead();
$page->head =& $head->formatted_head;
$body =& new Body();
$body->GenerateBody();
$page->body =& $body->formatted_body;
$sidebar =& new Sidebar();
$sidebar->GenerateSidebar();
$page->sidebar =& $body->formatted_sidebar;
$page->GeneratePage();
So basically I appear to be completely running through each page component class, getting the results from it, sticking it into another class and then outputting.
I'm wondering if I shouldn't just be creating the class instances of the page components within the overall Page class instance, and then "running" their "Generate" functions inside the Page instance - if I can do that, or if it even makes sense. I think it would look something like this:
$page =& new Page();
$page->head =& new Head();
$page->body =& new Body();
$page->sidebar =& new Sidebar();
// this is the part I'm not sure about...
$page->head->GenerateHead(); // run GenerateHead() on the instance of the "Head" class INSIDE the "Page" class
$page->body->GenerateBody(); // ditto for Body
$page->sidebar->GenerateSidebar(); // ditto for Sidebar
$page->GeneratePage();
The question - is this smart? Sane? Possible? Is this the right syntax for accessing an instance-within-an-instance?
And p.s. - am I using my pass-by-references right? ("=&") It's my first time out with these things...
Thanks for any advice you can offer.