Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What design pattern can I use to emulate traits / mixins in PHP?

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.

Problem:

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();
like image 225
james Avatar asked Apr 26 '11 14:04

james


1 Answers

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 ComponentHandlers

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 );
like image 60
Galen Avatar answered Sep 20 '22 17:09

Galen