0

我正在为由 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 堆栈的类。是代码的链接

4

2 回答 2

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;
        }
    }
}

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

编辑:固定路径。

于 2014-08-02T07:49:38.313 回答
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;
}
于 2018-11-30T18:43:35.360 回答