BlockPool.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\View;
  7. use Magento\Framework\View\Element\BlockFactory;
  8. use Magento\Framework\View\Element\BlockInterface;
  9. /**
  10. * Class BlockPool
  11. */
  12. class BlockPool
  13. {
  14. /**
  15. * Block factory
  16. * @var \Magento\Framework\View\Element\BlockFactory
  17. */
  18. protected $blockFactory;
  19. /**
  20. * Blocks
  21. *
  22. * @var array
  23. */
  24. protected $blocks = [];
  25. /**
  26. * Constructor
  27. *
  28. * @param BlockFactory $blockFactory
  29. */
  30. public function __construct(BlockFactory $blockFactory)
  31. {
  32. $this->blockFactory = $blockFactory;
  33. }
  34. /**
  35. * Add a block
  36. *
  37. * @param string $name
  38. * @param string $class
  39. * @param array $arguments [optional]
  40. * @return BlockPool
  41. * @throws \InvalidArgumentException
  42. */
  43. public function add($name, $class, array $arguments = [])
  44. {
  45. if (!class_exists($class)) {
  46. throw new \InvalidArgumentException(
  47. (string)new \Magento\Framework\Phrase('Invalid Block class name: %1', [$class])
  48. );
  49. }
  50. $block = $this->blockFactory->createBlock($class, $arguments);
  51. $this->blocks[$name] = $block;
  52. return $this;
  53. }
  54. /**
  55. * Get blocks
  56. *
  57. * @param string $name
  58. * @return BlockInterface|null
  59. */
  60. public function get($name = null)
  61. {
  62. if (!isset($name)) {
  63. return $this->blocks;
  64. }
  65. return $this->blocks[$name] ?? null;
  66. }
  67. }