PHP code example of phpatom / di

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.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpatom / di example snippets


use Atom\DI\Container;

$container = new Container();

use Atom\DI\Definition;
use Atom\DI\Definition;

lic readonly string $name)
    {
    }
}

class UserRepository
{
    public function __construct(private User $user)
    {

    }
    public function getUser(): User
    {
        return $this->user;
    }

}

class AuthService
{
    public function __construct(private UserRepository $userRepository)
    {
    }

    public function getUser(): User
    {
        return $this->userRepository->getUser();
    }

}

class Controller
{

    public function index(AuthService $authService): void
    {
        echo sprintf("Hello %s\n", $authService->getUser()->name);
    }

}

use Atom\DI\Container;

$container = new Container();

$definition = $container->bind(AuthService::class)
    ->toNewInstance()
    ->withClass(
        UserRepository::class,
        Definition::newInstanceOf(UserRepository::class)
            ->withParameter('user', new User(name: "daniel"))
    );


// output: hello daniel
$container->callMethod(Controller::class, 'index');

use Atom\DI\Container;
use Atom\DI\Definition;


class UserFactory
{
    public function __construct(
        private int $previousId = 0
    ) {
    }

    public function makeUser(): 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);

use Atom\DI\Container;
use Atom\DI\Definition;

$container = new Container();

$container->bind('foo', "bar");
//or
$container->bind('daniel')
    ->toValue(new User(name: "Nghokeng Daniel", id: 28));

//output: bar
echo $container->get('foo'), "\n";

use Atom\DI\Container;
use Atom\DI\Definition;

$container = new Container();
function makeDaniel()
{
    return new User("daniel", 28);
}

$container['foo'] = "bar";
$container['daniel'] = Definition::callTo("makeDaniel")
    ->function();

//output: bar
echo $container['foo'], "\n";
//output: daniel
echo $container['daniel']->name, "\n";