---
title: "Festi Plugin Architecture"
url: https://festi.dev/8.0/Core/Plugins/
---

# Festi Plugin Architecture

Any system written on Festi Framework contains a variety of plugins.
A plugin contains the business logic.

## Plugin Structure

Plugins are located in the `plugins` folder by default.
There are two ways to create a plugin.

The first way is to simply create a file in the `plugins` folder with a class describing the plugin.
Each plugin class has a mandatory suffix in its name, by default `Plugin`,
but the suffix can be overridden, and it must inherit from `AbstractPlugin`, `ApiPlugin`, `ObjectPlugin`, `DisplayPlugin`.
It is recommended to use `DisplayPlugin`.

The simplified form of a plugin will look like this:

`plugins/MyPlugin.php`:

```php
class MyPlugin extends DisplayPlugin
{
}
```

The second, more commonly used way is to create a full plugin.
It is created in a folder that corresponds to the plugin name without the postfix.
In this folder, a class is created as in the simplified version.
Here is how the structure usually looks:

```
My/
|-- Domain/
|   |-- Model/
|   |-- Service/
|-- static/
|-- templates/
|-- MyPlugin.php *
|-- MyObject.php
|-- init.php
```

Put the JS, CSS, and image files of the plugin in the `static` folder. See [Static files](https://festi.dev/8.0/Frontend/StaticFiles/index.md).

Put the templates of the plugin in the `templates` folder. When the plugin renders a template, the framework looks for the file in this order:

1. the `templates` folder of the plugin
2. the `templates` folder of the project
3. the `templates` folder of the theme

See [Templates](https://festi.dev/8.0/Core/Templates/index.md) for the full rules. In the `Domain` folder you can put logic that you move out of the plugin class.

`MyObject.php` is an object (DataAccessObject) for working with the database, which you can read about in another section.
Only plugin should have access to his object.

To connect JS and CSS, use the `includeStatic` method inside a display (routing) method. **Always include assets in the plugin URL handler method, not in `.phtml` templates.** Move asset inclusion out of templates into the controller.

```php
class MyPlugin extends DisplayPlugin
{
    public function onDisplayDefault(Response &$response)
    {
        // Paths are relative to the `static` folder of the plugin
        $this->includeStatic('js/test.js');
        $this->includeStatic('css/test.css');
        ...
    }
}
```

## init.php

`init.php` is an optional file, but if you put it in the plugin folder,
it will be called when the `Core` is initialized in the system.
Formally, this file should be used to initialize some actions for the correct operation of the plugin.
For example, if your plugin depends on events of another plugin or you need to make sure that the system is configured correctly for the plugin to work.

This file is in the `Core` scope, meaning that if you call `$this` inside the file, you will get access to the `Core` instance.

**Avoid calling `getPluginInstance()` (or other lifecycle-sensitive APIs) at the top level of `init.php`.** Doing so runs during Core/plugin initialization and can break the component lifecycle (e.g. cause crashes or undefined order of initialization). Instead, subscribe to an event that runs after init (e.g. `Core::EVENT_ON_AFTER_INIT`) and obtain the plugin instance inside that listener when you actually need it.

**Recommended** — register listeners after init:

```php
$this->addEventListener(Core::EVENT_ON_AFTER_INIT,
    function (FestiEvent &$event) {
        $plugin = Core::getInstance()->getPluginInstance(MyPlugin::class);
        $this->addEventListener(
            Store::EVENT_STORE_INIT,
            function (FestiEvent &$event) use ($plugin) {
                // ...
            }
        );
    }
);
```

**Avoid** — top-level plugin access in `init.php`:

```php
$plugin = $this->getPluginInstance("Jimbo");  // bad: runs during init, breaks lifecycle
```

## Accessing Plugin Instances

There are several ways to get an instance of a plugin:

1.  Get it through the `Core`:

    ```php
    $plugin = Core::getInstance()->getPluginInstance("My");
    // or
    $plugin = Core::getInstance()->getPluginInstance(MyPlugin::class);
    ```

    From a plugin's `init.php`, do not call `getPluginInstance` at top level; use a `Core::EVENT_ON_AFTER_INIT` listener instead (see [init.php](#initphp) above).

2.  If you need to get an instance of a plugin from another plugin, you can use `$this->plugin`:

    ```
    $this->plugin->my->getValues();
    $plugin = $this->plugin->my;
    ```

You cannot create an instance of a plugin manually through the constructor!


## Types of Plugins

Festi Framework supports three types of plugins. Each type has its own purpose depending on how and where the plugin will be used.

### Project Plugin

A regular plugin that contains business logic for a specific project. It is created inside the plugins/ folder and usually follows the standard plugin structure.

- Used only within the current project
- Can be a single file or a full folder structure
- Does not require Composer or a separate repository

### System Plugin

Every project should have one system plugin,
which differs from the ordinary one in that it should implement additional logic
and define a set of rules in the system, such as:

* getting system settings;
* handling system installation and update;
* defining routing rules;
* defining response serialization rules;
* etc.

The system plugin should be implemented from the `ISystemPlugin` interface and
its database object from the `ISystemObject` interface.

In most cases, the `Jimbo` plugin is used for web projects.

And most importantly, the system plugin must be explicitly specified in the `Core`:

```php
$core = Core::getInstance();

$systemPlugin = $core->getPluginInstance('Jimbo');
$core->setSystemPlugin($systemPlugin);
$systemPlugin->bindRequest();
```

The `bindRequest` method is the entry point for request processing in any system,
but only if you use Festi Framework as the main tool, not as a supporting one.

### Cross-Project Plugin

A plugin designed to be reused across multiple projects. It is developed in a separate repository and installed via Composer.

- Must follow PSR-4 autoloading
- Includes composer.json and unit tests
- Uses namespaced classes, typically starting with `Plugins\`
- Can be versioned and distributed as a package

## Plugin Metadata Annotations

Every cross-project plugin class docblock **must** include metadata annotations describing the plugin name, source repository, and dependencies:

```php
/**
 * Plugin description
 *
 * @pluginName PluginName
 * @pluginUrl UrlToPluginSite
 * @pluginSource UrlToPluginSource
 * @pluginDependency DependencyPluginName <DependencyPluginSource>
 */
class PluginNamePlugin extends ObjectPlugin
{
}
```

For project-level plugins, annotations are optional but recommended.

## Plugin Namespace Conventions

Namespaces help organize plugin code and avoid class name conflicts. Festi Framework supports both namespaced and non-namespaced plugins for backward compatibility, but using namespaces is strongly recommended for all new development.

```php
namespace Plugins\My;

class MyPlugin extends \AbstractPlugin
{
    // Your plugin logic
}
```

- The namespace must begin with `Plugins\`, which reflects the standard plugin folder `plugins/`.
- The second segment (`My`) matches your plugin's directory name.
- This structure aligns with modern PHP practices and supports PSR-4 autoloading.

## Method Naming Conventions for the RoutingMethod

Routing method naming rules are defined by system plugins and can be overridden or extended by any system plugin.
A system plugin is responsible for deciding which plugin methods should be treated as routing endpoints and how those methods are detected.
This allows the routing mechanism to remain flexible and customizable at the system level.

Each system plugin may introduce its own rules for identifying `RoutingMethods`.
These rules are usually based on method name prefixes, but the framework does not enforce a fixed convention.
Instead, the active system plugin determines how routing methods are discovered and processed.

By default, the `Jimbo` system plugin defines routing methods using method name prefixes.
Any plugin method whose name starts with one of the supported prefixes is treated as a routing endpoint and participates in the routing process.

Currently, `Jimbo` recognizes the following prefixes:

```
onDisplay*
onUpdate*
doAjaxResponse*
onAjax*
doJsonResponse*
onJson*
```

When a request is routed to a method identified as a `RoutingMethod`, an instance of the `Response` object is automatically passed as the first parameter.
The `Response` is preconfigured according to the routing type defined by the system plugin, including response handling and serialization behavior.
This design allows different system plugins to fully control routing conventions while keeping plugin implementations simple and consistent.
For more information, see [Response](https://festi.dev/8.0/Core/Response/index.md) and [Routing Requests](https://festi.dev/8.0/Core/UrlRouters/index.md).

## Business Logic / UI Separation

Split business logic from UI response handling. URL handler (routing) methods should be thin — set response type, call a business logic method, and format the response. Extract validation, persistence, and queue logic into separate `protected` methods for testability:

```php
// Good — thin handler delegates to business logic method
public function onAjaxSendContactForm(Response &$response)
{
    $response->setType(Response::JSON);

    $result = $this->doSendContactForm($_POST);

    if ($result->hasErrors()) {
        $response->setStatus(Response::STATUS_UNPROCESSABLE_ENTITY);
        $response->errors = $result->getErrors();
        return true;
    }

    $response->addNotification(__('Message sent.'));
    $response->setAction(Response::ACTION_RELOAD);
    return true;
}

// Business logic method — testable, no Response dependency
protected function doSendContactForm(array $formData): Result
{
    // validation, persistence, queue logic
    ...
}
```

## URL Resolution

Always resolve URLs through the framework helper `$this->getUrl()`. Never hardcode URLs as plain strings in templates or code:

```php
// Bad
$url = '/contact/send/';

// Good
$url = $this->getUrl('/contact/send/');
```

## Annotations for Plugin Methods

Methods in plugins have a number of additional annotations that make it easier to use the system and hide some of the system logic.
Here is an example of all the annotations that the system supports:

```php
/**
 * Plugin description
 *
 * @pluginName PluginName
 * @pluginUrl UrlToPluginSite
 * @pluginSource UrlToPluginSource
 * @pluginDependency DependencyPluginName <DependencyPluginSource>
 * @pluginDependency DependencyPluginName2 <DependencyPluginSource2>
 * @pluginVersion rc1.1
 */
class YourPlugin extends ObjectPlugin
{
    /**
     * @urlRule ~/test/([0-9])/~
     * @section sectionName|sectionMask
     * @area default
     * @userType admin
     * @interceptor ClassName
     * @listener PluginName::methodName
     * @prepare PluginName::methodName
     */
    public function method($param)
    {
    }

    /**
     * @event Store::EVENT_BEFORE_INSERT
     */
    public function onCreateNewItem(FestiEvent &$event)
    {

    }
}
```

- `urlRule` - describes the regular expression for which URL this method will be called.

- `section` - the name of the section in which the permissions are defined for who can call this method.

- `area` - from which zone this method can be called. sectionMask = (read|write|exec)

- `userType` - which type of user can call this method, userType is related to section.

- `interceptor` - the name of the interceptor class that will be called before and after calling this method.

- `listener` - specifies the callback method that should be called after the current method is executed.

- `prepare` - specifies the callback method that should be called before the current method is executed.

It is important to note that these annotations do not work "on the fly". If you have defined them for a method,
you need to either run a full plugin install (e.g. via Jimbo's installation flow) or add/update the plugin at **Plugins** (`/festi/festi_plugins/Jimbo/`). Adding or saving a plugin there triggers the install for that plugin and syncs annotations.
The framework's `Workbench` uses `PluginAnnotations` and `PluginContext` (see [Plugin Annotations & Context](https://festi.dev/8.0/Core/Plugins/PluginAnnotations/index.md)) to parse docblocks and sync `@area`, `@urlRule`, `@section` into the system plugin's object.

## Project Settings for Configurable Text

Project-specific text (intro messages, success messages, labels) should be stored in Project Settings, not hardcoded. Use `hasSetting()` / `getSetting()` to retrieve configurable values:

```php
$intro = '';
if ($this->hasSetting('contact_us_intro')) {
    $intro = $this->getSetting('contact_us_intro');
}
```

## Plugin Lifecycle

1. Plugin initialization occurs on the first call to the `getPluginInstance` method in the `Core`.
2. When the plugin is initialized, the `onInit` method is always called in it.
If you need to add logic for the plugin during initialization, do not use the constructor,
but use the overload of the `onInit` method.g
    ```
    class YourPlugin extends DisplayPlugin
    {
        public function onInit()
        {
            parent::onInit();

            // Your code
        }
    }
    ```

3. The plugin object instance lives as a singleton and each of your calls corresponds to the same plugin object instance,
regardless of whether you called it through a `Core` or through the plugin object itself.

## Unit Tests

If you are developing a system or a plugin that will be used in different projects and has a separate repository,
then you need to create a "tests" folder for it and add tests for its functionality.

> Tests for the plugin are run only with the main project.

1. Add to bootstrap.php:

```php
require_once 'tests/FestiTestCase.php';
require_once 'test/PluginTestCase.php';
require_once 'tests/TestUtils.php';

...

TestUtils::execPlugins();
```

2. Add at least one class with tests `[PLUGIN_NAME]PluginTest.php`:

```php

class [PLUGIN_NAME]PluginTest extends PluginTestCase
{
    public function testLogic()
    {
        ...
    }
}

```


## Usage Examples

### Calling a plugin method with passing parameters by reference

For example, we have a method in the `Test` plugin:

```php
public function onModuleConfig(&$groups)
{
    ...
}
```

And if we make a call from another plugin:

```php
$this->plugin->$pluginName->onModuleConfig($groups);
```

then `$groups` will be passed by reference, and if changes are made to `$groups` in
`onModuleConfig`, they will be applied.

## Plugin README Conventions

Every cross-project plugin must include a `README.md`. Follow these conventions:

- Use "Project Settings" (not "festi_settings") in user-facing documentation
- Use `./vendor/bin/festi-dgs-exec` for settings configuration examples, not raw SQL
- Link dependency plugins to their GitLab URLs

## Create Cross-Project Plugin

Festi Framework supports two main approaches for plugin development: Project-Level Plugins and Cross-Project Plugins. Both share the same core architecture and conventions, such as class naming, inheritance, and method prefixes. Project-Level Plugins are built directly inside the project and are ideal for quick or localized features. Cross-Project Plugins are designed for reuse across multiple systems. They are typically maintained in separate repositories, include a composer.json file for dependency management, and come with unit tests to ensure long-term stability and maintainability.

1. Create a repository for your plugin
2. Create a composer.json file in the root of your plugin repository
    ```json
    {
      "name": "festi-team/my-plugin",
      "version": "dev-develop",
      "minimum-stability": "dev",
      "repositories": [
        {
          "type": "composer",
          "url": "https://packages.festi.io/"
        }
      ],
      "require": {
        "php": ">=8.1",
        "festi-team/festi-framework-core": "dev-develop",
        "festi-team/festi-framework-theme": "dev-develop"
      },
      "require-dev": {
        "phpunit/phpunit": "9.6.8",
        "phpunit/php-code-coverage": ">=8.0.2",
        "phpunit/phpcov": ">=8.2.0",
        "phan/phan": ">=5.3.0",
        "squizlabs/php_codesniffer": "3.*"
      },
      "autoload": {
        "psr-4": {
          "Plugins\\My\\": "./"
        },
        "exclude-from-classmap": [
          "tests/"
        ]
      },
      "autoload-dev": {
        "psr-4": {
          "": [
            "tests"
          ]
        },
        "classmap": [
          "vendor/festi-team/festi-framework-core/tests/FestiTestCase.php",
          "vendor/festi-team/festi-framework-core/tests/PluginTestCase.php"
        ]
      }
    }
    ```
3. Create a plugin class in the root of your plugin repository
    `MyPlugin.php`:
    ```php

    namespace Plugins\My;


    class MyPlugin extends DisplayPlugin
    {

    }
    ```
4. Create README.md file in the root of your plugin repository to describe your plugin.
5. Create .gitignore file in the root of your plugin repository to exclude unnecessary files
    ```
    /vendor
    /tests/reports
    .DS_Store
    ```
6. Run `composer install` to install dependencies
7. Create folder `tests` and `tests\Plugin` in the root of your plugin repository. Also create `phpunit.xml`, `bootstrap.php`:
    ```xml
     <?xml version="1.0" encoding="UTF-8"?>
    <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" bootstrap="./bootstrap.php" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" forceCoversAnnotation="false" verbose="true" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
        <coverage>
            <include>
                <directory suffix=".php">../</directory>
            </include>
            <exclude>
                <directory>../tests/</directory>
                <directory>../templates/</directory>
                <directory>../vendor/</directory>
            </exclude>
            <report>
                <clover outputFile="./reports/phpunit.coverage.xml"/>
            </report>
        </coverage>
        <testsuites>
            <testsuite name="Main">
                <directory>./Plugin/</directory>
            </testsuite>
        </testsuites>
        <logging>
            <junit outputFile="./reports/phpunit.xml"/>
        </logging>
    </phpunit>
    ```
8. Create a test class in the `tests/Plugin` folder
    `MyPluginTest.php`:
    ```php
    <?php

    namespace Plugins\My\Tests\Plugin;

    use PluginTestCase;

    class MyPluginTest extends extends PluginTestCase
    {
        protected MyPlugin $myPlugin;

        public function setUp(): void
        {
            parent::setUp();

            $this->myPlugin = $this->core->getPluginInstance(MCPServerPlugin::class);
        }

        public function testBasicFunctionality(): void
        {
            $this->assertInstanceOf(MCPServerPlugin::class, $this->myPlugin);
        }
    }
    ```
9. Run tests with `cd tests && ../vendor/bin/phpunit`

> Important: Cross-Project Plugins must be developed with universal compatibility in mind and unit tests should be written to ensure that the plugin works correctly in different environments.
