Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Utils
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • Compiler
  • CompilerExtension
  • Container
  • ContainerBuilder
  • ContainerLoader
  • DependencyChecker
  • PhpGenerator
  • ServiceDefinition
  • Statement

Exceptions

  • MissingServiceException
  • ServiceCreationException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\DI;
  9: 
 10: use Nette;
 11: 
 12: 
 13: /**
 14:  * The dependency injection container default implementation.
 15:  */
 16: class Container
 17: {
 18:     use Nette\SmartObject;
 19: 
 20:     const TAGS = 'tags';
 21:     const TYPES = 'types';
 22:     const SERVICES = 'services';
 23:     const ALIASES = 'aliases';
 24: 
 25:     /** @var array  user parameters */
 26:     /*private*/public $parameters = [];
 27: 
 28:     /** @var object[]  storage for shared objects */
 29:     private $registry = [];
 30: 
 31:     /** @var array[] */
 32:     protected $meta = [];
 33: 
 34:     /** @var array circular reference detector */
 35:     private $creating;
 36: 
 37: 
 38:     public function __construct(array $params = [])
 39:     {
 40:         $this->parameters = $params + $this->parameters;
 41:     }
 42: 
 43: 
 44:     /**
 45:      * @return array
 46:      */
 47:     public function getParameters()
 48:     {
 49:         return $this->parameters;
 50:     }
 51: 
 52: 
 53:     /**
 54:      * Adds the service to the container.
 55:      * @param  string
 56:      * @param  object
 57:      * @return self
 58:      */
 59:     public function addService($name, $service)
 60:     {
 61:         if (!is_string($name) || !$name) {
 62:             throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name)));
 63: 
 64:         }
 65:         $name = isset($this->meta[self::ALIASES][$name]) ? $this->meta[self::ALIASES][$name] : $name;
 66:         if (isset($this->registry[$name])) {
 67:             throw new Nette\InvalidStateException("Service '$name' already exists.");
 68: 
 69:         } elseif (!is_object($service)) {
 70:             throw new Nette\InvalidArgumentException(sprintf("Service '%s' must be a object, %s given.", $name, gettype($service)));
 71: 
 72:         } elseif (isset($this->meta[self::SERVICES][$name]) && !$service instanceof $this->meta[self::SERVICES][$name]) {
 73:             throw new Nette\InvalidArgumentException(sprintf("Service '%s' must be instance of %s, %s given.", $name, $this->meta[self::SERVICES][$name], get_class($service)));
 74:         }
 75: 
 76:         $this->registry[$name] = $service;
 77:         return $this;
 78:     }
 79: 
 80: 
 81:     /**
 82:      * Removes the service from the container.
 83:      * @param  string
 84:      * @return void
 85:      */
 86:     public function removeService($name)
 87:     {
 88:         $name = isset($this->meta[self::ALIASES][$name]) ? $this->meta[self::ALIASES][$name] : $name;
 89:         unset($this->registry[$name]);
 90:     }
 91: 
 92: 
 93:     /**
 94:      * Gets the service object by name.
 95:      * @param  string
 96:      * @return object
 97:      * @throws MissingServiceException
 98:      */
 99:     public function getService($name)
100:     {
101:         if (!isset($this->registry[$name])) {
102:             if (isset($this->meta[self::ALIASES][$name])) {
103:                 return $this->getService($this->meta[self::ALIASES][$name]);
104:             }
105:             $this->registry[$name] = $this->createService($name);
106:         }
107:         return $this->registry[$name];
108:     }
109: 
110: 
111:     /**
112:      * Gets the service type by name.
113:      * @param  string
114:      * @return string
115:      * @throws MissingServiceException
116:      */
117:     public function getServiceType($name)
118:     {
119:         if (isset($this->meta[self::ALIASES][$name])) {
120:             return $this->getServiceType($this->meta[self::ALIASES][$name]);
121: 
122:         } elseif (isset($this->meta[self::SERVICES][$name])) {
123:             return $this->meta[self::SERVICES][$name];
124: 
125:         } else {
126:             throw new MissingServiceException("Service '$name' not found.");
127:         }
128:     }
129: 
130: 
131:     /**
132:      * Does the service exist?
133:      * @param  string service name
134:      * @return bool
135:      */
136:     public function hasService($name)
137:     {
138:         $name = isset($this->meta[self::ALIASES][$name]) ? $this->meta[self::ALIASES][$name] : $name;
139:         return isset($this->registry[$name])
140:             || (method_exists($this, $method = self::getMethodName($name))
141:                 && (new \ReflectionMethod($this, $method))->getName() === $method);
142:     }
143: 
144: 
145:     /**
146:      * Is the service created?
147:      * @param  string service name
148:      * @return bool
149:      */
150:     public function isCreated($name)
151:     {
152:         if (!$this->hasService($name)) {
153:             throw new MissingServiceException("Service '$name' not found.");
154:         }
155:         $name = isset($this->meta[self::ALIASES][$name]) ? $this->meta[self::ALIASES][$name] : $name;
156:         return isset($this->registry[$name]);
157:     }
158: 
159: 
160:     /**
161:      * Creates new instance of the service.
162:      * @param  string service name
163:      * @return object
164:      * @throws MissingServiceException
165:      */
166:     public function createService($name, array $args = [])
167:     {
168:         $name = isset($this->meta[self::ALIASES][$name]) ? $this->meta[self::ALIASES][$name] : $name;
169:         $method = self::getMethodName($name);
170:         if (isset($this->creating[$name])) {
171:             throw new Nette\InvalidStateException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($this->creating))));
172: 
173:         } elseif (!method_exists($this, $method) || (new \ReflectionMethod($this, $method))->getName() !== $method) {
174:             throw new MissingServiceException("Service '$name' not found.");
175:         }
176: 
177:         try {
178:             $this->creating[$name] = TRUE;
179:             $service = $this->$method(...$args);
180: 
181:         } finally {
182:             unset($this->creating[$name]);
183:         }
184: 
185:         if (!is_object($service)) {
186:             throw new Nette\UnexpectedValueException("Unable to create service '$name', value returned by method $method() is not object.");
187:         }
188: 
189:         return $service;
190:     }
191: 
192: 
193:     /**
194:      * Resolves service by type.
195:      * @param  string  class or interface
196:      * @param  bool    throw exception if service doesn't exist?
197:      * @return object  service or NULL
198:      * @throws MissingServiceException
199:      */
200:     public function getByType($class, $need = TRUE)
201:     {
202:         $class = ltrim($class, '\\');
203:         if (!empty($this->meta[self::TYPES][$class][TRUE])) {
204:             if (count($names = $this->meta[self::TYPES][$class][TRUE]) === 1) {
205:                 return $this->getService($names[0]);
206:             }
207:             throw new MissingServiceException("Multiple services of type $class found: " . implode(', ', $names) . '.');
208: 
209:         } elseif ($need) {
210:             throw new MissingServiceException("Service of type $class not found.");
211:         }
212:     }
213: 
214: 
215:     /**
216:      * Gets the service names of the specified type.
217:      * @param  string
218:      * @return string[]
219:      */
220:     public function findByType($class)
221:     {
222:         $class = ltrim($class, '\\');
223:         return empty($this->meta[self::TYPES][$class])
224:             ? []
225:             : array_merge(...array_values($this->meta[self::TYPES][$class]));
226:     }
227: 
228: 
229:     /**
230:      * Gets the service names of the specified tag.
231:      * @param  string
232:      * @return array of [service name => tag attributes]
233:      */
234:     public function findByTag($tag)
235:     {
236:         return isset($this->meta[self::TAGS][$tag]) ? $this->meta[self::TAGS][$tag] : [];
237:     }
238: 
239: 
240:     /********************* autowiring ****************d*g**/
241: 
242: 
243:     /**
244:      * Creates new instance using autowiring.
245:      * @param  string  class
246:      * @param  array   arguments
247:      * @return object
248:      * @throws Nette\InvalidArgumentException
249:      */
250:     public function createInstance($class, array $args = [])
251:     {
252:         $rc = new \ReflectionClass($class);
253:         if (!$rc->isInstantiable()) {
254:             throw new ServiceCreationException("Class $class is not instantiable.");
255: 
256:         } elseif ($constructor = $rc->getConstructor()) {
257:             return $rc->newInstanceArgs(Helpers::autowireArguments($constructor, $args, $this));
258: 
259:         } elseif ($args) {
260:             throw new ServiceCreationException("Unable to pass arguments, class $class has no constructor.");
261:         }
262:         return new $class;
263:     }
264: 
265: 
266:     /**
267:      * Calls all methods starting with with "inject" using autowiring.
268:      * @param  object
269:      * @return void
270:      */
271:     public function callInjects($service)
272:     {
273:         Extensions\InjectExtension::callInjects($this, $service);
274:     }
275: 
276: 
277:     /**
278:      * Calls method using autowiring.
279:      * @return mixed
280:      */
281:     public function callMethod(callable $function, array $args = [])
282:     {
283:         return $function(...Helpers::autowireArguments(Nette\Utils\Callback::toReflection($function), $args, $this));
284:     }
285: 
286: 
287:     /********************* shortcuts ****************d*g**/
288: 
289: 
290:     /**
291:      * Expands %placeholders%.
292:      * @param  mixed
293:      * @return mixed
294:      * @deprecated
295:      */
296:     public function expand($s)
297:     {
298:         return Helpers::expand($s, $this->parameters);
299:     }
300: 
301: 
302:     /** @deprecated */
303:     public function &__get($name)
304:     {
305:         trigger_error(__METHOD__ . ' is deprecated; use getService().', E_USER_DEPRECATED);
306:         $tmp = $this->getService($name);
307:         return $tmp;
308:     }
309: 
310: 
311:     /** @deprecated */
312:     public function __set($name, $service)
313:     {
314:         trigger_error(__METHOD__ . ' is deprecated; use addService().', E_USER_DEPRECATED);
315:         $this->addService($name, $service);
316:     }
317: 
318: 
319:     /** @deprecated */
320:     public function __isset($name)
321:     {
322:         trigger_error(__METHOD__ . ' is deprecated; use hasService().', E_USER_DEPRECATED);
323:         return $this->hasService($name);
324:     }
325: 
326: 
327:     /** @deprecated */
328:     public function __unset($name)
329:     {
330:         trigger_error(__METHOD__ . ' is deprecated; use removeService().', E_USER_DEPRECATED);
331:         $this->removeService($name);
332:     }
333: 
334: 
335:     public static function getMethodName($name)
336:     {
337:         $uname = ucfirst($name);
338:         return 'createService' . ((string) $name === $uname ? '__' : '') . str_replace('.', '__', $uname);
339:     }
340: 
341: }
342: 
Nette 2.4-20161109 API API documentation generated by ApiGen 2.8.0