Site icon Shyam Makwana

Laravel – How to override vendor class file?

override vendor classes composer.json file

override vendor classes composer.json file

As a Laravel developer you might have faced situation where you don’t like some code in a package in vendor folder, and you wanted to change it. And you can change that directly in that file. But the issue is when you hit composer update command. I figured out how to override vendor classes very easily.

So what’s the solution?

Thanks to composer guys that it has functionality to override any/package classes. Composer uses PSR-4 to load classes. So in composer.json you can mention from which files or folders to load classes. Same as you can exclude it also.

For windows

Exclude Files

See below example to see how I have excluded 3 files from package tymon/jwt-auth

"exclude-from-classmap": ["vendor\\tymon\\jwt-auth\\src\\Middleware\\BaseMiddleware.php"],

In above example it’s seen that I have excluded BaseMiddleware.php file. You have to put this line in composer in main object. One thing to notice here is that I have double backward slashes in path that’s because I was on windows machine and as it is JSON file so I have to escape (\) also so double backward slash there.

Include Files to override vendor

Now we have excluded files that we wanted to override, now new files with changes needs to be included so that composer knows what files to include.

For that Add one more key value pair to ‘psr-4’ key in composer.json like below:

"psr-4": {
            "App\\": "app/",
            "Tymon\\": "app/overrides/"
        }

Red text in above code is added, to instruct composer to include files inside app/overrides folder.

  1. Now create overrides folder.
  2. Copy paste all files from package that you want to override.
  3. Change file according to your needs.
  4. Add above line in composer.json
  5. run command “composer dump-autoload” (without quotes)

Above command will refresh all autoload files to include your new files. Remember whenever you change anything in composer.json file you need to fire above command to reflect changes.

For Unix/Linux

Instructions are same for Linux users, just code will change, that I’m mentioning below. Follow same instructions as windows users above.

Exclude Files

If you’re on Linux/Unix machine path will be like:

"exclude-from-classmap": ["vendor/tymon/jwt-auth/src/Middleware/BaseMiddleware.php"],

Include Files

"psr-4": {
            "App/": "app/",
            "Tymon/": "app/overrides/"
        }

Overrides is just a name, you can choose whatever you like. Important thing is to provide it’s relative path to composer.json file to it. 

Thank you

 

Enjoy Hacking …!!!

Exit mobile version