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
10 namespace Zend\ServiceManager\Di
;
13 use Zend\Di\Exception\ClassNotFoundException
as DiClassNotFoundException
;
14 use Zend\ServiceManager\Exception
;
15 use Zend\ServiceManager\FactoryInterface
;
16 use Zend\ServiceManager\ServiceLocatorInterface
;
18 class DiServiceFactory
extends Di
implements FactoryInterface
23 const USE_SL_BEFORE_DI
= 'before';
24 const USE_SL_AFTER_DI
= 'after';
25 const USE_SL_NONE
= 'none';
34 * @var \Zend\Di\InstanceManager
36 protected $name = null;
41 protected $parameters = [];
46 protected $useServiceLocator = self
::USE_SL_AFTER_DI
;
49 * @var ServiceLocatorInterface
51 protected $serviceLocator = null;
56 * @param \Zend\Di\Di $di
57 * @param null|\Zend\Di\InstanceManager $name
58 * @param array $parameters
59 * @param string $useServiceLocator
61 public function __construct(Di
$di, $name, array $parameters = [], $useServiceLocator = self
::USE_SL_NONE
)
65 $this->parameters
= $parameters;
66 if (in_array($useServiceLocator, [self
::USE_SL_BEFORE_DI
, self
::USE_SL_AFTER_DI
, self
::USE_SL_NONE
])) {
67 $this->useServiceLocator
= $useServiceLocator;
70 // since we are using this in a proxy-fashion, localize state
71 $this->definitions
= $this->di
->definitions
;
72 $this->instanceManager
= $this->di
->instanceManager
;
78 * @param ServiceLocatorInterface $serviceLocator
81 public function createService(ServiceLocatorInterface
$serviceLocator)
83 $this->serviceLocator
= $serviceLocator;
84 return $this->get($this->name
, $this->parameters
);
88 * Override, as we want it to use the functionality defined in the proxy
91 * @param array $params
93 * @throws Exception\ServiceNotFoundException
95 public function get($name, array $params = [])
97 // allow this di service to get dependencies from the service locator BEFORE trying di
98 if ($this->useServiceLocator
== self
::USE_SL_BEFORE_DI
&& $this->serviceLocator
->has($name)) {
99 return $this->serviceLocator
->get($name);
103 $service = parent
::get($name, $params);
105 } catch (DiClassNotFoundException
$e) {
106 // allow this di service to get dependencies from the service locator AFTER trying di
107 if ($this->useServiceLocator
== self
::USE_SL_AFTER_DI
&& $this->serviceLocator
->has($name)) {
108 return $this->serviceLocator
->get($name);
110 throw new Exception\
ServiceNotFoundException(
111 sprintf('Service %s was not found in this DI instance', $name),