zendframework/zf2 — pull request #4110 by Ocramius (2013-03-25 19:56:29+00:00)
Title: [RFC] Delegate factories

I've been working on this concept for some time, but this is basically a cleaned up version of #2995

The idea is to be able to build "[delegates](http://en.wikipedia.org/wiki/Delegation_pattern)" of any existing service.

Here's how it would work (the test explains it too):

```phpuse Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\DelegateFactoryInterface;

require_once __DIR__ . '/vendor/autoload.php';

class FooDelegateFactory implements DelegateFactoryInterface
{
public function createDelegateWithName(
ServiceLocatorInterface $serviceLocator,
$name,
$requestedName,
$callback
) {
$foo = new \stdClass();
$foo->tab = $callback(); // php5.4, heh

return $foo;
}
}

$serviceManager = new ServiceManager();
$serviceManager->setFactory('foo', function() {
$foo = new \stdClass();
$foo->bar = 'baz';

return $foo;
});
$serviceManager->setService('foo-delegate-factory',new FooDelegateFactory());
$serviceManager->setDelegate('foo', 'foo-delegate-factory');

var_dump($serviceManager->get('foo')->tab->bar); // baz
```

Current flaws of this implementation:

* Additional method call to `doCreate`, since I splitted `create` to allow this kind of behavior
* `doCreate` is public, since I cannot use a closure and call `->bindTo($this)` in PHP 5.3
* It may not be clear at first, but the delegate factory is a service (which is a huge advantage, but is a bit different from what we're used to see)

Thoughts?