ContextualBindingBuilder.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Illuminate\Container;
  3. use Illuminate\Contracts\Container\Container;
  4. use Illuminate\Contracts\Container\ContextualBindingBuilder as ContextualBindingBuilderContract;
  5. class ContextualBindingBuilder implements ContextualBindingBuilderContract
  6. {
  7. /**
  8. * The underlying container instance.
  9. *
  10. * @var \Illuminate\Contracts\Container\Container
  11. */
  12. protected $container;
  13. /**
  14. * The concrete instance.
  15. *
  16. * @var string|array
  17. */
  18. protected $concrete;
  19. /**
  20. * The abstract target.
  21. *
  22. * @var string
  23. */
  24. protected $needs;
  25. /**
  26. * Create a new contextual binding builder.
  27. *
  28. * @param \Illuminate\Contracts\Container\Container $container
  29. * @param string|array $concrete
  30. */
  31. public function __construct(Container $container, $concrete)
  32. {
  33. $this->concrete = $concrete;
  34. $this->container = $container;
  35. }
  36. /**
  37. * Define the abstract target that depends on the context.
  38. *
  39. * @param string $abstract
  40. * @return $this
  41. */
  42. public function needs($abstract)
  43. {
  44. $this->needs = $abstract;
  45. return $this;
  46. }
  47. /**
  48. * Define the implementation for the contextual binding.
  49. *
  50. * @param \Closure|string|array $implementation
  51. * @return $this
  52. */
  53. public function give($implementation)
  54. {
  55. foreach (Util::arrayWrap($this->concrete) as $concrete) {
  56. $this->container->addContextualBinding($concrete, $this->needs, $implementation);
  57. }
  58. return $this;
  59. }
  60. /**
  61. * Define tagged services to be used as the implementation for the contextual binding.
  62. *
  63. * @param string $tag
  64. * @return $this
  65. */
  66. public function giveTagged($tag)
  67. {
  68. return $this->give(function ($container) use ($tag) {
  69. $taggedServices = $container->tagged($tag);
  70. return is_array($taggedServices) ? $taggedServices : iterator_to_array($taggedServices);
  71. });
  72. }
  73. /**
  74. * Specify the configuration item to bind as a primitive.
  75. *
  76. * @param string $key
  77. * @param mixed $default
  78. * @return $this
  79. */
  80. public function giveConfig($key, $default = null)
  81. {
  82. return $this->give(fn ($container) => $container->get('config')->get($key, $default));
  83. }
  84. }