Home » Php » php – Handling classes with many versions, adapter or factory?

php – Handling classes with many versions, adapter or factory?

Posted by: admin July 12, 2020 Leave a comment


I am working with a third party library that has new versions of the same(mostly) classes every 3-4 months. I don’t want to have to update every class that uses them every time a new version is out.

The library is structured in the following manner where the service uses the class of the same version.


I can’t feed an adapter into the service, so I will have to construct the actual class. To illustrate:
$myService->handle(new MyClass);

My solution where factories use and build the actual classes:

So every time a new version of the classes are published, I will have to update all my factories.


  1. Is this the optimal approach to this problem?
  2. Is factory the correct naming convention to this approach?
How to&Answers:

The problem is that they use version number in any position of namespace.
In my opinion, your solution is not that bad.

The problem is when you want you type declaration in code, but this could generate only drawback. Then the same go to Factories. Then every few month you need to update them.

Autoloader itself, won’t resolve this, as you still declared class in factory. Additionally, you want omit problem coupling project to version – in result, you will omit everywhere type declaration for this objects.

Good advice is to use Integration testing (PHPUnit), this will find any problem with Data structure after update, you will need this.

Second advice – in constructor, send actual version to load and use loading by string name

return new $fullClassName()

with correct class name and version. Then you will change this only in you config file, for given factory. Don’t use use for following classes then.

I hope, this will fully resolve you problem.


From my point, this namespacing system is ridiculous. They publish their library with a version tag, and classes in it are this version only. When you decide to upgrade, you also receive one version only. Like any other library.

So now I’ve vomitted this system, how to fix it ?

One solution is to use an event handler in composer, such as post-package-update to dump the latest version number into a file. Then your factory read this file and load the correct version of the library


In my opinion, it is Google who are wrong here. They use semantic tagging in their GitHub repo, so what they should be telling people is to install the correct version using composer, instead of their bad solution where the latest tagged version on github contains 3 or 4 older versions in a namespaced folder.

So having said that, your idea ain’t all that bad. A quick find and replace would also work.

I would raise an issue on their Github and explain why they should be using the Git & composer tags!