Config file

Note

此页面的内容需要进行重大更新。旧页面包含过时且可能不准确的信息。您仍然可以在 Mautic Developer Documentation archived repository 中访问它。

如果您有兴趣帮助开发此页面和其他新内容的,请考虑加入文档编写工作。

请阅读 Contributing GuidelinesContributing to Mautic’s documentation 以开始您的贡献。

Mautic 利用一个简单的基于数组的配置文件来注册路由、菜单项、服务、类别和配置参数。

General config items

Mautic 通过常规配置选项识别插件。

<?php
// plugins/HelloWorldBundle/Config/config.php

return [
    'name'        => 'Hello World',
    'description' => 'This is an example config file for a simple Hello World plugin.',
    'author'      => 'Someone Awesome',
    'version'     => '1.0.0',

// ...

Key

Type

Description

name

string

Human readable name for the Plugin that displays in the Plugin Manager.

description

string

Optional description of the Plugin. This is currently not displayed in the UI.

author

string

Author of the Plugin for attribution purposes.

version

string

The version should be in a format compatible with PHP’s standardized version strings. The Plugin Manager uses PHP’s version_compare() to determine if the Plugin is eligible for an upgrade.

Routing config items

路由定义了执行指定控制器操作的 URL 路径。通过插件配置中的 routes 键,将路由注册到 Mautic 中。在 Mautic 的 supported firewalls 下定义每个路由,并使用唯一标识符和 route’s definition.

<?php

// ...

```markdown ‘routes’ => [

‘main’ => [
‘plugin_helloworld_world’ => [

‘path’ => ‘/hello/{world}’, ‘controller’ => [MauticPluginHelloWorldBundleControllerDefaultController, ‘world’], ‘defaults’ => [

‘world’ => ‘earth’,

], ‘requirements’ => [

‘world’ => ‘earth|mars’,

],

], ‘plugin_helloworld_list’ => [

‘path’ => ‘/hello/{page}’, ‘controller’ => [MauticPluginHelloWorldBundleControllerDefaultController, ‘index’],

], ‘plugin_helloworld_admin’ => [

‘path’ => ‘/hello/admin’, ‘controller’ => [MauticPluginHelloWorldBundleControllerDefaultController, ‘admin’]

],

], ‘public’ => [

‘plugin_helloworld_goodbye’ => [

‘path’ => ‘/hello/goodbye’, ‘controller’ => MauticPluginHelloWorldBundleControllerGoodbyeController::class, // assumes an invokable class

], ‘plugin_helloworld_contact’ => [

‘path’ => ‘/hello/contact’, ‘controller’ => MauticPluginHelloWorldBundleControllerContactController::class, // assumes an invokable class

],

], ‘api’ => [

‘plugin_helloworld_api’ => [

‘path’ => ‘/hello’, ‘controller’ => MauticPluginHelloWorldBundleControllerApiHelloController::class, // assumes an invokable class ‘method’ => ‘GET’,

],

],

],

// …

路由防火墙

以下防火墙可用于路由。

Key

URL 前缀

描述

api

/api/*

需要 API 用户身份验证的路由,例如 OAuth 2.0。

main

/s/*

需要标准用户身份验证才能访问 UI 的安全部分的路由。

public

/*

面向公众且不需要任何用户身份验证的路由。

catchall

/*

一个特殊的公共防火墙,在所有其他路由之后编译,主要由着陆页用于识别自定义着陆页 URL。

每个防火墙接受定义的路由数组。 每个键,即路由的名称,必须在所有包和防火墙中唯一。 路径必须在同一防火墙内唯一。 顺序很重要,因为 Symfony 使用第一个匹配的路由。

Warning

每个路由的名称必须在所有包和防火墙中唯一,并且路径必须在同一防火墙内唯一。

Warning

路由的顺序很重要,因为 Symfony 使用与 URL 匹配的第一个路由。

路由定义

```

路由定义定义了路由的方法、路径、控制器、参数以及其他定义的属性。

Key

Is required?

Type

Description

path

yes

string

定义路由的 URL 路径。使用花括号定义参数占位符。Symfony 将参数值传递给控制器方法中的匹配名称的参数。例如,/hello/{world} 匹配 /hello/earth/hello/mars/hello/jupiter 等。如果控制器的方法中声明了 string $world 参数,则 Symfony 会将 earthmarsjupiter 分别赋值给该参数。

controller

yes

string|array

定义当路径匹配时要调用的控制器和函数。支持三种格式。旧的字符串格式为 HelloWorldBundle:World:hello,执行 MauticPluginHelloWorldBundleControllerWorldController::helloAction()。从 Mautic 4 开始推荐的格式是 [MauticPluginHelloWorldBundleControllerWorldController::class, ‘hello’],执行 MauticPluginHelloWorldBundleControllerWorldController::hello(),或者 MauticPluginHelloWorldBundleControllerWorldController::class,执行 MauticPluginHelloWorldBundleControllerWorldController::__invoke()

method

no

string

将路由限制为特定的方法。例如 GET、POST、PATCH、PUT、OPTIONS。默认情况下,Symfony 识别所有方法。

defaults

no

array

定义路径占位符的默认值,以键/值对的形式。例如,给定路径 /hello/{world},其中 world 的默认值为 earth,则将其定义为数组 [‘world’ => ‘earth’]。访问 /hello 现在与访问 /hello/earth 相同。

requirements

no

array

定义正则表达式模式,用于占位符,URL 路径必须匹配这些模式,以键/值对的形式。例如,当给定路径 /hello/{world}requirements[‘world’ => ‘earth|mars’] 时,访问 /hello/jupiter 将被忽略。

format

no

string

设置 Request 对象的“请求格式”,例如响应的 “Content-Type”。例如,json 格式会转换为 “Content-Type” 为 “application/json”。

standard_entity

no

boolean

如果防火墙为 api,则将此设置为 TRUE 会自动注册用于单个和批量处理实体的 GET、POST、PUT、PATCH 和 DELETE API 端点。

特殊路由参数

如果插件未另作定义,Mautic 将默认以下路由定义。

    • Parameter
      • Default value

      • Description

        • {page}

        • ['requirements' => ['{page}' => '\d+']]

        • Recognizes only digits for page parameters - used in pagination.

        • {objectId}

        • ['defaults' => ['{objectId' => 0]]

        • Routes that views or edits a specific entity may leverage this.

        • {id}

        • ['requirements' => ['{id}' => '\d+']]

        • Requires a digit if using the api firewall.

Advanced routing

Configure custom routes through writing a listener to the \Mautic\CoreBundle\CoreEvents::BUILD_ROUTE event. Listeners to this event receives a Mautic\CoreBundle\Event\RouteEvent object. Mautic dispatches an event for each firewall when compiling routes.

class Mautic\CoreBundle\Event\RouteEvent
getType()
Returns:

The route firewall for the given route collection.

Return type:

string

getCollection()
Returns:

Returns a RouteCollection object that can be used to manually define custom routes.

Return type:

\Symfony\Component\Routing\RouteCollection

addRoutes(string $path)

Load custom routes through a resource file such as yaml or XML.

Parameters:
  • $path (string) – Path to the resource file. For example, @FMElfinderBundle/Resources/config/routing.yaml.

Return type:

void

Debugging routes

Use the follow commands to help debug routes:

Command

Description

php app/console router:debug

Lists all registered routes.

php app/console router:debug article_show

Lists the definition for the route article_show.

php app/console router:match /blog/my-latest-post

Lists the route that matches the URL path /blog/my-latest-post.

服务配置项

服务定义了插件的类及其与 Mautic 和 Symfony 的依赖关系。在特定键中定义的服务的会自动添加标签,如下所示。

<?php

// ...

'services' => [
    'events'  => [
        'helloworld.leadbundle.subscriber' => [
            'class' => \MauticPlugin\HelloWorldBundle\EventListener\LeadSubscriber::class,
        ],
    ],
    'forms'   => [
        'helloworld.form' => [
            'class' => \MauticPlugin\HelloWorldBundle\Form\Type\HelloWorldType::class,
        ],
    ],
    'helpers' => [
        'helloworld.helper.world' => [
            'class' => MauticPlugin\HelloWorldBundle\Helper\WorldHelper::class,
            'alias' => 'helloworld',
        ],
    ],
    'other'   => [
        'helloworld.mars.validator' => [
            'class'     => MauticPlugin\HelloWorldBundle\Form\Validator\Constraints\MarsValidator::class,
            'arguments' => [
                'mautic.helper.core_parameters',
                'helloworld.helper.world',
            ],
            'tag'       => 'validator.constraint_validator',
        ],
    ],
],

// ...

服务类型

为了方便,Mautic 会自动为在特定键中定义的服务的添加标签。

    • Key
      • Tag

      • Description

        • controllers

        • controller.service_arguments

        • Controllers are typically autowired by Symfony. However, you can register controllers as services to manage your own dependency injection rather than relying on Symfony’s service container.

        • models

        • mautic.model

        • Deprecated. Use service dependency injection instead.

        • permissions

        • mautic.permissions

        • Registers the service with Mautic’s permission service.

        • * or other

        • n/a

        • You can use any other key you want to organize services in the config array. Note that this could risk incompatibility with a future version of Mautic if using something generic that Mautic starts to use as well.

Service definitions

Key each service with a unique name to all of Mautic, including other Plugins.

    • Key
      • Is required?

      • Type

      • Description

        • class

        • yes

        • string

        • Fully qualified name for the service’s class.

        • arguments

        • no

        • array

        • Array of services, parameters, booleans, or strings injected as arguments into this service’s construct. Wrap parameter names in % signs, for example, '%mautic.some_parameter%',. Hard coded strings need to be wrapped in " signs, for example, '"some string"',. Any other string is assumed to be the name of a defined service.

        • alias

        • conditional

        • string

        • Used by specific types of services. For example, services defined under helpers use this as the key in the $view variable to access the defined service from PHP templates. Otherwise, it defines an alternate name for the service.

        • serviceAlias

        • no

        • string

        • Define an alias for this service in addition to the name defined as the service’s key. Note that Mautic sets the service’s class name as an alias by default.

        • serviceAliases

        • no

        • array

        • Define multiple aliases for this service in addition to the name defined as the service’s key. Note that the service’s class name is set as an alias by default.

        • tags

        • no

        • array

        • An array of tags when there are more than one. See Mautic service tags for Mautic specific tags. This supersedes tag.

        • tagArguments

        • no

        • array

        • Some tags have special arguments definable through an array of tagArguments. If using tag, this should be a key/value pair of the arguments specific to the given tag. For example, ['tag' => 'tag1', 'tagArguments' => ['tag1-key' => 'tag1-value'],],. If using tags, this should be an array of arrays keyed the same as the values of tags. For example, ['tags' => [ 'tag1', 'tag2'], 'tagArguments' => [['tag1-key' => 'tag1-value'],['tag2-key' => 'tag2-value'],],],.

        • factory

        • no

        • array

        • Define a factory to create this service. For example, 'factory' => ['@doctrine.orm.entity_manager', 'getRepository'],. See Symfony 5 factories.

        • methodCalls

        • no

        • array[]

        • Define methods to call after the service is instantiated. Use an array of arrays with keys as the method name and values the arguments to pass into the given method. For example, ['methodCalls' => ['setSecurity' => ['mautic.security'],],],.

        • decoratedService

        • no

        • string

        • Name of another service to override and decorate. The original service becomes available as thisServiceName.inner to this or others services. See Symfony 5 service decoration.

        • public

        • no

        • boolean

        • Defines the service as public and accessible through the service container. By default, all Mautic services are public. Set this to FALSE to make the service private instead.

Mautic 服务标签

Mautic 使用以下标签来注册服务,具体说明如下。

通道标签

标签

支持的标签参数

描述

mautic.sms_transport

['integrationAlias' => 'Name to display in the UI for this transport.']

将此服务注册为短信传输。

mautic.sms_callback_handler

none

注册此服务以处理来自短信传输的 Webhook。

mautic.email_transport

用于配置与传输服务的身份验证所需的字段的键/值对。请参阅 components/emails:Email transports

将该服务注册为 电子邮件传输

mautic.email_stat_helper

none

将此服务注册为电子邮件图表的统计辅助程序。请参阅 components/emails:Email stat helpers

核心标签

标签

支持的标签参数

描述

mautic.permissions

none

将该服务注册为权限对象,必须扩展 \Mautic\CoreBundle\Security\Permissions\AbstractPermissions。请参阅 权限的工作方式。位于 ['services']['permissions'] 数组下的服务不需要此项。

集成标签

标签

支持的标签参数

描述

mautic.basic_integration

none

将该服务注册为 集成

mautic.builder_integration

none

将该服务注册为 构建器

mautic.authentication_integration

none

注册此服务以 与集成的服务进行身份验证

mautic.config_integration

none

注册此服务以 配置集成

mautic.sync_integration

none

注册此服务以 与集成的服务同步 Mautic 对象

mautic.sync.notification_handler

none

注册此服务以处理同步通知。

分类配置项

使用 categories 定义可供分类管理器使用的分类类型。请参阅 components/categories:Categories

 <?php
 // ...

'categories' => [
     'plugin:helloWorld' => 'mautic.helloworld.world.categories',
 ],

 // ...

参数配置项

配置可以通过 Mautic 的 CoreParameterHelper 类访问,也可以通过使用 %mautic.key% 传递给服务,或者从环境变量 MAUTIC_KEY 中读取。有关更多信息,请参阅 components/config:Configuration parameters

<?php

// ...

'parameters' => [
    'helloworld_api_enabled'      => false,
    'helloworld_supported_worlds' => ['earth', 'mars', 'jupiter',],
],

// ...

Note

默认值必须与值的类型匹配,以便 Mautic 可以正确地进行类型转换和转换。例如,如果不存在特定的默认值,则应为数组类型定义一个空数组 [];对于整数类型,定义为零 0;对于布尔类型,定义为 TRUEFALSE,依此类推。利用参数的服务应该接受并处理 NULL 值,但整数和字符串类型除外,0 除外。

Note

默认情况下,参数不暴露给用户界面。有关更多信息,请参阅 components/config:Configuration

自定义配置参数

您可以在插件中定义自定义配置参数,以支持可配置的功能,例如启用或禁用功能。

Mautic 插件允许您定义这些参数以便在插件的代码中使用。将这些参数存储在 config/local.php 文件中,并在插件自己的配置文件中定义它们的默认值,以确保稳定性和避免错误。

为了避免在缓存编译期间或直接从容器访问参数时出现错误(而没有检查其是否存在),始终在 Parameters config items 中定义自定义参数。这可确保参数存在并具有回退值。

要将这些配置选项添加到 Mautic 的配置部分,您需要:

  • 一个 event subscriber 用于注册配置。

  • 一个 Form type 用于定义字段。

  • 一个特定的视图用于渲染表单。

Note

要翻译插件在配置表单中的标签,请在插件的 messages.ini 文件中包含一个翻译键,例如 mautic.config.tab.helloworld_config。将 helloworld_config 替换为在事件订阅者中注册表单时使用的 formAlias

配置事件订阅器

这允许插件与 Mautic 的配置事件进行交互。它监听两个重要的事件:ConfigEvents::CONFIG_ON_GENERATEConfigEvents::CONFIG_PRE_SAVE

以下代码示例显示了插件如何构建其事件订阅器。

<?php

declare(strict_types=1);

namespace MauticPlugin\HelloWorldBundle\EventListener;
use Mautic\ConfigBundle\Event\ConfigEvent;
use Mautic\ConfigBundle\ConfigEvents;
use Mautic\ConfigBundle\Event\ConfigBuilderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

```markdown final class ConfigSubscriber extends EventSubscriberInterface

{
/**
  • @return mixed[]

*/

static public function getSubscribedEvents(): array {

return [

ConfigEvents::CONFIG_ON_GENERATE => [‘onConfigGenerate’, 0], ConfigEvents::CONFIG_PRE_SAVE => [‘onConfigSave’, 0]

];

}

public function onConfigGenerate(ConfigBuilderEvent $event): void {

$event->addForm(
[

‘formAlias’ => ‘helloworld_config’, ‘formTheme’ => ‘HelloWorldBundle:FormThemeConfig’, ‘parameters’ => $event->getParametersFromConfig(‘HelloWorldBundle’)

]

);

}

public function onConfigSave(ConfigEvent $event): void {

/** @var array $values */ $values = $event->getConfig(); // Manipulate the values if (!empty($values[‘helloworld_config’][‘custom_config_option’])) {

$values[‘helloworld_config’][‘custom_config_option’] = htmlspecialchars($values[‘helloworld_config’][‘custom_config_option’]);

} // Set updated values $event->setConfig($values);

}

}

Subscribed events

The event subscriber listens to the following events:

  • ConfigEvents::CONFIG_ON_GENERATE: Mautic dispatches this event when it builds the configuration form. This allows the Plugin to inject its own tab and configuration options.

  • ConfigEvents::CONFIG_PRE_SAVE: Mautic triggers this event before it renders the form values and saves them to the local.php file. This allows the Plugin to clean up or modify the data before writing it to local.php.

Generate Plugin configuration

To register Plugin’s configuration details during the ConfigEvents::CONFIG_ON_GENERATE event, call the addForm() method on the ConfigBuilderEvent object. The method expects an array with the following elements:

Key

Description

formAlias

The alias of the form type class that defines the expected form elements.

formTheme

The view that formats the configuration form elements, for example, HelloWorldBundle:FormTheme\Config.

parameters

An array of custom configuration elements. Use $event->getParametersFromConfig('HelloWorldBundle') to retrieve them from the plugin’s configuration file.

Modify configuration before saving

To modify the form data before saving, use the ConfigEvents::CONFIG_PRE_SAVE event. This event is triggered just before values are saved to the local.php file, allowing the Plugin to adjust them.

Register the event subscriber

```

通过在 services[events] 中配置插件来注册订阅者(参见 Service config items)。这确保了插件能够监听事件并做出相应的反应。

表单类型

表单类型用于生成主配置表单中的字段。有关使用表单类型的更多信息,请参阅 Forms documentation

请记住,表单类型必须通过在 services[forms] 中配置插件来注册(参见 Service config items)。

以下是一个表单类型类的示例,它向插件的配置表单添加了一个自定义配置选项。

<?php
// plugins/HelloWorldBundle/Form/Type/ConfigType.php

namespace MauticPlugin\HelloWorldBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

final class ConfigType extends AbstractType
{
    /**
     * @param mixed[] $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add(
            'custom_config_option',
            'text',
            [
                'label' => 'plugin.helloworld.config.custom_config_option',
                'data'  => $options['data']['custom_config_option'],
                'attr'  => [
                    'tooltip' => 'plugin.helloworld.config.custom_config_option_tooltip'
                ]
            ]
        );
    }
}

配置模板

在事件监听器中注册表单主题为 HelloWorldBundle:FormTheme\Config,告诉 ConfigBundle 在 HelloWorldBundle 的 Resources/views/FormTheme/Config 文件夹中查找模板。具体来说,它将查找一个名为 _config_{formAlias}_widget.html.twig 的模板,其中 {formAlias} 与在插件的 ConfigEvents::CONFIG_ON_GENERATE 事件监听器中设置的 formAlias 相同。

该模板应采用面板格式,以匹配配置界面的其余部分。

以下是一个示例,说明模板应该如何组织:

{# plugins/HelloWorldBundle/Views/FormTheme/Config/_config_helloworld_config_widget.html.twig #}
<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">{{ 'mautic.config.tab.helloworld_config'|trans }}</h3>
    </div>
    <div class="panel-body">
        {% for field in form.children %}
            <div class="row">
                <div class="col-md-6">
                    {{ form_row(field) }}
                </div>
            </div>
        {% endfor %}
    </div>
</div