Decorator pattern in PHP
I wanted to build an object and keep the properties set during the process. Another class will extend 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 the application and the configDecorator decorates 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 :)