1. Go to this page and download the library: Download phpatom/di library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?phprequire_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
phpatom / di example snippets
useAtom\DI\Container;
$container = new Container();
useAtom\DI\Container;
useAtom\DI\Definition;
classUserFactory{
publicfunction__construct(
private int $previousId = 0
){
}
publicfunctionmakeUser(): User{
$user = new User(
sprintf("User #%d", $this->previousId),
id: $this->previousId,
);
$this->previousId++;
return $user;
}
}
/**
* the definition is either a prototype or a singleton, singleton is the default
*/
$container->bind(UserFactory::class)->singleton();
// output: hello daniel
$container->bind(
User::class,
Definition::callTo("makeUser")
->method()
->on(Definition::get(UserFactory::class))
)
->prototype(); // without this, the instance will be cached// output: int(0)
var_dump($container->get(User::class)->id);
// output: int(1)
var_dump($container->get(User::class)->id);