跳至主要内容
版本:5.1

模块和插件

模块和插件的服务提供者文件比组件的服务提供者文件简单得多。如果您查看 Joomla 实例的模块和插件文件夹,您会发现几个 services/provider.php 文件的示例。

模块

例如,对于 Joomla 5 中的 mod_breadcrumbs,我们有

use Joomla\CMS\Extension\Service\Provider\Module;

public function register(Container $container): void
{
$container->registerServiceProvider(new ModuleDispatcherFactory('\\Joomla\\Module\\Breadcrumbs'));
$container->registerServiceProvider(new HelperFactory('\\Joomla\\Module\\Breadcrumbs\\Site\\Helper'));

$container->registerServiceProvider(new Module());
}

该模块使用标准的 Joomla\CMS\Extension\Service\Provider\Module 类生成其扩展类 \Joomla\CMS\Extension\Module。

它有 2 个依赖项

  1. 它使用 ModuleDispatcherFactory 类在 src/Dispatcher/Dispatcher.php 中实例化自己的 Dispatcher.php
  2. 它使用 HelperFactory 在 src/Helper/BreadcrumbsHelper.php 中查找其辅助文件

插件

例如,对于 plugins/fields/color 中的自定义字段颜色插件

use Joomla\Plugin\Fields\Color\Extension\Color;

public function register(Container $container)
{
$container->set(
PluginInterface::class,
function (Container $container) {
$plugin = new Color(
$container->get(DispatcherInterface::class),
(array) PluginHelper::getPlugin('fields', 'color')
);
$plugin->setApplication(Factory::getApplication());

return $plugin;
}
);
}

插件的扩展类是 Color,它被实例化为 2 个参数传递到其构造函数中

  • EventDispatcher 类 - 这是从父 DIC 获取的,它最初是在 Joomla 初始化时从 libraries/src/Service/Provider/Dispatcher.php 放入其中的
  • 插件 stdClass 对象,Joomla 传统上使用它来存储插件数据(id、name、type 和 params)。

这是一个您可以用于您自己的插件的标准模式。您显然可以通过在 services/provider.php 文件或标准插件代码中调用 Factory::getApplication 来获取 Application 实例。