3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
15 * Simple service locator implementation capable of using closures to generate instances
17 class ServiceLocator
implements ServiceLocatorInterface
20 * Map of service names to methods
22 * As an example, you might define a getter method "getFoo", and map it to
23 * the service name "foo":
26 * protected $map = array('foo' => 'getFoo');
29 * When encountered, the return value of that method will be used.
31 * Methods mapped in this way may expect a single, array argument, the
32 * $params passed to {@link get()}, if any.
36 protected $map = array();
39 * Registered services and cached values
43 protected $services = array();
48 public function set($name, $service)
50 $this->services
[$name] = $service;
56 * Retrieve a registered service
58 * Tests first if a value is registered for the service, and, if so,
61 * If the value returned is a non-object callback or closure, the return
62 * value is retrieved, stored, and returned. Parameters passed to the method
63 * are passed to the callback, but only on the first retrieval.
65 * If the service requested matches a method in the method map, the return
66 * value of that method is returned. Parameters are passed to the matching
70 * @param array $params
73 public function get($name, array $params = array())
75 if (!isset($this->services
[$name])) {
76 if (!isset($this->map
[$name])) {
79 $method = $this->map
[$name];
81 return $this->$method($params);
84 $service = $this->services
[$name];
85 if ($service instanceof Closure
86 ||
(!is_object($service) && is_callable($service))
88 $this->services
[$name] = $service = call_user_func_array($service, $params);