Last active
December 22, 2017 10:42
-
-
Save lloc/1251665 to your computer and use it in GitHub Desktop.
Generic Decorator in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'generic-decorator.php'; | |
class Bar extends GenericDecorator { | |
public function get_bar() { | |
return number_format( $this->obj->get_bar(), 2, ',', '' ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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