I’ve been busy developing a WordPress plugin lately and I experienced a best practice right away.
While developing the plugin will probably be the only one loaded. Once released into the wild, for instance by testing it on your live site, and being used in conjunction with pre installed plugins, you may run into PHP Fatal error: Cannot redeclare class ... in ...
errors, even when you use import_once
or require_once
.
I did not dig to deep into this, but I assume WordPress loads every activated plugin before displaying a page. PHP processes your plugin and imports the file, as it has not been included into the scope of your plugin, being the main script. However, the class has been defined in the scope of this process or thread, so, from a PHP perspective, it’s an attempt to redefine a class.
The fix is easy. Find out which classes your plugin uses, and import the module conditionally, using something like this:
if (! class_exists('Smarty')) require_once('Smarty/libs/Smarty.class.php');
This prevents the PHP Fatal Error from occuring but it’s probably going to be a source of other problems. Consider your plugin using a specific version of Smarty which is incompatible with the version used by a plugin processed before yours. Your component would not be loaded, and your plugin would be using the incompatible version instead. I suggest documenting the use of standard components in the readme.txt bundled with your plugin. It shouldn’t be too difficult using a dependency strategy like RPM.