O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #51. Create Modular Interfaces

Use dynamic loading to allow users to write snap-in modules for your application.

Most of the really popular PHP open source applications have an extension mechanism that allows for PHP coders to write small fragments of code that are dynamically loaded into the application. This hack demonstrates an XML-based drawing script that you can extend simply by placing new PHP classes into a modules directory; of course, the point is not as much the drawing code as the way you can extend it easily.

The Code

Save the code in Example 6-1 as modhost.php.

Example 6-1. The code that handles a modular PHP architecture

<?php class DrawingEnvironment { private $img = null; private $x = null; private $y = null; private $colors = array(); public function __construct( $x, $y ) { $this->img = imagecreatetruecolor( $x, $y ); $this->addColor( 'white', 255, 255, 255 ); $this->addColor( 'black', 0, 0, 0 ); $this->addColor( 'red', 255, 0, 0 ); $this->addColor( 'green', 0, 255, 0 ); $this->addColor( 'blue', 0, 0, 255 ); imagefilledrectangle( $this->image(), 0, 0, $x, $y, $this->color( 'white' ) ); } public function image() { return $this->img; } public function size_x() { return $this->x; } public function size_y() { return $this->y; } public function color( $c ) { return $this->colors[$c]; } public function save( $file ) { imagepng( $this->img, $file ); } protected function addColor( $name, $r, $g, $b ) { $col = imagecolorallocate($this->img, $r, $g, $b); $this->colors[ $name ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required