You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Container.php 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. <?php
  2. namespace Illuminate\Container;
  3. use Closure;
  4. use Exception;
  5. use ArrayAccess;
  6. use LogicException;
  7. use ReflectionClass;
  8. use ReflectionParameter;
  9. use Illuminate\Support\Arr;
  10. use Illuminate\Contracts\Container\BindingResolutionException;
  11. use Illuminate\Contracts\Container\Container as ContainerContract;
  12. class Container implements ArrayAccess, ContainerContract
  13. {
  14. /**
  15. * The current globally available container (if any).
  16. *
  17. * @var static
  18. */
  19. protected static $instance;
  20. /**
  21. * An array of the types that have been resolved.
  22. *
  23. * @var bool[]
  24. */
  25. protected $resolved = [];
  26. /**
  27. * The container's bindings.
  28. *
  29. * @var array[]
  30. */
  31. protected $bindings = [];
  32. /**
  33. * The container's method bindings.
  34. *
  35. * @var \Closure[]
  36. */
  37. protected $methodBindings = [];
  38. /**
  39. * The container's shared instances.
  40. *
  41. * @var object[]
  42. */
  43. protected $instances = [];
  44. /**
  45. * The registered type aliases.
  46. *
  47. * @var string[]
  48. */
  49. protected $aliases = [];
  50. /**
  51. * The registered aliases keyed by the abstract name.
  52. *
  53. * @var array[]
  54. */
  55. protected $abstractAliases = [];
  56. /**
  57. * The extension closures for services.
  58. *
  59. * @var array[]
  60. */
  61. protected $extenders = [];
  62. /**
  63. * All of the registered tags.
  64. *
  65. * @var array[]
  66. */
  67. protected $tags = [];
  68. /**
  69. * The stack of concretions currently being built.
  70. *
  71. * @var array[]
  72. */
  73. protected $buildStack = [];
  74. /**
  75. * The parameter override stack.
  76. *
  77. * @var array[]
  78. */
  79. protected $with = [];
  80. /**
  81. * The contextual binding map.
  82. *
  83. * @var array[]
  84. */
  85. public $contextual = [];
  86. /**
  87. * All of the registered rebound callbacks.
  88. *
  89. * @var array[]
  90. */
  91. protected $reboundCallbacks = [];
  92. /**
  93. * All of the global resolving callbacks.
  94. *
  95. * @var \Closure[]
  96. */
  97. protected $globalResolvingCallbacks = [];
  98. /**
  99. * All of the global after resolving callbacks.
  100. *
  101. * @var \Closure[]
  102. */
  103. protected $globalAfterResolvingCallbacks = [];
  104. /**
  105. * All of the resolving callbacks by class type.
  106. *
  107. * @var array[]
  108. */
  109. protected $resolvingCallbacks = [];
  110. /**
  111. * All of the after resolving callbacks by class type.
  112. *
  113. * @var array[]
  114. */
  115. protected $afterResolvingCallbacks = [];
  116. /**
  117. * Define a contextual binding.
  118. *
  119. * @param array|string $concrete
  120. * @return \Illuminate\Contracts\Container\ContextualBindingBuilder
  121. */
  122. public function when($concrete)
  123. {
  124. $aliases = [];
  125. foreach (Arr::wrap($concrete) as $c) {
  126. $aliases[] = $this->getAlias($c);
  127. }
  128. return new ContextualBindingBuilder($this, $aliases);
  129. }
  130. /**
  131. * Determine if the given abstract type has been bound.
  132. *
  133. * @param string $abstract
  134. * @return bool
  135. */
  136. public function bound($abstract)
  137. {
  138. return isset($this->bindings[$abstract]) ||
  139. isset($this->instances[$abstract]) ||
  140. $this->isAlias($abstract);
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. public function has($id)
  146. {
  147. return $this->bound($id);
  148. }
  149. /**
  150. * Determine if the given abstract type has been resolved.
  151. *
  152. * @param string $abstract
  153. * @return bool
  154. */
  155. public function resolved($abstract)
  156. {
  157. if ($this->isAlias($abstract)) {
  158. $abstract = $this->getAlias($abstract);
  159. }
  160. return isset($this->resolved[$abstract]) ||
  161. isset($this->instances[$abstract]);
  162. }
  163. /**
  164. * Determine if a given type is shared.
  165. *
  166. * @param string $abstract
  167. * @return bool
  168. */
  169. public function isShared($abstract)
  170. {
  171. return isset($this->instances[$abstract]) ||
  172. (isset($this->bindings[$abstract]['shared']) &&
  173. $this->bindings[$abstract]['shared'] === true);
  174. }
  175. /**
  176. * Determine if a given string is an alias.
  177. *
  178. * @param string $name
  179. * @return bool
  180. */
  181. public function isAlias($name)
  182. {
  183. return isset($this->aliases[$name]);
  184. }
  185. /**
  186. * Register a binding with the container.
  187. *
  188. * @param string $abstract
  189. * @param \Closure|string|null $concrete
  190. * @param bool $shared
  191. * @return void
  192. */
  193. public function bind($abstract, $concrete = null, $shared = false)
  194. {
  195. $this->dropStaleInstances($abstract);
  196. // If no concrete type was given, we will simply set the concrete type to the
  197. // abstract type. After that, the concrete type to be registered as shared
  198. // without being forced to state their classes in both of the parameters.
  199. if (is_null($concrete)) {
  200. $concrete = $abstract;
  201. }
  202. // If the factory is not a Closure, it means it is just a class name which is
  203. // bound into this container to the abstract type and we will just wrap it
  204. // up inside its own Closure to give us more convenience when extending.
  205. if (! $concrete instanceof Closure) {
  206. $concrete = $this->getClosure($abstract, $concrete);
  207. }
  208. $this->bindings[$abstract] = compact('concrete', 'shared');
  209. // If the abstract type was already resolved in this container we'll fire the
  210. // rebound listener so that any objects which have already gotten resolved
  211. // can have their copy of the object updated via the listener callbacks.
  212. if ($this->resolved($abstract)) {
  213. $this->rebound($abstract);
  214. }
  215. }
  216. /**
  217. * Get the Closure to be used when building a type.
  218. *
  219. * @param string $abstract
  220. * @param string $concrete
  221. * @return \Closure
  222. */
  223. protected function getClosure($abstract, $concrete)
  224. {
  225. return function ($container, $parameters = []) use ($abstract, $concrete) {
  226. if ($abstract == $concrete) {
  227. return $container->build($concrete);
  228. }
  229. return $container->resolve(
  230. $concrete, $parameters, $raiseEvents = false
  231. );
  232. };
  233. }
  234. /**
  235. * Determine if the container has a method binding.
  236. *
  237. * @param string $method
  238. * @return bool
  239. */
  240. public function hasMethodBinding($method)
  241. {
  242. return isset($this->methodBindings[$method]);
  243. }
  244. /**
  245. * Bind a callback to resolve with Container::call.
  246. *
  247. * @param array|string $method
  248. * @param \Closure $callback
  249. * @return void
  250. */
  251. public function bindMethod($method, $callback)
  252. {
  253. $this->methodBindings[$this->parseBindMethod($method)] = $callback;
  254. }
  255. /**
  256. * Get the method to be bound in class@method format.
  257. *
  258. * @param array|string $method
  259. * @return string
  260. */
  261. protected function parseBindMethod($method)
  262. {
  263. if (is_array($method)) {
  264. return $method[0].'@'.$method[1];
  265. }
  266. return $method;
  267. }
  268. /**
  269. * Get the method binding for the given method.
  270. *
  271. * @param string $method
  272. * @param mixed $instance
  273. * @return mixed
  274. */
  275. public function callMethodBinding($method, $instance)
  276. {
  277. return call_user_func($this->methodBindings[$method], $instance, $this);
  278. }
  279. /**
  280. * Add a contextual binding to the container.
  281. *
  282. * @param string $concrete
  283. * @param string $abstract
  284. * @param \Closure|string $implementation
  285. * @return void
  286. */
  287. public function addContextualBinding($concrete, $abstract, $implementation)
  288. {
  289. $this->contextual[$concrete][$this->getAlias($abstract)] = $implementation;
  290. }
  291. /**
  292. * Register a binding if it hasn't already been registered.
  293. *
  294. * @param string $abstract
  295. * @param \Closure|string|null $concrete
  296. * @param bool $shared
  297. * @return void
  298. */
  299. public function bindIf($abstract, $concrete = null, $shared = false)
  300. {
  301. if (! $this->bound($abstract)) {
  302. $this->bind($abstract, $concrete, $shared);
  303. }
  304. }
  305. /**
  306. * Register a shared binding in the container.
  307. *
  308. * @param string $abstract
  309. * @param \Closure|string|null $concrete
  310. * @return void
  311. */
  312. public function singleton($abstract, $concrete = null)
  313. {
  314. $this->bind($abstract, $concrete, true);
  315. }
  316. /**
  317. * "Extend" an abstract type in the container.
  318. *
  319. * @param string $abstract
  320. * @param \Closure $closure
  321. * @return void
  322. *
  323. * @throws \InvalidArgumentException
  324. */
  325. public function extend($abstract, Closure $closure)
  326. {
  327. $abstract = $this->getAlias($abstract);
  328. if (isset($this->instances[$abstract])) {
  329. $this->instances[$abstract] = $closure($this->instances[$abstract], $this);
  330. $this->rebound($abstract);
  331. } else {
  332. $this->extenders[$abstract][] = $closure;
  333. if ($this->resolved($abstract)) {
  334. $this->rebound($abstract);
  335. }
  336. }
  337. }
  338. /**
  339. * Register an existing instance as shared in the container.
  340. *
  341. * @param string $abstract
  342. * @param mixed $instance
  343. * @return mixed
  344. */
  345. public function instance($abstract, $instance)
  346. {
  347. $this->removeAbstractAlias($abstract);
  348. $isBound = $this->bound($abstract);
  349. unset($this->aliases[$abstract]);
  350. // We'll check to determine if this type has been bound before, and if it has
  351. // we will fire the rebound callbacks registered with the container and it
  352. // can be updated with consuming classes that have gotten resolved here.
  353. $this->instances[$abstract] = $instance;
  354. if ($isBound) {
  355. $this->rebound($abstract);
  356. }
  357. return $instance;
  358. }
  359. /**
  360. * Remove an alias from the contextual binding alias cache.
  361. *
  362. * @param string $searched
  363. * @return void
  364. */
  365. protected function removeAbstractAlias($searched)
  366. {
  367. if (! isset($this->aliases[$searched])) {
  368. return;
  369. }
  370. foreach ($this->abstractAliases as $abstract => $aliases) {
  371. foreach ($aliases as $index => $alias) {
  372. if ($alias == $searched) {
  373. unset($this->abstractAliases[$abstract][$index]);
  374. }
  375. }
  376. }
  377. }
  378. /**
  379. * Assign a set of tags to a given binding.
  380. *
  381. * @param array|string $abstracts
  382. * @param array|mixed ...$tags
  383. * @return void
  384. */
  385. public function tag($abstracts, $tags)
  386. {
  387. $tags = is_array($tags) ? $tags : array_slice(func_get_args(), 1);
  388. foreach ($tags as $tag) {
  389. if (! isset($this->tags[$tag])) {
  390. $this->tags[$tag] = [];
  391. }
  392. foreach ((array) $abstracts as $abstract) {
  393. $this->tags[$tag][] = $abstract;
  394. }
  395. }
  396. }
  397. /**
  398. * Resolve all of the bindings for a given tag.
  399. *
  400. * @param string $tag
  401. * @return iterable
  402. */
  403. public function tagged($tag)
  404. {
  405. if (! isset($this->tags[$tag])) {
  406. return [];
  407. }
  408. return new RewindableGenerator(function () use ($tag) {
  409. foreach ($this->tags[$tag] as $abstract) {
  410. yield $this->make($abstract);
  411. }
  412. }, count($this->tags[$tag]));
  413. }
  414. /**
  415. * Alias a type to a different name.
  416. *
  417. * @param string $abstract
  418. * @param string $alias
  419. * @return void
  420. *
  421. * @throws \LogicException
  422. */
  423. public function alias($abstract, $alias)
  424. {
  425. if ($alias === $abstract) {
  426. throw new LogicException("[{$abstract}] is aliased to itself.");
  427. }
  428. $this->aliases[$alias] = $abstract;
  429. $this->abstractAliases[$abstract][] = $alias;
  430. }
  431. /**
  432. * Bind a new callback to an abstract's rebind event.
  433. *
  434. * @param string $abstract
  435. * @param \Closure $callback
  436. * @return mixed
  437. */
  438. public function rebinding($abstract, Closure $callback)
  439. {
  440. $this->reboundCallbacks[$abstract = $this->getAlias($abstract)][] = $callback;
  441. if ($this->bound($abstract)) {
  442. return $this->make($abstract);
  443. }
  444. }
  445. /**
  446. * Refresh an instance on the given target and method.
  447. *
  448. * @param string $abstract
  449. * @param mixed $target
  450. * @param string $method
  451. * @return mixed
  452. */
  453. public function refresh($abstract, $target, $method)
  454. {
  455. return $this->rebinding($abstract, function ($app, $instance) use ($target, $method) {
  456. $target->{$method}($instance);
  457. });
  458. }
  459. /**
  460. * Fire the "rebound" callbacks for the given abstract type.
  461. *
  462. * @param string $abstract
  463. * @return void
  464. */
  465. protected function rebound($abstract)
  466. {
  467. $instance = $this->make($abstract);
  468. foreach ($this->getReboundCallbacks($abstract) as $callback) {
  469. call_user_func($callback, $this, $instance);
  470. }
  471. }
  472. /**
  473. * Get the rebound callbacks for a given type.
  474. *
  475. * @param string $abstract
  476. * @return array
  477. */
  478. protected function getReboundCallbacks($abstract)
  479. {
  480. if (isset($this->reboundCallbacks[$abstract])) {
  481. return $this->reboundCallbacks[$abstract];
  482. }
  483. return [];
  484. }
  485. /**
  486. * Wrap the given closure such that its dependencies will be injected when executed.
  487. *
  488. * @param \Closure $callback
  489. * @param array $parameters
  490. * @return \Closure
  491. */
  492. public function wrap(Closure $callback, array $parameters = [])
  493. {
  494. return function () use ($callback, $parameters) {
  495. return $this->call($callback, $parameters);
  496. };
  497. }
  498. /**
  499. * Call the given Closure / class@method and inject its dependencies.
  500. *
  501. * @param callable|string $callback
  502. * @param array $parameters
  503. * @param string|null $defaultMethod
  504. * @return mixed
  505. */
  506. public function call($callback, array $parameters = [], $defaultMethod = null)
  507. {
  508. return BoundMethod::call($this, $callback, $parameters, $defaultMethod);
  509. }
  510. /**
  511. * Get a closure to resolve the given type from the container.
  512. *
  513. * @param string $abstract
  514. * @return \Closure
  515. */
  516. public function factory($abstract)
  517. {
  518. return function () use ($abstract) {
  519. return $this->make($abstract);
  520. };
  521. }
  522. /**
  523. * An alias function name for make().
  524. *
  525. * @param string $abstract
  526. * @param array $parameters
  527. * @return mixed
  528. */
  529. public function makeWith($abstract, array $parameters = [])
  530. {
  531. return $this->make($abstract, $parameters);
  532. }
  533. /**
  534. * Resolve the given type from the container.
  535. *
  536. * @param string $abstract
  537. * @param array $parameters
  538. * @return mixed
  539. *
  540. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  541. */
  542. public function make($abstract, array $parameters = [])
  543. {
  544. return $this->resolve($abstract, $parameters);
  545. }
  546. /**
  547. * {@inheritdoc}
  548. */
  549. public function get($id)
  550. {
  551. try {
  552. return $this->resolve($id);
  553. } catch (Exception $e) {
  554. if ($this->has($id)) {
  555. throw $e;
  556. }
  557. throw new EntryNotFoundException;
  558. }
  559. }
  560. /**
  561. * Resolve the given type from the container.
  562. *
  563. * @param string $abstract
  564. * @param array $parameters
  565. * @param bool $raiseEvents
  566. * @return mixed
  567. *
  568. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  569. */
  570. protected function resolve($abstract, $parameters = [], $raiseEvents = true)
  571. {
  572. $abstract = $this->getAlias($abstract);
  573. $needsContextualBuild = ! empty($parameters) || ! is_null(
  574. $this->getContextualConcrete($abstract)
  575. );
  576. // If an instance of the type is currently being managed as a singleton we'll
  577. // just return an existing instance instead of instantiating new instances
  578. // so the developer can keep using the same objects instance every time.
  579. if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
  580. return $this->instances[$abstract];
  581. }
  582. $this->with[] = $parameters;
  583. $concrete = $this->getConcrete($abstract);
  584. // We're ready to instantiate an instance of the concrete type registered for
  585. // the binding. This will instantiate the types, as well as resolve any of
  586. // its "nested" dependencies recursively until all have gotten resolved.
  587. if ($this->isBuildable($concrete, $abstract)) {
  588. $object = $this->build($concrete);
  589. } else {
  590. $object = $this->make($concrete);
  591. }
  592. // If we defined any extenders for this type, we'll need to spin through them
  593. // and apply them to the object being built. This allows for the extension
  594. // of services, such as changing configuration or decorating the object.
  595. foreach ($this->getExtenders($abstract) as $extender) {
  596. $object = $extender($object, $this);
  597. }
  598. // If the requested type is registered as a singleton we'll want to cache off
  599. // the instances in "memory" so we can return it later without creating an
  600. // entirely new instance of an object on each subsequent request for it.
  601. if ($this->isShared($abstract) && ! $needsContextualBuild) {
  602. $this->instances[$abstract] = $object;
  603. }
  604. if ($raiseEvents) {
  605. $this->fireResolvingCallbacks($abstract, $object);
  606. }
  607. // Before returning, we will also set the resolved flag to "true" and pop off
  608. // the parameter overrides for this build. After those two things are done
  609. // we will be ready to return back the fully constructed class instance.
  610. $this->resolved[$abstract] = true;
  611. array_pop($this->with);
  612. return $object;
  613. }
  614. /**
  615. * Get the concrete type for a given abstract.
  616. *
  617. * @param string $abstract
  618. * @return mixed $concrete
  619. */
  620. protected function getConcrete($abstract)
  621. {
  622. if (! is_null($concrete = $this->getContextualConcrete($abstract))) {
  623. return $concrete;
  624. }
  625. // If we don't have a registered resolver or concrete for the type, we'll just
  626. // assume each type is a concrete name and will attempt to resolve it as is
  627. // since the container should be able to resolve concretes automatically.
  628. if (isset($this->bindings[$abstract])) {
  629. return $this->bindings[$abstract]['concrete'];
  630. }
  631. return $abstract;
  632. }
  633. /**
  634. * Get the contextual concrete binding for the given abstract.
  635. *
  636. * @param string $abstract
  637. * @return \Closure|string|null
  638. */
  639. protected function getContextualConcrete($abstract)
  640. {
  641. if (! is_null($binding = $this->findInContextualBindings($abstract))) {
  642. return $binding;
  643. }
  644. // Next we need to see if a contextual binding might be bound under an alias of the
  645. // given abstract type. So, we will need to check if any aliases exist with this
  646. // type and then spin through them and check for contextual bindings on these.
  647. if (empty($this->abstractAliases[$abstract])) {
  648. return;
  649. }
  650. foreach ($this->abstractAliases[$abstract] as $alias) {
  651. if (! is_null($binding = $this->findInContextualBindings($alias))) {
  652. return $binding;
  653. }
  654. }
  655. }
  656. /**
  657. * Find the concrete binding for the given abstract in the contextual binding array.
  658. *
  659. * @param string $abstract
  660. * @return \Closure|string|null
  661. */
  662. protected function findInContextualBindings($abstract)
  663. {
  664. if (isset($this->contextual[end($this->buildStack)][$abstract])) {
  665. return $this->contextual[end($this->buildStack)][$abstract];
  666. }
  667. }
  668. /**
  669. * Determine if the given concrete is buildable.
  670. *
  671. * @param mixed $concrete
  672. * @param string $abstract
  673. * @return bool
  674. */
  675. protected function isBuildable($concrete, $abstract)
  676. {
  677. return $concrete === $abstract || $concrete instanceof Closure;
  678. }
  679. /**
  680. * Instantiate a concrete instance of the given type.
  681. *
  682. * @param string $concrete
  683. * @return mixed
  684. *
  685. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  686. */
  687. public function build($concrete)
  688. {
  689. // If the concrete type is actually a Closure, we will just execute it and
  690. // hand back the results of the functions, which allows functions to be
  691. // used as resolvers for more fine-tuned resolution of these objects.
  692. if ($concrete instanceof Closure) {
  693. return $concrete($this, $this->getLastParameterOverride());
  694. }
  695. $reflector = new ReflectionClass($concrete);
  696. // If the type is not instantiable, the developer is attempting to resolve
  697. // an abstract type such as an Interface or Abstract Class and there is
  698. // no binding registered for the abstractions so we need to bail out.
  699. if (! $reflector->isInstantiable()) {
  700. return $this->notInstantiable($concrete);
  701. }
  702. $this->buildStack[] = $concrete;
  703. $constructor = $reflector->getConstructor();
  704. // If there are no constructors, that means there are no dependencies then
  705. // we can just resolve the instances of the objects right away, without
  706. // resolving any other types or dependencies out of these containers.
  707. if (is_null($constructor)) {
  708. array_pop($this->buildStack);
  709. return new $concrete;
  710. }
  711. $dependencies = $constructor->getParameters();
  712. // Once we have all the constructor's parameters we can create each of the
  713. // dependency instances and then use the reflection instances to make a
  714. // new instance of this class, injecting the created dependencies in.
  715. $instances = $this->resolveDependencies(
  716. $dependencies
  717. );
  718. array_pop($this->buildStack);
  719. return $reflector->newInstanceArgs($instances);
  720. }
  721. /**
  722. * Resolve all of the dependencies from the ReflectionParameters.
  723. *
  724. * @param array $dependencies
  725. * @return array
  726. *
  727. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  728. */
  729. protected function resolveDependencies(array $dependencies)
  730. {
  731. $results = [];
  732. foreach ($dependencies as $dependency) {
  733. // If this dependency has a override for this particular build we will use
  734. // that instead as the value. Otherwise, we will continue with this run
  735. // of resolutions and let reflection attempt to determine the result.
  736. if ($this->hasParameterOverride($dependency)) {
  737. $results[] = $this->getParameterOverride($dependency);
  738. continue;
  739. }
  740. // If the class is null, it means the dependency is a string or some other
  741. // primitive type which we can not resolve since it is not a class and
  742. // we will just bomb out with an error since we have no-where to go.
  743. $results[] = is_null($dependency->getClass())
  744. ? $this->resolvePrimitive($dependency)
  745. : $this->resolveClass($dependency);
  746. }
  747. return $results;
  748. }
  749. /**
  750. * Determine if the given dependency has a parameter override.
  751. *
  752. * @param \ReflectionParameter $dependency
  753. * @return bool
  754. */
  755. protected function hasParameterOverride($dependency)
  756. {
  757. return array_key_exists(
  758. $dependency->name, $this->getLastParameterOverride()
  759. );
  760. }
  761. /**
  762. * Get a parameter override for a dependency.
  763. *
  764. * @param \ReflectionParameter $dependency
  765. * @return mixed
  766. */
  767. protected function getParameterOverride($dependency)
  768. {
  769. return $this->getLastParameterOverride()[$dependency->name];
  770. }
  771. /**
  772. * Get the last parameter override.
  773. *
  774. * @return array
  775. */
  776. protected function getLastParameterOverride()
  777. {
  778. return count($this->with) ? end($this->with) : [];
  779. }
  780. /**
  781. * Resolve a non-class hinted primitive dependency.
  782. *
  783. * @param \ReflectionParameter $parameter
  784. * @return mixed
  785. *
  786. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  787. */
  788. protected function resolvePrimitive(ReflectionParameter $parameter)
  789. {
  790. if (! is_null($concrete = $this->getContextualConcrete('$'.$parameter->name))) {
  791. return $concrete instanceof Closure ? $concrete($this) : $concrete;
  792. }
  793. if ($parameter->isDefaultValueAvailable()) {
  794. return $parameter->getDefaultValue();
  795. }
  796. $this->unresolvablePrimitive($parameter);
  797. }
  798. /**
  799. * Resolve a class based dependency from the container.
  800. *
  801. * @param \ReflectionParameter $parameter
  802. * @return mixed
  803. *
  804. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  805. */
  806. protected function resolveClass(ReflectionParameter $parameter)
  807. {
  808. try {
  809. return $this->make($parameter->getClass()->name);
  810. }
  811. // If we can not resolve the class instance, we will check to see if the value
  812. // is optional, and if it is we will return the optional parameter value as
  813. // the value of the dependency, similarly to how we do this with scalars.
  814. catch (BindingResolutionException $e) {
  815. if ($parameter->isOptional()) {
  816. return $parameter->getDefaultValue();
  817. }
  818. throw $e;
  819. }
  820. }
  821. /**
  822. * Throw an exception that the concrete is not instantiable.
  823. *
  824. * @param string $concrete
  825. * @return void
  826. *
  827. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  828. */
  829. protected function notInstantiable($concrete)
  830. {
  831. if (! empty($this->buildStack)) {
  832. $previous = implode(', ', $this->buildStack);
  833. $message = "Target [$concrete] is not instantiable while building [$previous].";
  834. } else {
  835. $message = "Target [$concrete] is not instantiable.";
  836. }
  837. throw new BindingResolutionException($message);
  838. }
  839. /**
  840. * Throw an exception for an unresolvable primitive.
  841. *
  842. * @param \ReflectionParameter $parameter
  843. * @return void
  844. *
  845. * @throws \Illuminate\Contracts\Container\BindingResolutionException
  846. */
  847. protected function unresolvablePrimitive(ReflectionParameter $parameter)
  848. {
  849. $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}";
  850. throw new BindingResolutionException($message);
  851. }
  852. /**
  853. * Register a new resolving callback.
  854. *
  855. * @param \Closure|string $abstract
  856. * @param \Closure|null $callback
  857. * @return void
  858. */
  859. public function resolving($abstract, Closure $callback = null)
  860. {
  861. if (is_string($abstract)) {
  862. $abstract = $this->getAlias($abstract);
  863. }
  864. if (is_null($callback) && $abstract instanceof Closure) {
  865. $this->globalResolvingCallbacks[] = $abstract;
  866. } else {
  867. $this->resolvingCallbacks[$abstract][] = $callback;
  868. }
  869. }
  870. /**
  871. * Register a new after resolving callback for all types.
  872. *
  873. * @param \Closure|string $abstract
  874. * @param \Closure|null $callback
  875. * @return void
  876. */
  877. public function afterResolving($abstract, Closure $callback = null)
  878. {
  879. if (is_string($abstract)) {
  880. $abstract = $this->getAlias($abstract);
  881. }
  882. if ($abstract instanceof Closure && is_null($callback)) {
  883. $this->globalAfterResolvingCallbacks[] = $abstract;
  884. } else {
  885. $this->afterResolvingCallbacks[$abstract][] = $callback;
  886. }
  887. }
  888. /**
  889. * Fire all of the resolving callbacks.
  890. *
  891. * @param string $abstract
  892. * @param mixed $object
  893. * @return void
  894. */
  895. protected function fireResolvingCallbacks($abstract, $object)
  896. {
  897. $this->fireCallbackArray($object, $this->globalResolvingCallbacks);
  898. $this->fireCallbackArray(
  899. $object, $this->getCallbacksForType($abstract, $object, $this->resolvingCallbacks)
  900. );
  901. $this->fireAfterResolvingCallbacks($abstract, $object);
  902. }
  903. /**
  904. * Fire all of the after resolving callbacks.
  905. *
  906. * @param string $abstract
  907. * @param mixed $object
  908. * @return void
  909. */
  910. protected function fireAfterResolvingCallbacks($abstract, $object)
  911. {
  912. $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks);
  913. $this->fireCallbackArray(
  914. $object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks)
  915. );
  916. }
  917. /**
  918. * Get all callbacks for a given type.
  919. *
  920. * @param string $abstract
  921. * @param object $object
  922. * @param array $callbacksPerType
  923. *
  924. * @return array
  925. */
  926. protected function getCallbacksForType($abstract, $object, array $callbacksPerType)
  927. {
  928. $results = [];
  929. foreach ($callbacksPerType as $type => $callbacks) {
  930. if ($type === $abstract || $object instanceof $type) {
  931. $results = array_merge($results, $callbacks);
  932. }
  933. }
  934. return $results;
  935. }
  936. /**
  937. * Fire an array of callbacks with an object.
  938. *
  939. * @param mixed $object
  940. * @param array $callbacks
  941. * @return void
  942. */
  943. protected function fireCallbackArray($object, array $callbacks)
  944. {
  945. foreach ($callbacks as $callback) {
  946. $callback($object, $this);
  947. }
  948. }
  949. /**
  950. * Get the container's bindings.
  951. *
  952. * @return array
  953. */
  954. public function getBindings()
  955. {
  956. return $this->bindings;
  957. }
  958. /**
  959. * Get the alias for an abstract if available.
  960. *
  961. * @param string $abstract
  962. * @return string
  963. */
  964. public function getAlias($abstract)
  965. {
  966. if (! isset($this->aliases[$abstract])) {
  967. return $abstract;
  968. }
  969. return $this->getAlias($this->aliases[$abstract]);
  970. }
  971. /**
  972. * Get the extender callbacks for a given type.
  973. *
  974. * @param string $abstract
  975. * @return array
  976. */
  977. protected function getExtenders($abstract)
  978. {
  979. $abstract = $this->getAlias($abstract);
  980. if (isset($this->extenders[$abstract])) {
  981. return $this->extenders[$abstract];
  982. }
  983. return [];
  984. }
  985. /**
  986. * Remove all of the extender callbacks for a given type.
  987. *
  988. * @param string $abstract
  989. * @return void
  990. */
  991. public function forgetExtenders($abstract)
  992. {
  993. unset($this->extenders[$this->getAlias($abstract)]);
  994. }
  995. /**
  996. * Drop all of the stale instances and aliases.
  997. *
  998. * @param string $abstract
  999. * @return void
  1000. */
  1001. protected function dropStaleInstances($abstract)
  1002. {
  1003. unset($this->instances[$abstract], $this->aliases[$abstract]);
  1004. }
  1005. /**
  1006. * Remove a resolved instance from the instance cache.
  1007. *
  1008. * @param string $abstract
  1009. * @return void
  1010. */
  1011. public function forgetInstance($abstract)
  1012. {
  1013. unset($this->instances[$abstract]);
  1014. }
  1015. /**
  1016. * Clear all of the instances from the container.
  1017. *
  1018. * @return void
  1019. */
  1020. public function forgetInstances()
  1021. {
  1022. $this->instances = [];
  1023. }
  1024. /**
  1025. * Flush the container of all bindings and resolved instances.
  1026. *
  1027. * @return void
  1028. */
  1029. public function flush()
  1030. {
  1031. $this->aliases = [];
  1032. $this->resolved = [];
  1033. $this->bindings = [];
  1034. $this->instances = [];
  1035. $this->abstractAliases = [];
  1036. }
  1037. /**
  1038. * Set the globally available instance of the container.
  1039. *
  1040. * @return static
  1041. */
  1042. public static function getInstance()
  1043. {
  1044. if (is_null(static::$instance)) {
  1045. static::$instance = new static;
  1046. }
  1047. return static::$instance;
  1048. }
  1049. /**
  1050. * Set the shared instance of the container.
  1051. *
  1052. * @param \Illuminate\Contracts\Container\Container|null $container
  1053. * @return \Illuminate\Contracts\Container\Container|static
  1054. */
  1055. public static function setInstance(ContainerContract $container = null)
  1056. {
  1057. return static::$instance = $container;
  1058. }
  1059. /**
  1060. * Determine if a given offset exists.
  1061. *
  1062. * @param string $key
  1063. * @return bool
  1064. */
  1065. public function offsetExists($key)
  1066. {
  1067. return $this->bound($key);
  1068. }
  1069. /**
  1070. * Get the value at a given offset.
  1071. *
  1072. * @param string $key
  1073. * @return mixed
  1074. */
  1075. public function offsetGet($key)
  1076. {
  1077. return $this->make($key);
  1078. }
  1079. /**
  1080. * Set the value at a given offset.
  1081. *
  1082. * @param string $key
  1083. * @param mixed $value
  1084. * @return void
  1085. */
  1086. public function offsetSet($key, $value)
  1087. {
  1088. $this->bind($key, $value instanceof Closure ? $value : function () use ($value) {
  1089. return $value;
  1090. });
  1091. }
  1092. /**
  1093. * Unset the value at a given offset.
  1094. *
  1095. * @param string $key
  1096. * @return void
  1097. */
  1098. public function offsetUnset($key)
  1099. {
  1100. unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]);
  1101. }
  1102. /**
  1103. * Dynamically access container services.
  1104. *
  1105. * @param string $key
  1106. * @return mixed
  1107. */
  1108. public function __get($key)
  1109. {
  1110. return $this[$key];
  1111. }
  1112. /**
  1113. * Dynamically set container services.
  1114. *
  1115. * @param string $key
  1116. * @param mixed $value
  1117. * @return void
  1118. */
  1119. public function __set($key, $value)
  1120. {
  1121. $this[$key] = $value;
  1122. }
  1123. }