Optimizes class loading performance by generating a single PHP file containing all of the autoloaded files.

Overview

Class Preloader for PHP

This tool is used to generate a single PHP script containing all of the classes required for a specific use case. Using a single compiled PHP script instead of relying on autoloading can help to improve the performance of specific use cases. For example, if your application executes the same bootstrap code on every request, then you could generate a preloader (the compiled output of this tool) to reduce the cost of autoloading the required classes over and over.

Banner

What it actually does

This tool listens for each file that is autoloaded, creates a list of files, traverses the parsed PHP file using PHP Parser and any visitors of a Config object, wraps the code of each file in a namespace block if necessary, and writes the contents of every autoloaded file (in order) to a single PHP file.

Notice

This tool should only be used for specific use cases. There is a tradeoff between preloading classes and autoloading classes. The point at which it is no longer beneficial to generate a preloader is application specific. You'll need to perform your own benchmarks to determine if this tool will speed up your application.

Installation

Add ClassPreloader as a dependency to your composer.json file by adding "classpreloader/classpreloader": "^4.1" to your require block. Note that if you want to use the cli tool, then you need to also add "classpreloader/console": "^3.1" to the require block.

Using the tool

You use the ./vendor/bin/classpreloader compile command with a few command line flags to generate a preloader.

--config: A CSV containing a list of files to combine into a classmap, or the full path to a PHP script that returns an array of classes or a ClassPreloader\ClassLoader\Config object.

--output: The path to the file to store the compiled PHP code. If the directory does not exist, the tool will attempt to create it.

--skip_dir_file: (no value) Skip files with __DIR__ or __FILE__ to make the cache portable.

--fix_dir: (defaults to 1) Set to 0 to not replace __DIR__ constants with the actual directory of the original file.

--fix_file: (defaults to 1) Set to 0 to not replace __FILE__ constants with the actual location of the original file.

--strict_types: (defaults to 0) Set to 1 to enable strict types mode.

--strip_comments: (defaults to 0) Set to 1 to strip comments from each source file.

Writing a config file

Creating a PHP based configuration file is fairly simple. Just include the vendor/classpreloader/classpreloader/src/ClassLoader.php file and call the ClassPreloader\ClassLoader::getIncludes() method, passing a function as the only argument. This function should accept a ClassPreloader\ClassLoader object and register the passed in object's autoloader using $loader->register(). It is important to register the ClassPreloader\ClassLoader autoloader after all other autoloaders are registered.

An array or ClassPreloader\ClassLoader\Config must be returned from the config file. You can attach custom node visitors if you need to perform any sort of translation on each matching file before writing it to the output.

<?php

// Here's an example of creating a preloader for using the
// Amazon DynamoDB and the AWS SDK for PHP 2.

require __DIR__.'/src/Config.php';
require __DIR__.'/src/ClassNode.php';
require __DIR__.'/src/ClassList.php';
require __DIR__.'/src/ClassLoader.php';

use ClassPreloader\ClassLoader;

$config = ClassLoader::getIncludes(function (ClassLoader $loader) {
    require __DIR__.'/vendor/autoload.php';
    $loader->register();
    $aws = Aws\Common\Aws::factory([
        'key'    => '***',
        'secret' => '***',
        'region' => 'us-east-1'
    ]);
    $client = $aws->get('dynamodb');
    $client->listTables()->getAll();
});

// Add a regex filter that requires all classes to match the regex.
// $config->addInclusiveFilter('/Foo/');

// Add a regex filter that requires that a class does not match the filter.
// $config->addExclusiveFilter('/Foo/');

return $config;

You would then run the classpreloader script and pass in the full path to the above PHP script.

./vendor/bin/classpreloader compile --config="/path/to/the_example.php" --output="/tmp/preloader.php"

The above command will create a file in /tmp/preloader.php that contains every file that was autoloaded while running the snippet of code in the anonymous function. You would generate this file and include it in your production script.

Automating the process with Composer

You can automate the process of creating preloaders using Composer's script functionality. For example, if you wanted to automatically create a preloader each time the AWS SDK for PHP is installed, you could define a script like the following in your composer.json file:

{
    "require": {
        "classpreloader/console": "^3.1"
    },
    "scripts": {
        "post-autoload-dump": "@php vendor/bin/classpreloader compile --config=/path/to/the_example.php --output=/path/to/preload.php"
    },
    "config": {
        "bin-dir": "bin"
    }
}

Using the above composer.json file, each time the project's autoloader is recreated using the install or update command, the classpreloader.php file will be executed. This script would generate a preload.php containing the classes required to run the previously demonstrated "the_example.php" configuration file.

Security

If you discover a security vulnerability within this package, please send an email to Graham Campbell at [email protected]. All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

Class Preloader is licensed under The MIT License (MIT).

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of classpreloader/classpreloader and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Issues
  • Testing the compiled file

    Testing the compiled file

    As discussed here: https://github.com/ClassPreloader/ClassPreloader/issues/48

    This PR is just for testing purpose.

    bug enhancement 
    opened by KennedyTedesco 12
  • PSR-4 Autoloading And Added Tests

    PSR-4 Autoloading And Added Tests

    This switches us to psr-4 autoloading, adds some tests, and bumps the version to 1.1. The actual 1.1.0 tag can come after the php parser stuff has gone through as previously discussed.

    • The test suite here is not 100% complete, but does cover the bulk of things.
    • There's travis config in here too, so you should be able to enable travis for this repo now.
    • Travis is passing on my fork: https://travis-ci.org/GrahamCampbell/ClassPreloader/builds/34125496.
    • Note that enabling code coverage with process isolation causes very poor performance.

    Running the tests just with process isolation takes 1-2 seconds. Running the tests with code coverage enabled too takes 1-2 minutes, and even longer on php 5.3.

    opened by GrahamCampbell 12
  • Not possible add a class without the namespace?

    Not possible add a class without the namespace?

    PHP Fatal error: Cannot mix bracketed namespace declarations with unbracketed namespace declarations in /var/www/laravel.local/bootstrap/compiled.php on line 10906

    opened by paveleremin 10
  • Use a visitor to wrap non-namespaced code in an empty namespace.

    Use a visitor to wrap non-namespaced code in an empty namespace.

    I found that some of the classes were outputted without a namespace, causing a PHP Fatal error: No code may exist outside of namespace {}. A quick fix was implemented in #7, but this ignores files with the character sequence namespace, regardless of its position. It may appear in a comment, for example.

    I've implemented a node visitor that ensures all code is wrapped in an empty/root namespace. I didn't feel it was necessary to make this configurable, so I did not implement an additional command line option.

    opened by rjkip 10
  • Cannot instantiate interface PhpParser\Parser

    Cannot instantiate interface PhpParser\Parser

    in ClassPreloader/src/Factory.php file line 64 , I find this code return new Parser(new Lexer()) , but the Parser is interface in the nikic/php-parser/lib/PhpParser/Parser.php , so I think it is a bug because we cant new a interface.

    opened by Awezome 9
  • Write file atomically

    Write file atomically

    On my production Laravel site I get some errors while "php artisan optimize" is running because this takes a few seconds to write the file, and it writes it line by line. While it is writing the file visitors are accessing the site and Laravel loads the vendor/compiled.php file this generates, but it is only half-written.

    I've changed it so it writes to a temporary file, then moves it into its final destination using PHP's rename() function.

    opened by antriver 9
  • Fix wrap namespaces

    Fix wrap namespaces

    There is problem with checking for namespace keyword at this moment: if we have this keyword in comments we will wrap code and sometimes it gives probles.

    Sometimes we need to skip wrapping at from this point I've added special option to skip wrap.

    opened by damnedest 7
  • Add support for PHP-Parser 4.0

    Add support for PHP-Parser 4.0

    Looks like no code changes were necessary.

    opened by nikic 7
  • Upgrade To PHP Parser 1.0

    Upgrade To PHP Parser 1.0

    This upgrades us to php parser 1.0.

    ~~I've bumped our version from 1.0 to 1.1 for this change. A php parser stable tag will come in 2 week's time (https://github.com/nikic/PHP-Parser/issues/125#issuecomment-53990700), so if you like this, it might be a good idea to stamp the 1.1.0 release after php parser has a stable tag.~~ The version bump was done as part of another pull.

    It might be a good idea to stamp the 1.1.0 release after php parser has a stable tag.

    opened by GrahamCampbell 7
Releases(4.2.0)
  • 4.2.0(Aug 28, 2021)

    This is the second release in the 4.2.x series.

    This release contains the following improvements:
    • Added support for PHP 8.1 (af9284543aedb45ed58359374918141c0ac7ae34)

    https://github.com/ClassPreloader/ClassPreloader/compare/4.1.0...4.2.0

    Source code(tar.gz)
    Source code(zip)
  • 4.1.0(Dec 31, 2020)

    This is the first release in the 4.1.x series.

    This release contains the following improvements:
    • Added support for PHP 8.0 (db3c991fe626fc69e4f33e6f4ae29b92b8f0a842)

    https://github.com/ClassPreloader/ClassPreloader/compare/4.0.1...4.1.0

    Source code(tar.gz)
    Source code(zip)
  • 4.0.1(Apr 13, 2020)

    This is the first patch release in the 4.0.x series.

    This release fixes the following regressions:
    • Updated funding information (a1264c8a6c079a6a0b8cfc5358b215293c399000)

    https://github.com/ClassPreloader/ClassPreloader/compare/4.0.0...4.0.1

    Source code(tar.gz)
    Source code(zip)
  • 3.2.1(Apr 12, 2020)

    This is the first patch release in the 3.2.x series.

    This release fixes the following regressions:
    • Updated funding information (297db07cabece3946f4a98d23f11f90aa10e1797)

    https://github.com/ClassPreloader/ClassPreloader/compare/3.2.0...3.2.1

    Source code(tar.gz)
    Source code(zip)
  • 4.0.0(Jan 1, 2020)

    This is the first release in the 4.0.x series.

    We've dropped support for PHP 5 and older PHP Parser versions. It's still possible to parse PHP 5 code, but not to run Class Preloader on PHP 5. This is the first release of Class Preloader to support the all the new syntax in PHP 7.3 and 7.4.

    We've also renamed some of our classes, and marked some of our code as internal. What used to be the Factory and ClassPreloader classes are now merged into one class called CodeGenerator. Management of the output file has been extracted to a new class called OutputWriter. Note also that our exception namespace has changed from ClassPreloader\Exceptions to ClassPreloader\Exception.


    https://github.com/ClassPreloader/ClassPreloader/compare/3.2.0...4.0.0

    Source code(tar.gz)
    Source code(zip)
  • 3.2.0(Dec 10, 2017)

    This is the first release in the 3.2.x series.

    This release contains the following improvements:
    • More robust strict declare parsing (#61)

    https://github.com/ClassPreloader/ClassPreloader/compare/3.1.0...3.2.0

    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(Dec 2, 2016)

    This is the first release in the 3.1.x series.

    This release fixes the following regressions:
    • Fixed classes with phpdoc before the namespace (#59)
    This release contains the following improvements:
    • Support PHP 7.1 and PHP Parser 3 (#60)

    https://github.com/ClassPreloader/ClassPreloader/compare/3.0.0...3.1.0

    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Nov 9, 2015)

    This is the first release in the 3.0.x series.

    This release adds support enabling strict types, and skipping files with strict types enabled if we don't want the compiled file to have strict types enabled. It also includes allowing usage with either PHP Parser 1.x or 2.x, rather than just 1.x, previously. Finally, the addition of a Factory class can help you get started even quicker if you're not using the Console package provided.


    https://github.com/ClassPreloader/ClassPreloader/compare/2.0.0...3.0.0

    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Jun 28, 2015)

    This is the first release in the 2.0.x series.

    This release contains internal refactoring and the abstraction of the console command to a separate package. We also have fewer dependencies so this package should be installable in even more places without conflict. Also note that we now only support php 5.5.9+.


    https://github.com/ClassPreloader/ClassPreloader/compare/1.4.0...2.0.0

    Source code(tar.gz)
    Source code(zip)
  • 1.4.0(May 28, 2015)

    This is the first release in the 1.4.x series.

    This release fixes the following regressions:
    • Fixed classes without namespace (#29, #48, #49)
    This release contains the following improvements:
    • Various minor changes

    https://github.com/ClassPreloader/ClassPreloader/compare/1.3.0...1.4.0

    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Apr 18, 2015)

    This is the first release in the 1.3.x series.

    This release fixes the following regressions:
    • PHP 7 Support (2d5a5b17002186d9f878b22d0287f95011a4ea8e, bf9f7436a2463c234bb24d3a1bb3403f868d304d, 30fa71d70196b238b957b8fd74a024eec8438746)
    This release contains the following improvements:
    • Tweaked phpunit config (0544616ba33fb2a6b792b3a7822650810c6d65d9)
    • Various minor fixes (a9a6ef9b1a6960d45481ce7fdf375177eeb7007f, 259b79f9685e5ef6d25e5b66918a6ce9ab3e3aee)
    • Minor cs fixes (82786dcc589932f71dc1e014a63a158143bfaa13, 642bf438ce3fcdcaddb89927295115e62c60870c, 32d7fd2f7731c45f719e4bcd2e5ba7916de4a687, b19768c7eb7170d52f0f4470b0fa6bcfe062406a)

    https://github.com/ClassPreloader/ClassPreloader/compare/1.2.0...1.3.0

    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Jan 26, 2015)

    This is the first release in the 1.2.x series.

    This release fixes the following regressions:
    • Fixed The Console Command On Windows (#36)
    • Fixed Multiple Class Declarations (#39)
    • Fixed The Readme Instructions (76dc4466dc85ca31efe135ff51cf30d663a41269)
    • Fixed Issues With ClassLoader Extension (a6b67d6e6837437959d6f69bf245eec7cb441a3b)
    • Added Missing Version Info To The Application (f0bfbf71fb3335c9473f695d4d966ba2fb879a9f)
    This release contains the following improvements:
    • Added Support For Skipping Classes With DIR Or FILE (#42)
    • Improved Docblocks (#32, f69e254a4aa4e395890de183f2160d42dbdcbe88)

    https://github.com/ClassPreloader/ClassPreloader/compare/1.1.0...1.2.0

    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Sep 23, 2014)

    This is the first release in the 1.1.x series.

    This release fixes the following regressions:
    • Fixed Non-Existent Classes (#26)
    This release contains the following improvements:
    • Upgraded To PHP Parser 1.0 (#27)
    • PSR-4 Autoloading (ae497b8c8bc86cab0dd49b81026b97acde304af6)

    https://github.com/ClassPreloader/ClassPreloader/compare/1.0.2...1.1.0

    Source code(tar.gz)
    Source code(zip)
  • 1.0.2(Sep 7, 2014)

    This is the second patch release in the 1.0.x series.

    This release fixes the following regressions:
    • Fixed An Undefined Variable Issue (e45cfc00f40d74a26876e18112dea750363659fa)
    • Composer Fixes (526394d57ddbf06b38e3f991764147b415de1910)
    This release also contains the following improvements:
    • Tweaked Some Docblocks (8a13e719477a212f2ed18ae74e60aa668ad41a32)
    • Tweaked The Readme (ac526397f05362cd084282e5c53193c5efd2855a)

    https://github.com/ClassPreloader/ClassPreloader/compare/1.0.1...1.0.2

    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Sep 7, 2014)

    This is the first patch release in the 1.0.x series.

    This release fixes the following regressions:
    • Windows Path Fix (bec3c8ba4b2a09bc2e9c45626e58f6c7d9b21ef5)
    This release also contains the following improvements:
    • Add A Branch Alias (3279a898baab198f553166681823a82bfff844bd)
    • Support Interfaces (8130c630e533b0ff8f9a9b762d757f7fac89ed5c, 1a50f7945b725ff2c60f234e51407d1d6e7c77c5)

    https://github.com/ClassPreloader/ClassPreloader/compare/1.0.0...1.0.1

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Sep 7, 2014)

Owner
Class Preloader
Class Preloader
Exploiting and fixing security vulnerabilities of an old version of E-Class. Project implemented as part of the class YS13 Cyber-Security.

Open eClass 2.3 Development of XSS, CSRF, SQLi, RFI attacks/defences of an older,vulnerable version of eclass. Project implemented as part of the clas

Aristi_Papastavrou 10 Oct 26, 2021
Allows generate class files parse from json and map json to php object, including multi-level and complex objects;

nixihz/php-object Allows generate class files parse from json and map json to php object, including multi-level and complex objects; Installation You

zhixin 1 Oct 29, 2021
🔨 Prefixes all PHP namespaces in a file/directory to isolate the code bundled in PHARs.

PHP-Scoper PHP-Scoper is a tool which essentially moves any body of code, including all dependencies such as vendor directories, to a new and distinct

Humbug 479 Nov 9, 2021
Control all text in multiple file bad words filter with worps

About Worps | PHP! Control all text in multiple file bad words filter with worps If you try online Click What to do use for worps Create new object Wo

null 1 Nov 1, 2021
Write to Laravel Config files and maintain file integrity

Laravel Config Writer Write to Laravel Config files and maintain file integrity. This library is an extension of the Config component used by Laravel.

Sam Geo 152 Oct 10, 2021
:globe_with_meridians: List of all countries with names and ISO 3166-1 codes in all languages and data formats.

symfony upgrade fixer • twig gettext extractor • wisdom • centipede • permissions handler • extraload • gravatar • locurro • country list • transliter

Saša Stamenković 4.8k Nov 16, 2021
Greyhole uses Samba to create a storage pool of all your available hard drives, and allows you to create redundant copies of the files you store.

Greyhole Greyhole is an application that uses Samba to create a storage pool of all your available hard drives (whatever their size, however they're c

Guillaume Boudreau 225 Nov 18, 2021
Making multiple identical function calls has the same effect as making a single function call.

Making multiple identical function calls has the same effect as making a single function call.

李铭昕 4 Oct 16, 2021
Simple user settings facade for Hyperf. Settings are stored as JSON in a single database column, so you can easily add it to an existing table.

hyperf-user-settings Simple user settings util for hyperf Settings are stored as JSON in a single database column, so you can easily add it to an exis

lysice 1 Oct 15, 2021
Track your farming and pool performance on the Binance Smart Chain

farm.army - Frontend Track your farming and pool performance on the Binance Smart Chain. Tech Stack PHP 8 + Symfony node.js + npm (Webpack, Symfony en

farm.army 21 Nov 23, 2021
Performance fixes for magento 2 core.

magento2-performance-fixes Performance fixes for magento 2 core. Problem and solution's concept - briefly PHP / Magento doesn't support concurency req

Mariusz Łopuch 33 Oct 18, 2021
A small package to add computed properties to any PHP class. 🐘

Computed Properties This package provides a trait and attribute that can provide computed property support. Installation This package can be installed

Ryan Chandler 21 Sep 7, 2021
Class for manage directly leds on raspberry pi in PHP

led_raspberry Class for manage directly leds on raspberry pi in PHP We can access GPIO ports directly with fwrite() for power on|off leds, without use

Rafael Martin Soto 8 Sep 15, 2021
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

Doctrine 1.1k Nov 21, 2021
Simple class that implement a CAPTCHA for your PHP App.

simple-captcha Simple class that implement a CAPTCHA for your PHP App. Installation Use the package manager composer to install. composer require will

WILLIAM B. SAMPAIO 1 Nov 24, 2021
FuelPHP Framework - Class and Namespace alias library

Fuel Alias Library for lazy class aliasing. Install Via Composer $ composer require fuelphp/alias Usage Within FuelPHP class aliases are used to provi

fuelphp-storage 19 Apr 23, 2017
A class to help convert bytes into other units (kb, mb, etc).

A class to help convert bytes into other units (kb, mb, etc). This package can be used to convert int|float values from bytes to KB, MB and GB as well

Ryan Chandler 12 Aug 30, 2021
COP4331 Class Project 1 - "ConnectUs" virtual contact manager/Rolodex

ConnectUs COP4331 Class Project 1 - "ConnectUs" virtual contact manager/Rolodex Team Members Orion (Project Manager) Eric (Database) Rafael (API/Backe

Orion 4 Sep 25, 2021