Skip to content

Instantly share code, notes, and snippets.

@lloc
Last active December 22, 2017 10:42
Show Gist options
  • Save lloc/1251665 to your computer and use it in GitHub Desktop.
Save lloc/1251665 to your computer and use it in GitHub Desktop.
Generic Decorator in PHP
<?php
require_once 'bar.php';
require_once 'foo.php';
$foo = new Foo;
$bar = new Bar( $foo );
$foo->set_foo( 123.4 );
$foo->set_bar( 123.4 );
// 123
echo $foo->get_foo() . "\n";
// 123.4
echo $foo->get_bar() . "\n";
// 123
echo $bar->get_foo() . "\n";
// 123,40
echo $bar->get_bar() . "\n";
$foo->set_bar( 123.6 );
// 123,60
echo $bar->get_bar() . "\n";
$bar->set_bar( 123.8 );
// 123,80
echo $bar->get_bar() . "\n";
<?php
require_once 'generic-decorator.php';
class Bar extends GenericDecorator {
public function get_bar() {
return number_format( $this->obj->get_bar(), 2, ',', '' );
}
}
<?php
class Foo {
private $_foo, $_bar;
public function set_foo( $value ) {
$this->_foo = (int) $value;
}
public function set_bar( $value ) {
$this->_bar = (float) $value;
}
public function get_foo() {
return $this->_foo;
}
public function get_bar() {
return $this->_bar;
}
}
<?php
class GenericDecorator {
protected $obj;
public function __construct( $obj ) {
$this->obj = $obj;
}
final public function __call( $method, $args ) {
return call_user_func_array( array( $this->obj, $method ), $args );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment