Overview

Namespaces

  • Budovy
  • Kdyby
    • BootstrapFormRenderer
      • DI
      • Latte
  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Diagnostics
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
      • Diagnostics
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • PhpGenerator
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
  • NetteModule
  • Nextras
    • Datagrid
  • None
  • PHP
  • Tester
    • CodeCoverage
    • Runner
      • Output
  • Vodacek
    • Forms
      • Controls
  • WebLoader
    • Filter
    • Nette

Classes

  • Compiler
  • CompilerExtension
  • Container
  • ContainerBuilder
  • Helpers
  • ServiceDefinition
  • Statement

Exceptions

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