Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. <?php
  2.  
  3. // for each module could be created folder "configs" with definitions for DI Container
  4. // It is hask for encapsulating DI container at least to the module.
  5.  
  6. /**
  7. * @copyright &copy; Iterios
  8. * YII2
  9. * Date: 11.06.18
  10. * Time: 17:32
  11. */
  12.  
  13. namespace app\common\base;
  14. use yii\di\Container;
  15.  
  16.  
  17. abstract class Module extends \yii\base\Module
  18. {
  19. protected $consoleNamespace = '';
  20. /**
  21. * @var Container
  22. */
  23. public $container;
  24.  
  25. /**
  26. * @throws \ReflectionException
  27. */
  28. public function init()
  29. {
  30. parent::init();
  31. if ($this->consoleNamespace !== '' && \Yii::$app instanceof \yii\console\Application) {
  32. $this->controllerNamespace = $this->consoleNamespace;
  33. }
  34. $this->setContainer(\Yii::$container);
  35. $this->configure();
  36. }
  37.  
  38. /**
  39. * @param Container $container
  40. */
  41. public function setContainer(Container $container)
  42. {
  43. $this->container = $container;
  44. }
  45.  
  46. /**
  47. * @return Container
  48. */
  49. public function getContainer() : Container
  50. {
  51. return $this->container;
  52. }
  53.  
  54.  
  55. /**
  56. * @param array $config
  57. * @throws \ReflectionException
  58. */
  59. protected function configure($config = [])
  60. {
  61. $config = (empty($config)) ? $this->getConfig() : $config;
  62. if(empty($config)) {
  63. return;
  64. }
  65. if(isset($config['module'])) {
  66. \Yii::configure($this,$config['module']);
  67. }
  68. if(isset($config['definitions']) && is_array($config['definitions']) && !empty($config['definitions'])) {
  69. $definitions = $config['definitions'];
  70. $this->container->setDefinitions($definitions);
  71. }
  72.  
  73. }
  74.  
  75. /**
  76. * @return mixed|null
  77. * @throws \ReflectionException
  78. */
  79. protected function getConfig()
  80. {
  81. $class = new \ReflectionClass($this);
  82. if(file_exists(dirname($class->getFileName()) . '/configs/config.php')) {
  83. return require_once dirname($class->getFileName()) . '/configs/config.php';
  84. }
  85. return null;
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement