thadafinser/speed-loader

此包已被废弃,不再维护。没有建议的替代包。

加速类加载

v1.0.0 2015-04-13 06:37 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:45:12 UTC


README

Build Status Code Coverage Scrutinizer Code Quality

一个文件一次性加载所有需要的类!由于自动加载需要更多的时间,一个高效的自动加载变得非常重要。《SpeedLoader》旨在提升您的自动加载体验

安装

使用composer获取

composer require thadafinser/speed-loader

创建一个单独的文件

// composer autoloading
require 'vendor/autoload.php';

//since composer is always needed, exclude all classes loaded until here
$classesNoLoad = array_merge(get_declared_interfaces(), get_declared_traits(), get_declared_classes());

//execute your app part you want to cache
$app = MyApplication::init();

//find all loaded files until here
$classes = array_merge(get_declared_interfaces(), get_declared_traits(), get_declared_classes());
//remove the classes loaded by composer
$classes = array_diff($classes, $classesNoLoad);

//cache it now
$cache = new SpeedLoader\BuildCache();
$cache->setClasses($classes);
//$cache->setNewLine("\n");
//$cache->setCompressionLevel(SpeedLoader\BuildClass::COMPRESS_HIGH);

file_put_contents('data/cache/classes.php.cache', '<?php ' . "\n" . $cache->getCachedString());

将缓存添加到您的应用程序中

if (file_exists('data/cache/classes.php.cache')) {
    require_once 'data/cache/classes.php.cache';
}

这是新功能吗?

不,这不是全新的功能。周围有几个解决方案,但它们都存在一些问题,这就是我“重新发明轮子”的原因。

功能

  • 独立
    • 可以与所有包或框架一起使用
    • 或仅与您的代码一起使用
  • 不同的压缩模式
    • 生产环境的压缩
    • 开发环境的正常使用
  • 以您想要的方式保存缓存
    • 您将获得完整的缓存作为字符串
    • 例如,将其保存为文件或内存

示例

生成

只需执行您想要缓存的您应用程序的一部分。不要在常规流程中这样做 - 使用cronjob或类似方式预热您的缓存

// composer autoloading
require 'vendor/autoload.php';

//since composer is always needed, exclude all classes loaded until here
$classesNoLoad = array_merge(get_declared_interfaces(), get_declared_traits(), get_declared_classes());

//execute your app...(only the bootstrap)
$app = Zend\Mvc\Application::init($appConfig);

//find all loaded files
$classes = array_merge(get_declared_interfaces(), get_declared_traits(), get_declared_classes());
$classes = array_diff($classes, $classesNoLoad);

//cache it
$cache = new SpeedLoader\BuildCache();
$cache->setClasses($classes);
//$cache->setNewLine("\n");
//$cache->setCompressionLevel(SpeedLoader\BuildClass::COMPRESS_HIGH);

file_put_contents('data/cache/classes.php.cache', '<?php ' . "\n" . $cache->getCachedString());

将文件包含在您的最终应用程序中

if (file_exists('data/cache/classes.php.cache')) {
    require_once 'data/cache/classes.php.cache';
}

为什么合并类

在文件系统中查找和打开很多文件是昂贵的。(与您应该合并JS或CSS文件的原因相似...但在那里的HTTP)

替代方案

EdpSuperluminal

  • 未维护
  • 仅适用于ZF2
  • 只能进行压缩

Symfony

  • 仅输出直接到文件
  • 不能进行压缩

ClassPreloader

  • 类层次结构可能错误(例如,一个类需要一个接口,而接口在文件中稍后出现...但在那之前自动加载器已经加载了接口 -> “无法重新声明错误”)

基准测试

http://stackoverflow.com/questions/8240726/are-there-performance-downsides-while-using-autoloading-classes-in-php https://mwop.net/blog/245-Autoloading-Benchmarks.html