6

If i've different version of same third-party library ( or class ) that have of course same namespaces and class names. Is there a way to include them in same project avoiding name collisions?

Another case for this issue happens when we've a modular project where components are developed separately . So we can have different modules that includes same external library file in their own folder, but of course when modules will be loaded , we have a class collision.

in this article Loading multiple versions of the same class

an user suggests to use 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 doesn't work. Classes collides anyway because they are declared gobally instead of vars.

So..is there another solution that is not hand-edit all the namespace of libraries to include?

thanks in advance

Community
  • 1
  • 1
Joseph
  • 1,029
  • 13
  • 26

1 Answers1

3

This is a very common problem in modular systems. In PHP you could try to solve it with very bad hacks (eval, file_get_contents, str_replace), but you would loose a lot of usefull tooling support (backtrace, debugging, op code cache, precise error reporting, just to mention a few).

The usual way to approch these problems is to use some kind of dependency management. E.g. in java maven is used most times, in scala it is maven or sbt and php guys would normaly use composer (never used this one, so I'm not completely sure whether it is good or not and whether it even supports what you need).

These tools usualy have some kind of algorithm to detect and solve 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 select one of the provided versions, select some version in between (sometimes very strange) or let you decide which version to use. But of course, they also cannot solve problems in which you will definitely require both versions within the same namespace.

Generally said, the easiest way is to allways use the same library or module version company wide or at least application wide. The tools above will help you with that.

Sorry, to not help you with your concrete problem, but I hope some of the provided keywords will be of some use for you.

Ska
  • 168
  • 9
  • thanks for your reply :) i've mailed php devs to explain this problem here: news.php.net/php.internals/68115 however seems that composer cannot solve This problem in any way as i said here: http://news.php.net/php.internals/68126 – Joseph Jul 16 '13 at 05:39