<?php
interface Creatable
{
}
class FooCreatable implements Creatable
{
}
class BarCreatable implements Creatable
{
}
interface Creator
{
/**
*
* @param string $input
* @param Creatable $creatable
* @return bool
*/
function tryCreate($input, Creatable &$creatable = null);
}
class AggregateCreator implements Creator
{
/**
*
* @var Creator[]
*/
private $creators = [];
/**
*
* @param Creator[] $creators
*/
public function __construct($creators)
{
$this->creators = $creators;
}
/**
*
* @param string $input
* @param Creatable $creatable
* @return bool
*/
public function tryCreate($input, Creatable &$creatable = null)
{
foreach ($this->creators as $creator)
{
if ($creator->tryCreate($input, $creatable))
{
return true;
}
}
return false;
}
}
class FooCreator implements Creator
{
/**
*
* @param string $input
* @param Creatable $creatable
* @return bool
*/
public function tryCreate($input, Creatable &$creatable = null)
{
if ($input == 'foo')
{
$creatable = new FooCreatable;
return true;
}
return false;
}
}
class BarCreator implements Creator
{
/**
*
* @param string $input
* @param Creatable $creatable
* @return bool
*/
public function tryCreate($input, Creatable &$creatable = null)
{
if ($input == 'bar')
{
$creatable = new BarCreatable;
return true;
}
return false;
}
}
$creator = new AggregateCreator([
new FooCreator,
new BarCreator,
]);
$creatable = null;
var_dump($creator->tryCreate('foo', $creatable), $creatable);
$creatable = null;
var_dump($creator->tryCreate('bar', $creatable), $creatable);
$creatable = null;
var_dump($creator->tryCreate('qux', $creatable), $creatable);
preferences:
58.77 ms | 402 KiB | 5 Q