Image for post: Decorator pattern in PHP

Decorator pattern in PHP

I wanted to build an object and keep the properties set during the process. Another class will extends the main application object without losing all previous properties.

<?phpabstract class application {private $config;private $channel, $controller;public function getConfig(){return $this->config;}}class app extends application {public function setUpDatabase(){}}// The config decorator will set the value of the final app classclass configDecorator {private $_app;// passing the app object...public function __construct(application $app){$this->_app = $app;}// Decorate the app propertypublic function setConfig($config){$this->_app->config = $config;}}/*** Usage ***/$app = new app();$configDecorator = new configDecorator($app);$configDecorator->setConfig('this is config');echo "<pre>".print_r($app, 1)."</pre>";

It's very simple. The abstract application object is the container of all properties. The class app extends application and the configDecorator decorate the config property. We have a dependency but it's ok, if we want to isolate all actions for  $config, we'll create a new class or we let there's no dependency between the main application and the config. I hope this will be useful  to build your own application using only OOP. No global variables are used :)

Tags