Loading two classes with the same name

Asked

Viewed 410 times

2

In a legacy system, I have a situation where 2 classes have the same name. One legacy version and another recent one (using MVC framework). There are cases that in the new version of the class I need to call the same (old) or other class of the old system. Unfortunately there is no way to eliminate the old class (to maintain compatibility) and it would be very difficult to migrate to the new version, having to keep the old and the new. The old system was not designed to call new methods, only the new one manages to call the old.

After discussion, we decided to create a class that serves as a "bridge" to the old classes of the system. We wanted to create a kind of "sandbox", where we could call old classes (with the same name as new ones) and return their results, alone.

Something that would solve (and be correct) would be to use namespaces, but slash on the rework problem of fitting both the old and the new part. So we discarded that.

We ended up injecting a custom __autoload() when we invoked this "bridge" class. Where to check if the name called exists in the old part of the system, if it exists, takes the contents of it, gives a append in her name, to modify the name and not cause conflict, check the class code and make substitutions of other classes to ensure that everything dependent is invoked. The content is saved in a temporary file and included, after the termination is erased the temporary file.

I think seeing the class will be able to understand better: https://gist.github.com/juliovedovatto/559eb1d76c4ea8fb81d8

I want to know if there is a more efficient way to do this without appealing to a system hack. We saw about php Runkit_Sandbox (http://php.net/manual/en/runkit.sandbox.php) and the uopz (http://php.net/uopz), but I can’t imagine how to use it (and if it really works). We have another problem that the version of our PHP is 5.3 (unfortunately it is difficult to update version, because of the legacy system).

  • I could not apply namespace?

  • You can only use namespaces in the new version and call classes with the same root namespaces name as a dependency.

1 answer

1

First option, do this on the deploy instead of doing a Loader. It is easier and efficient your deploy script to rename classes once and only choose the PHP file.

Runkit in production is a bad idea.

Any other solution (except refactoring) will be even worse -- and I would totally recommend a Refactoring. Note, if you just need to change class names you can make one sed or replace in your own IDE with a regex, like the one you’ve already put in your autoloader, and resolve it forever. You will only have problems if the evals abuse code, and you will detect any problem on the fly when you run your test suite.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.