spl_autoload with namespace php

时间:2014-08-02 07:37:12

标签: php spl-autoload-register spl-autoloader

我正在为一个由nodejs外部进程运行的预定作业构建一个小框架。我想使用自动加载器但由于某种原因数据没有达到它。我也在使用命名空间。这是我的文件夹结构:

Library
  |_ Core
     |_ JobConfig.php
  |_ Utilities
     |_ Loader.php
  |_ Scheduled
     |_ SomeJob.php
  |_ Config.php

我的Config.php只有一些定义和我Loader.php的实例。

Loader.php看起来像:

public function __constructor()
{
    spl_autoload_register(array($this, 'coreLoader'));
    spl_autoload_register(array($this, 'utilitiesLoader'));
}

private function coreLoader($class)
{
    echo $class;
    return true;
}

private function utilitiesLoader($lass)
{
    echo $class;
    return true;
}

因此对于我的SomeJob.php我包括Config.php然后尝试在失败时实例化JobConfig.php。我的命名空间看起来像Library\Core\JobConfig,依此类推。我不确定这是否是最好的方法,如果没有能力的东西。但是在失败之前我没有看到装载机的回声。

修改:

我尝试了@Layne的消化,但没有奏效。我仍然得到一个没有找到的类,看起来像是没有进入spl堆栈的类。 Here是代码的链接

2 个答案:

答案 0 :(得分:0)

如果您实际使用名称空间的方式与使用目录结构的方式相同,那么这应该很容易。

<?php
namespace Library {
    spl_autoload_register('\Library\Autoloader::default_autoloader');

    class Autoloader {
        public static function default_autoloader($class) {
            $class = ltrim($class, '\\');

            $file = __DIR__ . '/../';
            if ($lastNsPos = strrpos($class, '\\')) {
                $namespace = substr($class, 0, $lastNsPos);
                $class     = substr($class, $lastNsPos + 1);
                $file .= str_replace('\\', '/', $namespace) . '/';
            }

            $file .= $class . '.php';
            include $file;
        }
    }
}

将它放入您的Library目录并在更高级别上要求它。希望我没有弄乱那个,没有测试它。

编辑:固定路径。

答案 1 :(得分:0)

使用此类来为您的项目建立索引,只需将WP_CONTENT_DIR替换为另一个目录级别即可扫描php文件,此类会自动包含文件:

    <?php

class autoloader
{

    public static function instance()
    {
        static $instance = false;
        if( $instance === false )
        {
            // Late static binding
            $instance = new static();
        }

        return $instance;
    }

    /**
     * @param $dir_level directory level is for file searching
     * @param $php_files_json_name name of the file who all the PHP files will be stored inside it
     */
    private function export_php_files($dir_level, $php_files_json_name)
    {

        $filePaths = array(mktime());
        /**Get all files and directories using iterator.*/
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir_level));

        foreach ($iterator as $path) {
            if (is_string(strval($path)) and pathinfo($path, PATHINFO_EXTENSION) == 'php') {
                $filePaths[] = strval($path);
            }
        }

        /**Encode and save php files dir in a local json file */
        $fileOpen = fopen($dir_level . DIRECTORY_SEPARATOR . $php_files_json_name, 'w');
        fwrite($fileOpen, json_encode($filePaths));
        fclose($fileOpen);
    }

    /**
     * @param $php_files_json_address json file contains all the PHP files inside it
     * @param $class_file_name name of the class that was taken from @spl_autoload_register_register plus .php extension
     * @return bool Succeeding end of work
     */
    private function include_matching_files($php_files_json_address, $class_file_name)
    {
        static $files;
        $inc_is_done = false;

        if ($files == null) {
            $files = json_decode(file_get_contents($php_files_json_address), false);
        }

        /**Include matching files here.*/
        foreach ($files as $path) {
            if (stripos($path, $class_file_name) !== false) {
                require_once $path;
                $inc_is_done = true;
            }
        }
        return $inc_is_done;
    }

    /**
     * @param $dir_level directory level is for file searching
     * @param $class_name name of the class that was taken from @spl_autoload_register
     * @param bool $try_for_new_files Try again to include new files, that this feature is @true in development mode
     * it will renew including file each time after every 30 seconds @see $refresh_time.
     * @return bool Succeeding end of work
     */
    public function request_system_files($dir_level, $class_name, $try_for_new_files = false)
    {
        $php_files_json = 'phpfiles.json';
        $php_files_json_address = $dir_level . DIRECTORY_SEPARATOR . $php_files_json;
        $class_file_name = $class_name . '.php';
        $files_refresh_time = 30;

        /**Include required php files.*/
        if (is_file($php_files_json_address)) {

            $last_update = json_decode(file_get_contents($php_files_json_address), false)[0];

            if ((mktime() - intval($last_update)) < $files_refresh_time || !$try_for_new_files) {
                return $this->include_matching_files($php_files_json_address, $class_file_name);
            }

        }

        $this->export_php_files($dir_level, $php_files_json);
        return $this->include_matching_files($php_files_json_address, $class_file_name);

    }

    /**
     * Make constructor private, so nobody can call "new Class".
     */
    private function __construct()
    {
    }

    /**
     * Make clone magic method private, so nobody can clone instance.
     */
    private function __clone()
    {
    }

    /**
     * Make sleep magic method private, so nobody can serialize instance.
     */
    private function __sleep()
    {
    }

    /**
     * Make wakeup magic method private, so nobody can unserialize instance.
     */
    private function __wakeup()
    {
    }


}

/**
 * Register autoloader.
 */
try {
    spl_autoload_register(function ($className) {
        $autoloader = autoloader::instance();

        return $autoloader->request_system_files(WP_CONTENT_DIR, $className, true);
    });
} catch (Exception $e) {
    var_dump($e);
    die;
}