plugins-api.html 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <p>APIs are a form of plugins that are tightly associated with a module. Instead of a module providing any number of plugins, each module provides only one file for an API and this file can contain hooks that the module should invoke.</p>
  2. <p>Modules support this API by implementing hook_ctools_plugin_api($module, $api). If they support the API, they return a packet of data:</p>
  3. <pre>
  4. function mymodule_ctools_plugin_api($module, $api) {
  5. if ($module == 'some module' && $api = 'some api') {
  6. return array(
  7. 'version' => The minimum API version this system supports. If this API version is incompatible then the .inc file will not be loaded.
  8. 'path' => Where to find the file. Optional; if not specified it will be the module's directory.
  9. 'file' => an alternative version of the filename. If not specified it will be $module.$api.inc
  10. );
  11. }
  12. }
  13. </pre>
  14. <p>This implementation must be in the .module file.</p>
  15. <p>Modules utilizing this can invole ctools_plugin_api_include() in order to ensure all modules that support the API will have their files loaded as necessary. It's usually easiest to create a small helper function like this:</p>
  16. <pre>
  17. define('MYMODULE_MINIMUM_VERSION', 1);
  18. define('MYMODULE_VERSION', 1);
  19. function mymodule_include_api() {
  20. ctools_include('plugins');
  21. return ctools_plugin_api_include('mymodule', 'myapi', MYMODULE_MINIMUM_VERSION, MYMODULE_VERSION);
  22. }
  23. </pre>
  24. <p>Using a define will ensure your use of version numbers is consistent and easy to update when you make API changes. You can then use the usual module_invoke type commands:</p>
  25. <pre>
  26. mymodule_include_api();
  27. module_invoke('myhook', $data);
  28. </pre>
  29. <p>If you need to pass references, this construct is standard:</p>
  30. <pre>
  31. foreach (mymodule_include_api() as $module => $info) {
  32. $function = $module . '_hookname';
  33. // Just because they implement the API and include a file does not guarantee they implemented
  34. // a hook function!
  35. if (!function_exists($function)) {
  36. continue;
  37. }
  38. // Typically array_merge() is used below if data is returned.
  39. $result = $function($data1, $data2, $data3);
  40. }
  41. </pre>
  42. <p>TODO: There needs to be a way to check API version without including anything, as a module may simply
  43. provide normal plugins and versioning could still matter.</p>