Since traits aren't available in PHP 5.3 AFAIK I need to emulate some of the functionality they offer. Interfaces won't work because I need concrete functionality.
I have two client classes that need to share some functionality but extend from different base classes.
ClassA extends Foo {}
ClassB extends Bar {}
I need to be able to implement a function called getComponent() in both classes and it needs to be functionality identical.
Changing the base class is not an option. I was thinking to do something like this:
Class ComponentHandler {
function getInstance() {
//return singleton
}
function getComponent() {
//required functionality
}
}
Class A extends Foo {
var $handler;
function __construct() {
$this->handler = ComponentHandler::getInstance();
}
}
I would implement this constructor in both ClassA and ClassB. In my client I would make calls like this:
$class = new ClassA();
$class->handler->getComponent();
$class = new ClassB();
$class->handler->getComponent();
I prefer to pass objects via the constructor whenever possible. Your method has a dependency on the Class Name ComponentHandler
. By passing the object via the constructor and adding a type hint you are still adding a dependency, but one that allows you to create different type of ComponentHandler
s
Class A extends Foo {
var $handler;
function __construct( ComponentHandler $handler ) {
$this->handler = $handler
}
}
$componentHandler = ComponentHandler::getInstance();
$class = new ClassA( $componentHandler );
Class can take any handler that extends ComponentHandler, this will work too...
Class ComponentHandler2 extends ComponentHandler {}
$componentHandler = ComponentHandler2::getInstance();
$class = new ClassA( $componentHandler2 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With