DEV Community

youssef ACHCHIRAJ
youssef ACHCHIRAJ

Posted on

Service Container and DI for wordpress plugins

As a WordPress plugin developer, I kept hitting the same problem:
every new plugin starts procedural, globals creep in, testing becomes painful, and refactoring later is expensive.

I didn’t want to rebuild a service container + dependency injection setup every time, so I did two things:

  • extracted a lightweight PSR-4 service container into a Composer package

  • built a small WordPress plugin starter kit around it (service providers, bootstrapping, sane structure)

Result: I save ~1–2 days every time I start a new plugin, and the code base stays maintainable and testable from day one.**

Features:

  • PSR-4 autoloading
  • automatic dependency resolution
  • singleton & closure bindings
  • service provider pattern
  • circular dependency detection
  • container injection explicitly forbidden by default

Example:

// in PluginServiceProvider.php
public function register(Container $container) {
  $container->bind(LoggerInterface::class, Logger::class);
}

$logger = $container->get(LoggerInterface::class);

// Alternative method
$logger = $container->resolve(LoggerInterface::class);

// The container automatically resolves dependencies
class UserController {
    public function __construct(
        private LoggerInterface $logger,
        private DatabaseService $db
    ) {}
}


// All dependencies are automatically injected
$controller = $container->get(UserController::class);
Enter fullscreen mode Exit fullscreen mode

Links

Repositories:

Documentation: https://achchiraj.dev/plugins/sefra-starter

I’m sharing this in case it’s useful to other WordPress devs who want a cleaner architecture.
Feedback welcome, especially from people who’ve tried similar approaches in WP

Top comments (0)