I’ve tried to include Twig directly in a plugin that I’m creating, installing it using Composer and loading it using the supplied autoloader as recommended in the documentation. Unfortunately, this created naming conflicts because another plugin (WPML) also included Twig.
This resulted in a ton of warnings such as:
Warning: Cannot declare interface Twig_LoaderInterface, because the name is already in use
And finally the script halted at a fatal error:
Fatal error: Cannot redeclare twig_cycle() (previously declared in …
Disabling WPML made my plugin run successfully, but of course I cannot make my plugin incompatible with WPML.
I haven’t had the time to really dig deep into what’s going on here but I’m guessing the Composer autoloader is not smart enough to find that the Twig classes has already been loaded so it tries to load them again. WPML also seems to load Twig using a Composer autoloader, but naturally it will be a completely different instance.
I assume the recommended route is to install Twig “globally” using the WordPress plugin Timber, but for some reason I wanted to try to make my plugin self-contained and not depend on another plugin.
(Actually I will probably go back to relying on Timber because I may create other plugins that also will need to use the Twig templating engine and the duplication of a large library in several plugins is not very appealing. Installing Twig made my plugin grow by 1.8 MB and 852 files, whereas Timber adds 2.8 MB over 1095 files.)
But, just out of curiosity, would it be possible to include a library such as Twig in a conflict-proof way in a WordPress plugin (without making changes to the library itself)?
Read more here:: How to include Twig in a custom plugin without conflicts