在WordPress插件中使用spl_autoloding

时间:2015-12-17 作者:Pascale Beier

我正在与spl_autoloading 在一个有名称空间的WordPress插件中。

我已经修改了这些问题:

我的文件夹结构如下所示:

为下面的所有内容命名SamplePlugin

在…内wp-content/plugins/sample-plugin

    src
     \'-- SamplePlugin
     \'   \'-- ShortCode.php
     \'-- autoload.php
    sample-plugin.php
我当前的自动加载功能(正如我习惯的那样…)

spl_autoload_register(function ($class) {

$dir = \'src/\';
$file = str_replace(\'\\\\\', \'/\', $class) . \'.php\';

require_once $dir . $file;
使用它,可以正确添加前缀名称空间,因此如果我在中实例化sample-plugin.php:

namespace SamplePlugin;
require_once \'src/autoload.php\';

$shortcode = new ShortCode();
我得到以下输出(VVV):

警告:require\\u once(src/SamplePlugin/ShortCode.php):无法打开流:在/srv/www/wordpress-default/wp-content/plugins/sample-plugin/src/autoload中没有这样的文件或目录。php第8行

致命错误:require\\u once():无法打开所需的“src/SamplePlugin/ShortCode”。php“(include\\u path=\'。:/usr/share/php:/usr/share/pear”)位于/srv/www/wordpress-default/wp-content/plugins/sample-plugin/src/autoload中。php第8行

有什么提示吗?

所有类(例如,ShortCode)都可以通过SamplePlugin\\ShortCode调用。

1 个回复
最合适的回答,由SO网友:birgire 整理而成

我想问题是你用的是relative path 在里面autoload.php 内部src/ 子文件夹,

例如,尝试修改src/autoload.php 使用absolute paths 而是:

\\spl_autoload_register( function( $class )
{
    $dir = plugin_dir_path( __FILE__ );

    $file = str_replace( \'\\\\\', \'/\', $class ) . \'.php\';

    $path = $dir . $file;

    if( file_exists( $path ) )
        require_once $path;

} );
我们在此处添加file_exists 特定于插件类。

更新/sample-plugin/sample-plugin.php 文件:

<?php
/**
 * Plugin Name: Sample Plugin
 */

namespace SamplePlugin;

require_once __DIR__ . \'/src/autoload.php\';
// require_once \'src/autoload.php\';

$shortcode = new ShortCode();
这是/simple-plugin/src/SamplePlugin/Shortcode.php 文件:

<?php
/**
 * Class Shortcode
 */

namespace SamplePlugin;

class Shortcode
{
    public function __construct()
    {
        print \'DEBUG: Greetings from the Shortcode instance!\';
    }
}
你也可以看看Composer 生成vendor/autoload.php 文件,其中包括:

require __DIR__ . \'/vendor/autoload.php\';

相关推荐

无法在模板函数.php中使用IS_HOME

我试图在标题中加载一个滑块,但只在主页上加载。如果有帮助的话,我正在使用Ultralight模板。我正在尝试(在template functions.php中)执行以下操作:<?php if ( is_page( \'home\' ) ) : ?> dynamic_sidebar( \'Homepage Widget\' ); <?php endif; ?> 但这行不通。现在,通过快速的google,我似乎需要将请