PHP includes another version of the same library

If I have a different version of the same third-party library (or class) that has the same namespaces and class names. Is there a way to include them in one project, avoiding name conflicts?

Another case for this problem arises when we have a modular project where components are developed separately. Thus, we can have different modules that include the same external library file in their own folder, but, of course, when the modules are loaded, we have a clash of classes.

in this article Downloading multiple versions of the same class

the user suggests using this code:

namespace old { include /lib/api-1.0/library.php; } namespace foo { include /lib/api-2.0/library.php; } $oldlibary = new old\Library(); $newlibrary = new foo\Library(); 

but of course it won’t work. Classes collide anyway, because they are declared gobally, not vars.

So, is there another solution that does not manually edit the entire library namespace to include?

early

+4
source share
1 answer

This is a very common problem in modular systems. In PHP, you can try to solve the problem with very bad hacks (eval, file_get_contents, str_replace), but you will lose a lot of useful tool support (backtrace, debugging, op code cache, accurate error reporting, just to mention a few).

The usual way to solve these problems is to use some kind of dependency management. For instance. in java, maven is used most often, in scala it is maven or sbt and php guys will use composer normally (never used this one, so I'm not quite sure if this is good or not, and whether it supports what you need).

These tools usually have some kind of algorithm for detecting and resolving typical version conflicts. However, this will only work if two conflicting versions are compatible (or at least the part you are using is compatible). They will either choose one of the provided versions, or they will choose some version (sometimes very strange), or let you decide which version to use. But of course, they also cannot solve problems in which you definitely need both versions in the same namespace.

As a rule, the easiest way is to always use the same library or module version throughout the company, or at least in a wide range of applications. The above tools will help you with this.

Sorry to not help you with your specific problem, but I hope that some of the keywords provided will be useful to you.

+3
source

Source: https://habr.com/ru/post/1491245/


All Articles