【问题标题】:Codeigniter 4 modules loading constantsCodeigniter 4 模块加载常量
【发布时间】:2021-03-20 23:57:32
【问题描述】:

我有一个正在 codeigniter 4 中重新设计的项目。该项目将包含几个可以根据需要打开和关闭的模块。对于这个项目,我需要根据项目中的活动模块加载和加载的常量。

我正在寻找的是实现这一目标的最佳方式。我尝试过多种方式,但都失败了。

首先介绍一下我目前的 CI4 设置

  • 自动加载 Autoload.php 配置文件中的模块
  • 自动发现 Modules.php 配置文件中的配置文件
  • modules 文件夹位于 app 文件夹之外。该文件夹由包含实际模块的子文件夹组成。 (例如:模块/管理员和模块/用户)

我尝试向 Modules.php $aliases 数组添加常量。但由于常量文件实际上不是类文件,因此它不会被加载。

我还尝试在 app/Config/Constants.php 中使用以下代码。它可以加载常量,但如果我禁用一个模块,这些常量仍然会被加载。

if (file_exists(ROOTPATH. 'modules')) {
$modulesPath = ROOTPATH.'modules/';
$modules = scandir($modulesPath);

foreach ($modules as $module) {
    if ($module === '.' || $module === '..') continue;
    if (is_dir($modulesPath) . '/' . $module) {
        $constantsPath = $modulesPath . $module . '/Config/Constants.php';
        if (file_exists($constantsPath)) {
            require($constantsPath);
        } else {
            continue;
        }
    }
}

非常感谢任何建议或不同的思维方式。

【问题讨论】:

    标签: php module codeigniter-4


    【解决方案1】:

    我建议的另一种方法是在 CI4 中使用 CustomConfiguration 作为服务。

    首先使用将返回模块路径的方法创建一个类。所以会是这样的:

    public class CustomConfiguration{
    
       //returns module paths.
       public function getActiveModulePaths(){
        return [
        'path1',
        'path2'
        ];
       }
    
      }
    

    现在要将此 CustomConfig 用作 CI4 中的服务,您需要扩展 CI4 的服务。

    因此,在以下路径 app/Config/Services 中,您将需要创建 CustomConfiguration 文件的单例:

       class Services extends CoreServices
    {
    
           public static function customConfig($getShared = true)
           {
               if ($getShared)
               {
                   return static::getSharedInstance('customConfig');
               }
        
               return new CustomConfiguration();
           }
    }
    

    这保证了无论何时调用 CustomConfiguration,它总是会返回一个自定义配置类的实例。

    现在,只要您想获取活动模块的路径,您只需调用 以下:

    service('customConfig')->getActiveModulePaths()
    

    这将返回活动模块的路径。

    现在要在 getActiveModulePaths 中操作活动模块的路径,您可以使用 env 文件动态获取路径或使用 Setter Method 或 DB Query 设置它。

    参考:https://codeigniter4.github.io/userguide/concepts/services.html?highlight=service

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 2017-12-27
      • 1970-01-01
      相关资源
      最近更新 更多