aclips / class-override
Runtime PHP class overriding with inheritance
Requires
- php: ^8.1
- nikic/php-parser: ^5.0
Requires (Dev)
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Runtime PHP class overriding with inheritance.
aclips/class-override lets you replace a named class from a third-party
package with your own descendant without modifying the package sources. The
library prepares a virtual copy of the original class, points your class at
it, loads your class and registers it under the original name with
class_alias(). Existing code keeps working with the original name, while
new OriginalName() creates your object and parent::method() calls the
original implementation.
Requirements
- PHP
^8.1 - Composer
nikic/php-parser^5.0(installed automatically as a dependency)- Readable source files for the original and override classes; the paths are given in the configuration, so framework autoloaders (Bitrix, legacy kernels) work without Composer class resolution
- The library must be initialized before the first access to any overridden class
Installation
composer require aclips/class-override
Configuration
Configuration is a PHP file that returns an array. The key is the fully
qualified name of the original class. original_class_path is the path to
the file declaring the original class, override_class_path is the path to
the file declaring your class, replace is an optional map of method
visibility changes for the original class.
<?php return [ \Vendor\Package\SomeClass::class => [ 'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/SomeClass.php', 'override_class_path' => __DIR__ . '/../src/Override/SomeClass.php', ], \Vendor\Package\AnotherClass::class => [ 'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/AnotherClass.php', 'override_class_path' => __DIR__ . '/../src/Override/AnotherClass.php', 'replace' => [ 'someMethod' => [ 'visibility' => 'public', ], ], ], ];
The override class is discovered from override_class_path: the file must
contain exactly one class extending the original class. Both paths are
validated during init(), together with the presence of the original class
in its file.
A framework class that is not registered with Composer can be overridden the same way:
<?php return [ \CCrmDeal::class => [ 'original_class_path' => __DIR__ . '/../../bitrix/modules/crm/classes/mysql/crm_deal.php', 'override_class_path' => __DIR__ . '/../../local/override/crm_deal.php', 'replace' => [], ], ];
Allowed visibility values: public, protected, private.
Override class
Your class extends the original class as usual:
<?php namespace App\Override; class SomeClass extends \Vendor\Package\SomeClass { public function someMethod(): string { return 'custom'; } }
Initialization
Initialize the library once after loading Composer autoload and before the first access to any overridden class:
<?php require_once __DIR__ . '/vendor/autoload.php'; \Aclips\ClassOverride\Override::init( __DIR__ . '/config/override.php' );
PHP cannot replace a class that is already declared, so initialization after
the original class has been loaded throws an OverrideException. The same
applies when the original class is already declared at the moment of
init(). init() also validates the configured paths: the original class
must be found in original_class_path, and override_class_path must
contain a class extending it. Initialize first, then use the classes.
Calling init() twice with the same configuration is a no-op. Calling it
again with a different configuration throws an OverrideException.
Replace
replace changes the visibility of methods on the original class. This is
useful when you need to call or override a method that is protected or
private in the original class.
<?php return [ \Vendor\Package\SomeClass::class => [ 'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/SomeClass.php', 'override_class_path' => __DIR__ . '/../src/Override/SomeClass.php', 'replace' => [ 'someMethod' => [ 'visibility' => 'public', ], ], ], ];
Behavior of replace:
- method names are matched case-insensitively;
- a missing method, an unknown key or an invalid visibility value throws an
OverrideException; - only methods declared directly in the class are visible to
replace: methods coming from traits or parent classes cannot be changed, and the error message says so; - changing visibility does not remove
final: changing the visibility of afinalmethod throws anOverrideException, because the method still cannot be overridden; replaceonly changes visibility, it never changes the method body;staticandabstractmodifiers are preserved.
Limitations and known features
- Already declared classes cannot be replaced.
init()and the loader throw anOverrideExceptioninstead of silently doing nothing. finalclasses andfinalmethods cannot be overridden.- Interfaces, traits and enums cannot be overridden.
- Classes provided by PHP extensions cannot be overridden.
- The configured source paths are used as given: no Composer class resolution
is needed for the overridden classes themselves. Composer
ClassLoaderinstances registered inspl_autoload_functions()are used only to intercept other classes that share a source file with a configured class. Without such a loader (framework autoloaders), those sibling classes must be loaded before initialization or live in separate files. - The override class is discovered by parsing
override_class_path: exactly one class in that file must extend the original class, otherwiseinit()throws anOverrideException. - Classes loaded with a direct
requirebefore initialization are not handled. - Method bodies cannot be replaced through configuration, only visibility.
- A class that extends an overridden class must not be declared in the same
source file as the class it extends (including anonymous classes and
subclasses of the override class itself). Such a configuration throws an
OverrideExceptionnaming both classes; move the subclass to a separate file. Chained overrides in separate files work as usual. - Classes that share a source file with a configured class are loaded from a sanitized copy of that file, in which the configured classes are renamed. This keeps the original declaration semantics and avoids redeclare errors.
- Inside the overridden original class,
self::classand__CLASS__return the internal virtual class name, not the original name.static::binds to your class, exactly as with normal inheritance.new self()creates an instance of the virtual class. The same applies to__METHOD__: it returns the virtual class name, and__LINE__refers to the generated file.__FILE__and__DIR__are rewritten to the original source location and keep their usual meaning. - Top-level executable code in an overridden source file must not trigger the loading of a class that is declared later in the same file. If the generated file fails during loading, the failure is reported once and the file is not retried in the same process.
- Requiring the override class file directly after initialization is not supported.
- Generated files are cached in
sys_get_temp_dir()/aclips-class-override-<uid>. The cache key includes the source path and content hash, the configured class names and replace settings, and the versions of the compiler, PHP andnikic/php-parser. Changing any of them regenerates the file. Files and directory ownership are verified before loading, because the temporary directory is shared. Cached files are not garbage collected and may accumulate over time.
Full minimal example
Layout:
project/
├── composer.json
├── config/
│ └── override.php
├── src/
│ ├── Override/
│ │ └── SomeClass.php
│ └── ...
└── vendor/
composer.json:
{
"require": {
"aclips/class-override": "^1.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
config/override.php:
<?php return [ \Vendor\Package\SomeClass::class => [ 'original_class_path' => __DIR__ . '/../vendor/vendor/package/src/SomeClass.php', 'override_class_path' => __DIR__ . '/../src/Override/SomeClass.php', ], ];
src/Override/SomeClass.php:
<?php namespace App\Override; class SomeClass extends \Vendor\Package\SomeClass { public function someMethod(): string { return 'custom:' . parent::someMethod(); } }
Bootstrap:
<?php require_once __DIR__ . '/vendor/autoload.php'; \Aclips\ClassOverride\Override::init(__DIR__ . '/config/override.php'); $object = new \Vendor\Package\SomeClass(); var_dump($object instanceof \App\Override\SomeClass); // true echo $object->someMethod(); // your implementation
Tests
composer test