ContextualBindingBuilder.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. * @return void
  31. */
  32. public function __construct(Container $container, $concrete)
  33. {
  34. $this->concrete = $concrete;
  35. $this->container = $container;
  36. }
  37. /**
  38. * Define the abstract target that depends on the context.
  39. *
  40. * @param string $abstract
  41. * @return $this
  42. */
  43. public function needs($abstract)
  44. {
  45. $this->needs = $abstract;
  46. return $this;
  47. }
  48. /**
  49. * Define the implementation for the contextual binding.
  50. *
  51. * @param \Closure|string|array $implementation
  52. * @return void
  53. */
  54. public function give($implementation)
  55. {
  56. foreach (Util::arrayWrap($this->concrete) as $concrete) {
  57. $this->container->addContextualBinding($concrete, $this->needs, $implementation);
  58. }
  59. }
  60. /**
  61. * Define tagged services to be used as the implementation for the contextual binding.
  62. *
  63. * @param string $tag
  64. * @return void
  65. */
  66. public function giveTagged($tag)
  67. {
  68. $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 void
  79. */
  80. public function giveConfig($key, $default = null)
  81. {
  82. $this->give(fn ($container) => $container->get('config')->get($key, $default));
  83. }
  84. }