How to avoid duplicate API classes?

I am trying to include a commonly used API in my WordPress plugin and encountering duplicate class errors. I’ve tried checking using class_exists() but without being able to control the order plugins load, another plugin (that doesn’t check class_exists) loads after mine and then WP crashes.

I’ve considered editing the API class and adding a relatively unique prefix. I’ve also considered just updating it to use namespaces. However, maintaining changes in 3rd party code doesn’t seem ideal in the long term.

Read More

Is there a way to accomplish this without editing the API code directly? How about creating a namespace’d wrapper for the API classes?

UPDATE:

I see that a couple others share this same question. Over the past month, I have continued reading about best practices and still haven’t found any good advice. My software is now using several APIs that are likely to conflict because other plugin writers don’t check class_exists. I cannot edit directly to namespace all of these 3rd party APIs for some are quite large/complex and I feel there has to be a better alternative.

I’m still curious if there is a way to create a namespace’d wrapper for 3rd party API classes. Or if there are any other ideas, I quite eager to hear.

Related posts

1 comment

  1. The classname in PHP is hard-encoded into the source file. That is including the namespace.

    This actually is the reason why PHP has introduced a namepsace feature in PHP 5.3, so that same named classes can reside in their own namespace to prevent the class-name clashes (the fatal error and white screen of death you can see).

    There is not much you can do about the issue you have. The original library needs to be namespaced. If the upstream vendor of that lib is not able to deliver that, one option is you can fork the library and do the work your own. You can then consider to provide your changes as a pull-request back to the original project so that everybody can benefit from your changes (and future changes can be easier integrated from upstream into your copy).

    However when this is always about the same class (from the same library), then you’re just running into a problem with wordpress plugins: As there is no shared libary in wordpress with autoloading (well, the wordpress core could be seen as such, just w/o autoloading), each plugin must check whether or not a certain class needs to be loaded or not if it is shared between multiple plugins. If only one of the plugins misbehaves with that, you will see the crashes you have. In that case you will need to fix those plugins and report the problems back to the plugin vendors.

Comments are closed.