wp-starter/container
Lightweight dependency injection container for PHP. Provides simple service binding and resolution to help structure applications and manage dependencies cleanly, suitable for small projects and framework-agnostic setups.
Installation
composer require wp-starter/container
Add the service provider to config/app.php under providers:
WpStarter\Container\ContainerServiceProvider::class,
Basic Usage
Register a container binding in a service provider (e.g., AppServiceProvider):
use WpStarter\Container\Container;
public function register()
{
Container::bind('my.service', function () {
return new MyService();
});
}
First Use Case Resolve the binding in a controller or anywhere else:
$service = Container::resolve('my.service');
Container::bind('App\Contracts\MyInterface', 'App\Services\MyService');
Container::singleton('cache', Cache::class); // Singleton
Container::transient('logger', Logger::class); // New instance per resolve
Replace Laravel’s Container (Advanced)
Override Laravel’s container in AppServiceProvider:
$this->app->singleton('container', function () {
return new WpStarter\Container\Container();
});
(Use cautiously—test thoroughly!)
Contextual Bindings Bind services dynamically based on context (e.g., request):
Container::bindWhen('user.repository', function ($app) {
return new UserRepository($app['request']->user());
}, function ($needs) {
return isset($needs['user']);
});
Container::bind('wp.db', function () {
global $wpdb;
return $wpdb;
});
RuntimeException on circular dependencies. Refactor to break cycles.Container::resolve('unbound.service') throws BindingResolutionException. Use Container::bound() to check:
if (Container::bound('service')) { ... }
dd(Container::getBindings());
Container::rebind() instead of bind() to replace existing bindings:
Container::rebind('service', NewService::class);
WpStarter\Container\Contracts\Resolver:
Container::extend('custom.resolver', function ($concrete) {
return new CustomResolver($concrete);
});
bindIf() to conditionally register bindings:
Container::bindIf('debug.logger', DebugLogger::class, function () {
return app()->environment('local');
});
Container::make() in queues with caution.How can I help you explore Laravel packages today?