Replace Hard Dependency Class with New Simulation Class via “replace” and “classmap” in Composer Configuration
If we are using 3rd party library that managed by composer, which has hard dependency that we don’t want to use, for example, at the following use case:
- “realexpayments/rxp-remote-php” library require a “apache/log4php” dependency for apache “Logger” class usage.
- we don’t want to log everything via “apache/log4php”‘s Logger, for whatever reason.
The one of the solutions for that is by using “replace” and “classmap” configuration in our composer.json
. First, we need to prepare of the class to simulate the Logger
class, for example, we have it in src/App/Apache/Logger.php
:
<?php // src/App/Apache/Logger.php class Logger { function debug(...$args) {} function info(...$args) {} function trace(...$args) {} function warn(...$args) {} function error(...$args) {} function fatal(...$args) {} public static function configure(...$args) {} public static function getLogger() { return new self(); } }
Yes, above class doesn’t do anything, for silent action when Logger::{themethod()}
called in realexpayments/rxp-remote-php
library classes.
Next, we can register it to our composer.json:
{ "require": { // ... "realexpayments/rxp-remote-php": "^1.2" // ... }, "replace": { "apache/log4php": "^2.3.0" }, "autoload": { "psr-4": { "App\\": "src/App/", }, "classmap": [ "src/App/Apache/Logger.php" ] } }
In above configuration, the replace
of “apache/log4php” doesn’t has replacement library in ‘require’ part will make the dependency removed entirely as we don’t want to use it anymore, and by the classmap
configuration, we have new redefined of the Logger class as simulation of “apache/log4php” Logger class.
Last step, we can run:
➜ composer update
That’s it!
leave a comment