1. Go to this page and download the library: Download peroxide/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/ */
peroxide / container example snippets
# From PSR-11
public function get(string $id): object;
public function has(string $id): bool;
# From our interface SetDependency
public function set(string $id, callable $factory): void;
public function setInvokableClass(string $id, string $invocableClass): void;
use Peroxide\DependencyInjection\Container;
$config = [
YourDependencyName::class => fn() => new YourDependencyName(),
YourDependency::class => YourDependencyFactoryClass::class,
// should be invokable class
ConcreteClass::class => new ConcreteClassFactory(),
// Or passing as reference string
ConcreteClass::class => ConcreteClassFactory::class
];
$container = new Container($config);
// how to get dependencies
$container->get(YourDependencyName::class);
$container->get(YourDependency::class);
$container->get(ConcreteClass::class);
use Psr\Container\ContainerInterface;
use Peroxide\DependencyInjection\Interfaces\ContainerFactory;
class ConcreteClassFactory implements ContainerFactory
{
public function __invoke(ContainerInterface $container): ConcreteClass
{
// config your dependency injection here
// you can compose your dependency
// return new ParentDependency($container->get(DependencyChild::class));
return new ConcreteClass();
}
}
use Peroxide\DependencyInjection\Container;
$container = new Container();
$container->set(DependencyPath::class, fn() => new DependencyInstance());
$container = new Container([
// Dependency parent with dependency child
// all dependencies should be involved by a Closure(function() or fn())
Dependency::class => fn() => new Dependency(),
ComponentThatHasAnotherDependency::class => function($container) {
return new ComponentThatHasAnotherDependency(
$container->get(Dependency::class)
);
},
// or simply
ComponentThatHasAnotherDependency::class => fn($c) => new ComponentThatHasAnotherDependency($c->get(Dependency::class)),
// more complex injections
ComponentThatHasTwoDeps::class => fn($c) => new ComponentThatHasTwoDeps(
$c->get(Dependency::class),
$c->get(AnotherDependency::class),
)
]);
use Peroxide\DependencyInjection\Container;
use Peroxide\DependencyInjection\Invokables\Singleton;
$container = new Container([
// Dependency parent with dependency child
Dependency::class => new Singleton(fn() => new Dependency()),
ParentDependency::class => new Singleton(
fn($container) => new ParentDependency($container->get(Dependency::class))
),
// Singleton passing factory as reference string
ConcreteClass::class => new Singleton(ConcreteClassFactory::class)
]);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.