This will be a short guide on how you can override a specific class included in your vendor directory by Composer with your implementation of that class. You might need to do this if you need to urgently fix any issues you’ve found, or you simply have a different idea of the implementation that you need specifically for your application.

Note: I generally do not recommend this unless you have exhausted all other available options. The best way is always to report the issue upstream or even better, create a pull request to the original repository.

As an example, let’s say in your application, you are using league/csv package, but there’s something you’ll need to change that it’s not possible to do unless you edit it directly in that class. First, you’ll need to duplicate the class that you want to override and put it into a directory of your choosing but keep the namespace declaration identical.

For Laravel, I usually put this into app/Overrides directory that I’ll create later. Then you’ll need to edit your composer.json file and add two extra lines inside the autoload section to swap out the implementation.

"exclude-from-classmap": ["vendor/league/csv/src/Writer.php"],
"files": ["app/Overrides/Writer.php"]

The first line will exclude the original class from being loaded, and the second class will point to the original class with the proper namespace for your implementation.

Then you can run:

composer dump-autoload

And you’re good to go!