【问题标题】:Class conflicts with plugin frameworks - PHP / Wordpress类与插件框架冲突 - PHP / Wordpress
【发布时间】:2011-08-14 07:10:58
【问题描述】:

我正处于编写基本 MVC WordPress 插件开发框架的初始阶段,我意识到我将遇到命名冲突问题。如果我想在我正在开发的几个插件和/或主题中包含这个框架,最终我会遇到一个 class_exists() 无法解决的问题。

我可以将框架创建为独立插件,但这需要任何下载了我的插件或主题之一的人也下载该框架,这似乎不现实(尤其是升级到现有插件时)目前没有这样的依赖)。

无论如何,我想你们中的许多人可能都遇到过同样的问题,我想看看是否有人制定了解决问题的好策略。

如果可能的话,我不需要每个插件都有一个唯一的前缀(这将使更新框架成为一场噩梦)。我希望有一些聪明的方法可以动态命名每个类,而无需硬编码。

【问题讨论】:

    标签: php wordpress namespaces


    【解决方案1】:

    我最终选择的解决方案是创建一个bootstrap.php 文件,让框架的每个实例都注册(在全局变量中)它是什么版本及其文件路径。然后我注册一个在所有插件/主题加载后运行的操作,它比较所有版本并仅加载与最新版本关联的类。

    我看到的唯一缺点是我必须确保我的框架向后兼容,但我还是打算这样做。

    这是我在引导文件中使用的代码。显然,每个框架实例中的版本号都需要与所包含框架的版本号相对应。

    // register this version of the framework
    $GLOBALS['pw_framework_meta']['0.1.2'] = __FILE__;
    
    if ( !function_exists('pw_framework_init') ) {
    
        /**
         * Sort the $GLOBALS['pw_framework_meta'] variable for the latest registered
         * version of the framework. Include the PW_Framework.php file and then call init()
         */
        function pw_framework_init()
        {
            // get all the different versions registered with $GLOBALS['pw_framework_meta']
            $versions = $GLOBALS['pw_framework_meta'];
    
            // sort the versions
            uksort($versions, 'version_compare');
    
            // get the latest versions (the last in the array)
            $latest = end($versions);
    
            if ( !class_exists('PW_Framework') ) {
                require_once( dirname($latest) . '/PW_Framework.php' );
            }
            PW_Framework::init();
        }
    
        // register pw_framework_init() with the 'after_setup_theme' hook
        // This way we can ensure that all plugins or themes that might be using PW_Framework
        // have had a chance to register with the $GLOBALS['pw_framework_meta'] variable
        add_action( 'after_setup_theme', 'pw_framework_init' );
    }
    

    【讨论】:

      【解决方案2】:

      更新

      向提问者道歉,因为第一次没有做对。卢克是对的。 Namespace 是最好的选择。

      原创

      一些框架选择在其类名前放一个字母以避免冲突。 Yii 只是在前面加了 C,比如:

      class CClassName 
      {
      }
      

      【讨论】:

      • 我在问题中特别指出我不想硬编码前缀。原因是因为我想让任何人都可以使用这个框架来加入他们的项目,我不想让他们检查每一个类文件并将其更改为独特的东西。
      【解决方案3】:

      Namespace可以解决你的问题。

      【讨论】:

      • 不是真的,首先命名空间需要 php 5.3.,很多人没有运行,其次,(据我所知)命名空间不能动态创建,所以我遇到了同样的问题。
      • 没有命名空间,没有前缀,我很好奇你如何解决你的问题。
      猜你喜欢
      • 2011-06-18
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多