I am currently writing my first WordPress plugin. Since I am pretty sure this will not be my last one, I try to put as much code as possible into common code files for later reuse in other plugins.
I am using namespaces and OOP programming to allow the code being reused like I do in my C++ projects (as far as PHP allows to do so).
However in WordPress/PHP there is a problem with no obvious solution: Where should I place the shared code files? WordPress kind of merges all the code in a global application. So copying code into each plugin folder could mean potential collisions and/or random use of code files with same content, but different stages of development. Also this would create ugly redundancies.
I did not find a dedicated central storage place.
Placing the shared code in the "plugins" folder is a bad idea since each shared code file would be considered a separate plugin.
I could add all the shared code by means of a special library plugin (as far as I know, this would make the contained code visible to all other plugins), but this seems kind of weird. Also I am not sure if this would be reliable.
What is the best solution?
Regarding adamiscoding's answer: I am trying the proposed hook solution, pushing the framework-plugin to first place in the plugin loading queue. I found some code snippets that should allow to do so, like the following one:
add_action('activated_plugin', 'load_this_plugin_first');
function load_this_plugin_first()
{
$path = plugin_basename(dirname(__FILE__)).'/'.basename(__FILE__);
if ( $plugins = get_option( 'active_plugins' ) ) {
if ( $key = array_search( $path, $plugins ) ) {
array_splice( $plugins, $key, 1 );
array_unshift( $plugins, $path );
update_option( 'active_plugins', $plugins );
}
}
}
I disable to dependent plugins entirly if the framework plugin was not installed/activated, so I don't get a bunch errors about missing definitions when loading the plugin administration page in that case. I am using the following check for this:
if (!class_exists('Framework\MainClass'))
{
if (is_admin())
{
// What to do here?
}
}
else
{
// Normal plugin code
}
This seems to work fine.
Currently I am a bit unsure what I should do in case of missing framework. I could automatically deactivate it. Or I could show a persistent admin message... but that isn't that easy, because I get a warning about some characters of "unexpected output" when activating the depended plugin due to the message code line:
echo "<div class='updated'><p>Plugin will not work without framework!</p></div>";
This is why I try to check if the plugin code is executed during activation, so I can suppress the message in that case:
if (!function_exists('is_plugin_active'))
{
echo "<div class='updated'><p>Plugin will not work without Framework!</p></div>";
}
This seems to work too but I wonder if there is a better way to check if a plugin is executed during activation than function_exists('is_plugin_active')
?