1. Go to this page and download the library: Download fkeloks/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/ */
fkeloks / simple-container example snippets
$configuration = [
FakeClassA::class => FakeClassA::class,
FakeClassB::class => FakeClassA::class,
'FakeC' => FakeClassC::class,
'FakeD' => [
'class' => FakeClassD::class,
'params' => ['A', 'B']
]
]
/*
* get(FakeClassA::class) will return FakeClassA class
* |-> But this statement is useless, the container will understand automatically.
*
* get(FakeClassB::class) will return FakeClassA class
* |-> Because the configuration overrides the name of the class.
*
* get('FakeC') will return FakeClassC class
*
* get('FakeD') will return FakeClassD class withs constructor parameters 'A' and 'B'
*/
use SimpleContainer\ContainerBuilder;
ContainerBuilder::build($configuration);
$container = ContainerBuilder::getContainer();
use SimpleContainer\ContainerBuilder;
// Short syntax
$container = ContainerBuilder::build($configuration)::getContainer();
use SimpleContainer\ContainerBuilder;
$container = ContainerBuilder::getContainer();
// The container will be configured with the previous `ContainerBuilder::build()`
class Hello() {
private $name;
private $pseudo;
public function __construct($name, $pseudo) {
$this->name = $name;
$this->pseudo = $pseudo;
}
public function sayHello() {
return "Hello {$this->pseudo} ({$this->name}) !";
}
}
SimpleContainer\ContainerBuilder::build([
'helloClass' => [
'class' => Hello::class,
'params' => ['James', 'Jojo']
]
])
$container = SimpleContainer\ContainerBuilder::getContainer();
$helloClass = $container->get('helloClass');
echo $helloClass->sayHello();
/*
* The result will be: "Hello Jojo (James) !"
*/
SimpleContainer\ContainerBuilder::build([
'classA' => ClassA::class
])
$container = SimpleContainer\ContainerBuilder::getContainer();
$classA = $container->get('classA'); // A new instance of ClassA is generated
$classA = $container->get('classA'); // Class A has been cached, so the same instance is returned
$classA = $container->make('classA');
// |-> The make function does not take the cache into account, so a new instance of A is generated