The Sefra Container package provides a powerful and flexible service container for managing dependencies in your WordPress plugins. This guide will walk you through the steps to integrate the Sefra Container into your existing WordPress plugin.
Use Composer to install the Sefra Container package in your plugin directory:
$ composer require sefra/container
First of all, your plugin should be using Composer's autoloading. If you haven't set it up yet, run composer init in your plugin directory and follow the prompts to create a composer.json file. Then, run:
$ composer dump-autoload
and require the autoloader in your main plugin file:
1
2
3
4
// In your-plugin-main-file.php
// code...
$ require_once __DIR__ . '/vendor/autoload.php';
// code ...
Create a main plugin class in src/Plugin.php to bootstrap your plugin:
src/Plugin.php
1
2
3
4
5
6
7
8
9
<?php
namespace YourVendor;
class Plugin
{
public function boot(): void
{
// Plugin boot logic here
}
}Create a service provider class to register your services. This class should implement the ServiceProvider interface provided by the Sefra Container package.
src/Providers/PluginServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
namespace YourVendorProviders;
use SefraContainer;
use SefraProvidersServiceProvider;
class PluginServiceProvider implements ServiceProvider
{
public function register(Container $container): void
{
// Register your services here
}
public function boot(Container $container): void
{
// Boot logic can be added here if needed
}
}In your main plugin file, register the service provider and initialize the container.
your-plugin-main-file.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
/**
* Plugin Name: Your Plugin Name
* Description: A description of your plugin.
* Version: 1.0.0
* @package your-plugin
*/
if( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
use YourVendorProvidersPluginServiceProvider;
use SefraContainer;
use SefraProvidersApp;
use YourVendorPlugin;
require_once __DIR__ . '/vendor/autoload.php';
App::registerProviders($providers = [
PluginServiceProvider::class,
]);
Container::getInstance()->resolve(Plugin::class)->boot();
now your plugin is set up to use the Sefra Container for dependency management. You can now register and resolve services using the container in your service provider and plugin classes**.**