开发名称空间和自动加载器的wordpress插件问题

时间:2017-06-15 14:49:47

标签: wordpress autoload spl-autoload-register

受到https://www.smashingmagazine.com/2015/05/how-to-use-autoloading-and-a-plugin-container-in-wordpress-plugins/的启发,我想编写一个使用autoloader +名称空间的插件。

在文件夹插件的根目录中,我有simplestform.php文件:

<?php
/*
Plugin Name: Simplest Form
Description: A simplest contact form
Version: 1.0.0
License: GPL-2.0+
*/

if ( ! defined( 'ABSPATH' ) ) exit;

/* AUTOLOADER */
/* Inspired by: https://www.smashingmagazine.com/2015/05/how-to-use-autoloading-and-a-plugin-container-in-wordpress-plugins/
 * 
 */

spl_autoload_register( 'simplestform_autoloader' );

function simplestform_autoloader( $class_name ) {


    $classes_dir = realpath ( plugin_dir_path ( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;

    $class_file = str_replace( '\\', DIRECTORY_SEPARATOR, $class_name ) . '.php';

    require_once $classes_dir . $class_file;

}

/*$class_name = 'Base';
$classes_dir = realpath ( plugin_dir_path ( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
$class_file = str_replace( '\\', DIRECTORY_SEPARATOR, $class_name ) . '.php';

require_once $classes_dir . $class_file;*/


$simplestform = new Base();

在src文件夹中有一个名为Base.php的文件

<?php

namespace Simplestform;

class Base {

    /**
     * Prefix for every single input / key / field / etc
     * 
     * @var Array
     */
    private $_prefix = 'simplest_';

    /**
     * Container for the key(s) of the input / textarea form.
     * 
     * @var Array
     */
    private $_array_key_form;

    public function __construct() {

        $this->_array_key_form['meta_key_name'] = $this->_prefix.'meta_key_name';
        $this->_array_key_form['meta_key_email'] = $this->_prefix.'meta_key_email';

    }


    protected function getArrayKeyForm() {

        return $this->_array_key_form;

    }

}

如果我删除自动加载器功能(simplestform_autoloader)并取消注释4行:

/*$class_name = 'Base';
    $classes_dir = realpath ( plugin_dir_path ( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
    $class_file = str_replace( '\\', DIRECTORY_SEPARATOR, $class_name ) . '.php';

    require_once $classes_dir . $class_file;*/

代码有效。

通过自动加载器功能,PHP抛出了错误:

Class 'Base' not found in /var/www/vhosts/..../httpdocs/wp-content/plugins/simplest-form/simplestform.php

我确实尝试了以下各种组合:

new \Base | new \Simplestform\Base | new Base | new SimplestForm\Base

等。谢谢。

0 个答案:

没有答案