1: <?php
2: /**
3: * A binder object for binding an interface to a closure.
4: *
5: * An interface may be bound to a closure. That closure must accept a
6: * Horde_Injector and return an object that satisfies the instance
7: * requirement. For example:
8: *
9: * <pre>
10: * $injector->bindClosure('database', function($injector) { return new my_mysql(); });
11: * </pre>
12: *
13: * @author Bob Mckee <bmckee@bywires.com>
14: * @author James Pepin <james@jamespepin.com>
15: * @author Chuck Hagenbuch <chuck@horde.org>
16: * @category Horde
17: * @package Injector
18: */
19: class Horde_Injector_Binder_Closure implements Horde_Injector_Binder
20: {
21: /**
22: * TODO
23: *
24: * @var Horde_Injector_Binder_Closure
25: */
26: private $_closure;
27:
28: /**
29: * Create a new Horde_Injector_Binder_Closure instance.
30: *
31: * @param string $closure The closure to use for creating objects.
32: */
33: public function __construct($closure)
34: {
35: $this->_closure = $closure;
36: }
37:
38: /**
39: * TODO
40: *
41: * @param Horde_Injector_Binder $otherBinder TODO
42: *
43: * @return boolean Equality.
44: */
45: public function equals(Horde_Injector_Binder $otherBinder)
46: {
47: return (($otherBinder instanceof Horde_Injector_Binder_Closure) &&
48: ($otherBinder->getClosure() == $this->_closure));
49: }
50:
51: /**
52: * Get the closure that this binder was bound to.
53: *
54: * @return callable The closure this binder is bound to.
55: */
56: public function getClosure()
57: {
58: return $this->_closure;
59: }
60:
61: /**
62: * Create instance using a closure
63: *
64: * If the closure depends on a Horde_Injector we want to limit its scope
65: * so it cannot change anything that effects any higher-level scope. A
66: * closure should not have the responsibility of making a higher-level
67: * scope change.
68: * To enforce this we create a new child Horde_Injector. When a
69: * Horde_Injector is requested from a Horde_Injector it will return
70: * itself. This means that the closure will only ever be able to work on
71: * the child Horde_Injector we give it now.
72: *
73: * @param Horde_Injector $injector Injector object.
74: *
75: * @return TODO
76: */
77: public function create(Horde_Injector $injector)
78: {
79: $childInjector = $injector->createChildInjector();
80: $closure = $this->_closure;
81:
82: return $closure($childInjector);
83: }
84:
85: }
86: