ObjectManager.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Magento object manager. Responsible for instantiating objects taking into account:
  4. * - constructor arguments (using configured, and provided parameters)
  5. * - class instances life style (singleton, transient)
  6. * - interface preferences
  7. *
  8. * Intentionally contains multiple concerns for best performance
  9. *
  10. * Copyright © Magento, Inc. All rights reserved.
  11. * See COPYING.txt for license details.
  12. */
  13. namespace Magento\Framework\ObjectManager;
  14. class ObjectManager implements \Magento\Framework\ObjectManagerInterface
  15. {
  16. /**
  17. * @var \Magento\Framework\ObjectManager\FactoryInterface
  18. */
  19. protected $_factory;
  20. /**
  21. * List of shared instances
  22. *
  23. * @var array
  24. */
  25. protected $_sharedInstances = [];
  26. /**
  27. * @var ConfigInterface
  28. */
  29. protected $_config;
  30. /**
  31. * @param FactoryInterface $factory
  32. * @param ConfigInterface $config
  33. * @param array &$sharedInstances
  34. */
  35. public function __construct(FactoryInterface $factory, ConfigInterface $config, &$sharedInstances = [])
  36. {
  37. $this->_config = $config;
  38. $this->_factory = $factory;
  39. $this->_sharedInstances = &$sharedInstances;
  40. $this->_sharedInstances[\Magento\Framework\ObjectManagerInterface::class] = $this;
  41. }
  42. /**
  43. * Create new object instance
  44. *
  45. * @param string $type
  46. * @param array $arguments
  47. * @return mixed
  48. */
  49. public function create($type, array $arguments = [])
  50. {
  51. return $this->_factory->create($this->_config->getPreference($type), $arguments);
  52. }
  53. /**
  54. * Retrieve cached object instance
  55. *
  56. * @param string $type
  57. * @return mixed
  58. */
  59. public function get($type)
  60. {
  61. $type = ltrim($type, '\\');
  62. $type = $this->_config->getPreference($type);
  63. if (!isset($this->_sharedInstances[$type])) {
  64. $this->_sharedInstances[$type] = $this->_factory->create($type);
  65. }
  66. return $this->_sharedInstances[$type];
  67. }
  68. /**
  69. * Configure di instance
  70. * Note: All arguments should be pre-processed (sort order, translations, etc) before passing to method configure.
  71. *
  72. * @param array $configuration
  73. * @return void
  74. */
  75. public function configure(array $configuration)
  76. {
  77. $this->_config->extend($configuration);
  78. }
  79. }