Configs.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace common\modules\rbac\components;
  3. use Yii;
  4. use yii\caching\Cache;
  5. use yii\db\Connection;
  6. use yii\helpers\ArrayHelper;
  7. /**
  8. * Configs
  9. * Used for configure some value. To set config you can use [[\yii\base\Application::$params]].
  10. *
  11. * ~~~
  12. * return [
  13. *
  14. * 'mdm.admin.configs' => [
  15. * 'db' => 'customDb',
  16. * 'menuTable' => 'admin_menu',
  17. * ]
  18. * ];
  19. * ~~~
  20. *
  21. * or use [[\Yii::$container]]
  22. *
  23. * ~~~
  24. * Yii::$container->set('rbac\components\Configs',[
  25. * 'db' => 'customDb',
  26. * 'menuTable' => 'admin_menu',
  27. * ]);
  28. * ~~~
  29. *
  30. * @author Misbahul D Munir <misbahuldmunir@gmail.com>
  31. *
  32. * @since 1.0
  33. */
  34. class Configs extends \yii\base\BaseObject
  35. {
  36. /**
  37. * @var Connection Database connection.
  38. */
  39. public $db = 'db';
  40. /**
  41. * @var Cache Cache component.
  42. */
  43. public $cache = 'cache';
  44. /**
  45. * @var int Cache duration. Default to a month.
  46. */
  47. public $cacheDuration = 2592000;
  48. /**
  49. * @var string Menu table name.
  50. */
  51. public $menuTable = '{{%menu}}';
  52. /**
  53. * @var self Instance of self
  54. */
  55. private static $_instance;
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function init()
  60. {
  61. if ($this->db !== null && !($this->db instanceof Connection)) {
  62. if (is_string($this->db) && strpos($this->db, '\\') === false) {
  63. $this->db = Yii::$app->get($this->db, false);
  64. } else {
  65. $this->db = Yii::createObject($this->db);
  66. }
  67. }
  68. if ($this->cache !== null && !($this->cache instanceof Cache)) {
  69. if (is_string($this->cache) && strpos($this->cache, '\\') === false) {
  70. $this->cache = Yii::$app->get($this->cache, false);
  71. } else {
  72. $this->cache = Yii::createObject($this->cache);
  73. }
  74. }
  75. parent::init();
  76. }
  77. /**
  78. * Create instance of self.
  79. *
  80. * @return static
  81. */
  82. public static function instance()
  83. {
  84. if (self::$_instance === null) {
  85. $type = ArrayHelper::getValue(Yii::$app->params, 'mdm.admin.configs', []);
  86. if (is_array($type) && !isset($type['class'])) {
  87. $type['class'] = static::className();
  88. }
  89. return self::$_instance = Yii::createObject($type);
  90. }
  91. return self::$_instance;
  92. }
  93. }