sammela.com header image 2

How OpenCart Renders Pages

November 14th, 2009 · No Comments · article, news, opencart

The OpenCart Controller class contains a render method that is used to produce HTML pages output by all OpenCart classes that inherit from Controller class.

Here is how it works.

Each time a page is rendered, it is done with one top level controller. The top level controller may contain zero or more child controllers and it contains a template. Rendering proceed in the following order:

  1. Each child controller is rendered
  2. The top level controller is rendered, based on its own data and the output of the child controllers

That’s it. The rest is details which are described in the remainder of this article.

How the Template is Rendered

As stated previously, the top level controller render method produces output using a template. To accomplish this, it passes the template to the fetch method, which does the actual work.

The fetch Method

As stated previously, the top level controller render method produces output using a template. To accomplish this, it passes the template to the fetch method, which does the actual work.

The fetch method is not very long, but it does some clever things and it takes advantage of some very powerful features of PHP. Here is the operative code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Create local variables from the controller data array
extract($this->data);

// Initialize PHP output buffering
ob_start();  

// Load the template file, which is automatically
// populated with the local variables created above                                
require($file);

// Get the output of the template file
// Which has been echoed to the PHP output buffer
$content = ob_get_contents();

// Empty the PHP output buffer
ob_end_clean();

Basically, all information necessary to populate the template must be stored in the controller’s $data array. The native PHP extract function pulls the information out the the $data array and populates the local symbol table with it, so it is available to the template file.

Now here is the trick. The template file echoes its output; but since PHP buffering is turned on, the echoed HTML is not output to the client browser, but rather to the PHP output buffer. The fetch method stores the PHP output buffer contents in the $content variable and then returns it to the calling function. Cool beans.

But there’s more. Not only is this method used for the top level controller, but each of the controllers contained by the top level controller (the children) is evaluated the same way; and the children can contain their own children, theoretically without limit, although in practical terms it is unlikely they will go more than two or three levels deep.

© 2009, Sam Mela. All rights reserved.

Tags:

No Comments so far ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment