PHP code example of gdetassigny / simple-container
1. Go to this page and download the library: Download gdetassigny/simple-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/ */
gdetassigny / simple-container example snippets
use GabrielDeTassigny\SimpleContainer\ContainerProvider;
$container = (new ContainerProvider())->getContainer();
$container->get(Foo\Bar::class); // returns an instance of Foo\Bar
$container = (new ContainerProvider())->getContainer();
class NoConstructor {}
$container->get(NoConstructor::class);
class ConstructorNoParam {
public function __construct() {}
}
$container->get(ConstructorNoParam::class);
class ConstructorWithClassParam {
public function __construct(stdClass $param) {}
}
// Note: $param will be also instantiate and injected in the constructor
$container->get(ConstructorWithClassParam::class);
class ConstructorWithDefaultParam {
public function __construct(?string $test = null) {}
}
// Note: parameters with default values will be set to these values when autowired
$container->get(ConstructorWithDefaultParam::class);
$container = (new ContainerProvider())->getContainer();
class ConstructorWithPrimitiveParam {
public function __construct(string $test) {}
}
// Fails! Autowiring cannot figure out the value of the $test parameter.
// Consider using a service provider
$container->get(ConstructorWithPrimitiveParam::class);
interface FooInterface {}
class Bar implements FooInterface {}
// Fails! Autowiring does not know which concrete class you want
// Consider using either a YAML Config or a service provider
$container->get(FooInterface::class);
use GabrielDeTassigny\SimpleContainer\ContainerProvider;
$container = (new ContainerProvider('/path/to/config.yaml'))->getContainer();
$container->get(Foo\BarInterface::class); // returns an instance of Foo\Bar
$container->get('some-id'); // returns an instance of Foo\Baz
use GabrielDeTassigny\SimpleContainer\ServiceProvider;
use GabrielDeTassigny\SimpleContainer\ContainerProvider;
class FooServiceProvider implements ServiceProvider
{
public function getService(): object
{
return new Foo('some-string');
}
}
$containerProvider = new ContainerProvider();
$containerProvider->registerService(Foo::class, new FooServiceProvider());
$container = $containerProvider->getContainer();
$container->get(Foo::class); // returns the instance of Foo defined in FooServiceProvider
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.