这个时候非常简单的问题,基本上我有一组文件夹,其中一些包含我想要自动加载的文件,每当我运行我的网站脚本时。但是,我不希望指定自动加载的文件,因为我希望流程是动态的,我希望能够在飞行中创建和删除不同的文件。 所以当然,最简单的解决方案是在目录中获取文件夹列表,并将路径构建到自动加载文件,如果文件存在,则脚本包含它们。 但是,我的问题是影响我脚本的表现的多少?它实际上是一个框架,我想在稍后释放,因此表现是非常的问题。 任何想法?

有帮助吗?

解决方案

You should consider simply letting PHP autoload your classes.

If that won't work, then you're pretty much left with the directory-scanning solution, and you shouldn't really care about performance penalties. If you want the functionality, you'll put up with the costs.

Generally you shouldn't stress overmuch about performance in PHP anyways. If it becomes an issue when your framework is complete, revisit it. Chances are you'll find whatever performance gains/losses you incur now are rendered moot by implementing a good caching system in your framework.

See Premature Optimization.

其他提示

It depends on your disk speed, file system, and the size of the directory. No matter what, having to dynamically load the directory to get the list of files will take longer than loading a static list; how much of an increase is acceptable depends on your requirements.

If it's an option, caching that list could help.

Autoloading is great although it's not "free", the performance hit is not noticeable. Of course you can measure this and refactor if needed.

Here's my autoloader:

spl_autoload_register(
    function ($className) {
        $possibilities = array(
            APPLICATION_PATH.'beans'.DIRECTORY_SEPARATOR.$className.'.php',
            APPLICATION_PATH.'controllers'.DIRECTORY_SEPARATOR.$className.'.php',
            APPLICATION_PATH.'helpers'.DIRECTORY_SEPARATOR.$className.'.php',
            APPLICATION_PATH.'models'.DIRECTORY_SEPARATOR.$className.'.php',
            APPLICATION_PATH.'views'.DIRECTORY_SEPARATOR.$className.'.php'
        );
        foreach (explode(PATH_SEPARATOR, ini_get('include_path')) as $k => $v) {
            $possibilities[] = $v.DIRECTORY_SEPARATOR.$className.'.php';
        }
        foreach ($possibilities as $file) {
            if (file_exists($file)) {
                require_once($file);
                return true;
            }
        }
        return false;
    }
);

It depends.

Try your approach and measure. You can always add caching later. Or resort to autoload.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top