Skip to content

Instantly share code, notes, and snippets.

@dry
Created December 7, 2011 20:50
Show Gist options
  • Save dry/1444586 to your computer and use it in GitHub Desktop.
Save dry/1444586 to your computer and use it in GitHub Desktop.
A possible way to simulate mixins in PHP
<?php
class Person {
private $mixins = array();
private $instances = array();
public function __construct()
{
if (func_num_args())
{
foreach(func_get_args() AS $mixin)
{
$reflection = new ReflectionClass($mixin);
$methods = $reflection->getMethods();
foreach($methods AS $method)
{
$this->mixins[$method->name] = array('class' => $mixin);
}
}
}
}
public function __call($name, $arguments)
{
if (isset($this->mixins[$name]))
{
if ( ! isset($this->instances[$this->mixins[$name]['class']]))
{
$this->instances[$this->mixins[$name]['class']] = new $this->mixins[$name]['class'];
}
call_user_func_array(array($this->instances[$this->mixins[$name]['class']], $name), $arguments);
}
else
{
throw new Exception('Method not found');
}
}
public function walk()
{
print 'A person can walk'.PHP_EOL;
}
}
class WaiterMixin {
private static $at;
public function __construct()
{
self::$at = microtime(TRUE);
}
public function say($something = '')
{
if ($something)
{
print 'The waiter would say it like this: '.implode(' and ', (array) $something).PHP_EOL;
}
else
{
print 'The waiter mixin was instantiated at '.self::$at.'. A waiter would say "Vodka sir?"'.PHP_EOL;
}
}
public function wave()
{
print 'The waiter mixin was instantiated at '.self::$at.'. A waiter waves like this \/'.PHP_EOL;
}
}
class MechanicMixin {
public function say($something = '')
{
if ($something)
{
print 'The mechanic would say it like this: '.implode(' and ', (array) $something).PHP_EOL;
}
else
{
print 'Alright Guv, this needs a new exhaust'.PHP_EOL;
}
}
}
$person = new Person('WaiterMixin', 'MechanicMixin');
$person->walk();
$person->say();
$person->wave();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment