Back to Portfolio

How to use the Sefra Container Package in Your Existing WordPress Plugin

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.

Step 1: Install the Sefra Container Package

Use Composer to install the Sefra Container package in your plugin directory:

$ composer require sefra/container

if you don't have composer.json file yet

Setup Autoloading

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 ...

Then proceed to install the Sefra Container package as shown above.

Make a Plugin Class

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 } }

Step 2: Set Up the Plugin Service Provider

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 } }

Step 3: Register the Service Provider in Your Plugin

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**.**