|
Composition by inclusion and callback pattern |
This pattern is behind the page composition of phpPeanuts. It builds on the fact that the code from the included file is executed inside the function it is included from. For example let's say we have in 'myScript.php':
<?php require_once('MyPage.class.php'); $page = new MyPage(); $page->service(); ?>
in 'MyPage.class.php':
<?php
class MyPage {
function service() { include('MyPage.skin.php'); }
function printTitle() { print "My Page"; }
function printBodyPart() { require_once('MyBodyPart.class.php'); $part = new MyBodyPart(); $part->service(); } }
in 'MyPage.skin.php':
<HTML><HEAD> <TITLE><? $this->printTitle() ?></TITLE> </HEAD> <BODY> <?php $this->printBodyPart() ?> </BODY> </HTML>
in 'MyBodyPart.class.php':
class MyBodyPart {
function service() { include('MyBodyPart.skin.php'); }
function printMessage() { print "Hello World"; } }
in 'MyBodyPart.skin.php':
<B><?php $this->printMessage() ?></B>
Becuase the skin files are included inside methods, the $this variable will reference the object whose method includes the skin. This way we get: - separation of layout and OOP code, - pages composed from reusable parts And all this without a framework, without a template engine, all you need is to follow a simple pattern!
N.B. phpPeanuts uses different naming conventions for class and skin files. P.S. The user interface of pnt/unit is a more complete example following this pattern (pht/uint does not use any framework code except pnt/generalfunctions.php) |
|