In this tutorial we will cover how to create a patch and then configure composer to apply that patch when the module is installed.
Why is this needed?
Sometimes there are fixes you need to apply to code that isn't directly in source control. This method allows you to keep these files out of source control whilst still being able to manage (in source control) the changes to these files.
Scenario
We need to set the default value of $_skipSaleableCheck
within vendor/magento/module-catalog/Helper/Product.php
to true
Code snippet of file to be changed.
Prerequisites
- cweagans/composer-patches must be installed.
- You have a "patches" directory. We usually keep this at the root of the project
/patches
Steps
- cd into the project root and make a copy of the file.
- Make the changes you require to the file (not the newly created .orig file)
vendor/magento/module-catalog/Helper/Product.php
is now
- Change into the module directory
- Create the diff (patch file) we usually us ticket numbers from our project management system though you can use anything unique that works for you
N.B Here you would replace 1001-hot-fix.patch
with an appropriate name.
- Open the patch file and remove the "
.orig
" from the patch file.
If you open1001-hot-fix.patch
you will see it contains
We need to remove .orig
so that the file looks like
N.B there will be a line ending at the end of the file. You need to ensure that this is maintained. It isn't showed in the snippets as it is just an empty line.
- Undo the changes you made to the file.
- Move the patch file into your patches directory
Note: the /patches directory is in the project root/patches
- Update the patch config within the project
composer.json
To do this we need to know the module name, in this case it ismagento/module-catalog
. If you are unsure it can be found in the modulescomposer.json
vendor/magento/module-catalog/composer.json
Now open /composer.json
.
You are looking for patches
under the extra
node. If yours doesn't exist you can paste the code below in. If it does exist, you will need to add the new bits in.
You can specify multiple patches for the same module, if unsure please see here
- Remove the module code from vendor.
- Reinstall using composer
You should see the following
If you check vendor/magento/module-catalog/Helper/Product.php
you will see the changes from the patch file have been applied.
- You should now commit all the files you have changed to source control. In this case it would be:
/patches/1001-hot-fix.patch
/composer.json
Complete
From this point on whenever somebody has you commit, and they install this package it will be updated by the patch file.