Class Replacement Manager
No security coverage
The Crema module allows you to replace existing PHP classes within your Drupal modules. By defining replacements in your module's info file, you can provide your own implementations of Drupal classes without altering the core or contributed modules directly. This enables custom logic and behavior through a clever mechanism that intercepts class loading, though it comes with limitations such as debugger inaccessibility and file size constraints.
⇧ …And the idea also is pretty insane and silly anyway…
A PoC module which aim to "replace" PHP classes you define in your module's info.yml file.
Usage
- Add a new key
class_replacementsto the.info.ymlof the module which contains the replacement modules:
name: Migration Manager Replacement type: module class_replacements: # Key: the qualified name of the class which should be replaced. # Value: location of the replacement file, relative to the actual module's root. Drupal\migrate\Plugin\MigrationPluginManager: src/migrate/MigrationPluginManager.php Drupal\migrate_drupal\MigrationPluginManager: src/migrate_d/MigrationPluginManager.php - Make sure that the module depends on
crema; or have a good reason not doing so 🙃 - Create the replacement file at the declared location:
- Its namespace must be the namespace of the original file with the leading
Drupalreplaced byCrema. - The class name must be the same as the replaced class name.
- If you want to extend the original class (I'm pretty sure you want to), then you can do it by adding the proper (aliased) use declaration of the original class.
# File content of <module_root>/src/migrate/MigrationPluginManager.php <?php namespace Crema\migrate\Plugin; use Drupal\migrate\Plugin\MigrationPluginManager as Original; /** * Replaces the default migration plugin manager. */ class MigrationPluginManager extends Original { protected $defaults = [ 'class' => '\Drupal\my_module\Plugin\BetterMigration', ]; public function foo(): string { return 'foo'; } } - Its namespace must be the namespace of the original file with the leading
Limitations
- You cannot replace the same PHP class (or trait or interface) more than once.
- Due to the way how Crema works, you cannot use debugger breakpoint neither in the replacement nor in the replaced
phpfile. - The module only can replace files with
Drupal\*namespace, and not all of them, but most of them. For example you cannot replace Drupal kernels, database driver classes etc. - Crema uses PHP's temporary stream to store the replaced and the replacement files before it loads them. Because of this, (for now) the files must me smaller than 2MB: https://www.php.net/manual/en/wrappers.php.php#wrappers.php.memory