1. Go to this page and download the library: Download marcosdipaolo/container library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
class UserRepository
{
public function __construct(private DatabaseConnection $db) {}
}
class UserService
{
public function __construct(private UserRepository $repo) {}
}
// No registration needed!
$userService = $container->get(UserService::class);
// All dependencies are automatically injected
$container->factory('config', function(Container $container) {
return new Config(getenv('CONFIG_PATH'));
});
// Created fresh every time via the factory function
$config = $container->get('config');
if ($container->has('config')) {
$config = $container->get('config');
}
$service = $container->resolve(MyService::class);
// All constructor dependencies are wired automatically
$container->clearSingletons();
// Next get() will create fresh instances
$container->clearReflectionCache();
class Service
{
public function __construct($dependency) {} // No type hint!
}
$container->get(Service::class);
// ContainerException: Cannot resolve "Service" - constructor parameter
// "dependency" is missing a type hint. Add a type declaration or use
// a factory function for explicit wiring.
class Service
{
public function __construct(TypeA|TypeB $dependency) {}
}
$container->get(Service::class);
// ContainerException: Cannot resolve "Service" - constructor parameter
// "dependency" has a union type. Union types are ambiguous for automatic
// resolution. Use a factory function instead.
class ServiceA { public function __construct(ServiceB $b) {} }
class ServiceB { public function __construct(ServiceA $a) {} }
$container->get(ServiceA::class);
// CircularDependencyException: Circular dependency detected:
// ServiceA -> ServiceB -> ServiceA
class Service
{
public function __construct(string $name) {} // No default value
}
$container->get(Service::class);
// ContainerException: Cannot resolve "Service" - constructor parameter
// "name" is a builtin type with no default value. Use a factory function
// for custom wiring.
// Good - database connection created once
$container->singleton(PDOConnection::class, function($c) {
return new PDO('mysql:host=localhost', 'user', 'pass');
});
// Poor - creates new connection for every request
$container->transient(PDOConnection::class, PDOConnection::class);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.