LoadModule.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: NODELOG
  5. * Date: 16/7/2
  6. * Time: 下午6:12
  7. */
  8. namespace common\components;
  9. use common\models\Module;
  10. use Yii;
  11. use yii\base\BootstrapInterface;
  12. use yii\base\Component;
  13. use yii\helpers\ArrayHelper;
  14. class LoadModule extends Component implements BootstrapInterface
  15. {
  16. public function bootstrap($app)
  17. {
  18. // 先判断是否安装,没安装不操作~
  19. if (!file_exists(Yii::getAlias('@root/web/storage/install.txt'))) {
  20. return;
  21. }
  22. $models = Module::findOpenModules(Module::TYPE_CORE);
  23. $bootstrapType = $app->id;
  24. foreach ($models as $model) {
  25. $modulePackage = Yii::$app->moduleManager->findOne($model->id);
  26. if ($modulePackage === null) {
  27. continue;
  28. }
  29. $class = [
  30. 'class' => $modulePackage->getModuleClass(),
  31. 'params' => $modulePackage->getConfig()
  32. ];
  33. $this->setModule($model->id, $class);
  34. if ($model->bootstrap == '*') {
  35. $bootstraps = ['frontend', 'backend', 'api', 'wechat', 'console'];
  36. } else {
  37. $bootstraps = explode("|", $model->bootstrap);
  38. }
  39. if (in_array($bootstrapType, $bootstraps)) {
  40. $module = \Yii::$app->getModule($model->id);
  41. if ($module instanceof BootstrapInterface) {
  42. $module->bootstrap($app);
  43. }
  44. }
  45. }
  46. }
  47. public function setModule($id, $config)
  48. {
  49. $definitions = \Yii::$app->getModules();
  50. Yii::$app->setModule($id,
  51. ArrayHelper::merge($config, array_key_exists($id, $definitions) ? $definitions[$id] : [])
  52. );
  53. }
  54. }