DEV Community

Graham Crocker
Graham Crocker

Posted on • Updated on

Create a Magento 2 Patch to override core

You may run into a situation where you need to modify core for some reason or another. In my career as a Magento2 developer there were many instances where we needed to do this and there are many ways to do it such as overriding/extending via preference or using a plugin, but I found that if you need to fix a Magento bug the best way of doing it is via a git patch, because if anything in the vendor/magento folder changes it will not apply the change and will be more visible to you, rather than spotting weird errors in logs a few years later when Magento2 fixes it.

Image description

You may also submit this fix as a PR to the magento2 github repository, but be advised that there is a lot of overhead that goes into proving a problem exists https://github.com/magento/magento2/pull/10102 and there are cases where this is not done such as this example case where we used a patch to fix an issue that was infrastructure related.
https://alanstorm.com/fixing-x-magento-tags-too-large-errors/

1. Commit the original state

Go into root directory

git init
git add vendor/magento
git commit -m 'init'

2. Commit your change

Make your code change
git add vendor/magento
git commit -m 'Description of your change'

3. Create the Patch

git format-patch -1 HEAD
cp x.patch patches/INITIALS-descriptionofchange.patch

Ensure the relative paths are a/vendor/x/y

4. Test the patch

Find the commit of init
git log
Reset vendor folder
git reset --hard <commit hash>

Execute the patch to check whether it applies or not
if git apply --check patches/INITIALS-descriptionofchange.patch; then git apply patches/INITIALS-descriptionofchange.patch; fi"

5. Add script to composer.json to apply the patch

Add to composer.json
"scripts": {
   "post-install-cmd": [
       "if git apply --check patches/INITIALS-descriptionofchange.patch; then git apply patches/INITIALS-descriptionofchange.patch; fi",
}
Enter fullscreen mode Exit fullscreen mode

6. Conclusion

Ensure to run composer install to apply changes on CI/CD process or when pulling in other developers patches

Troubleshooting

If your machine can't handle git add to vendor/magento then go directly to the folder you need changing and do the process from there rather than from root directory. After you copy over the patch match the relative paths (where there is a/... and b/...) with the full path like a/vendor/magento.

Discussion (0)