PHP code example of neat / service

1. Go to this page and download the library: Download neat/service 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/ */

    

neat / service example snippets




// First whip up a new container
$container = new Neat\Service\Container();

// Then teach it how to create a service
$container->set(PDO::class, function () {
    return new PDO('sqlite:memory');
});

// And retrieve it using has and get methods
if ($container->has(PDO::class)) {
    $pdo = $container->get(PDO::class);
}



/** @var Neat\Service\Container $container */

// Suppose we want to access the Neat\Database\Connection service by an alias
$container->alias(PDO::class, 'db');

// Now we can access a service by its db alias
$container->set('db', function() {
    return new PDO('sqlite:memory');
});

$db = $container->get('db');



/** @var Neat\Service\Container $container */

class Services
{
    public function now(): DateTime
    {
        return new DateTime('now');
    }

    // Notice how this depends on the service above, the container will
    // automatically resolve this dependency for us.
    public function clock(DateTime $time): Example\Clock
    {
        return new Example\Clock($time);
    }
}

// Now register the service provider
$container->register(new Services());

// To get my clock you would simply use
$container->get(Example\Clock::class);

// Or access the service through its alias (the name of the method)
$container->get('clock');



/** @var Neat\Service\Container $container */

// Assuming your container can produce a PDO and Clock object instance
class BlogController
{
    private $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    public function getPosts(Example\Clock $clock, string $tag = null) {
        // ...
    }
}

// You'd create a controller and automatically inject the PDO object
$blog = $container->create(BlogController::class);

// Call the getPosts method and have it receive the Clock object
$posts = $container->call([$blog, 'getPosts']);

// You can combine these two calls into one invocation
$posts = $container->call('BlogController@getPosts');

// And pass any arguments you wish to specify or override
$sportsPosts = $container->call('BlogController@getPosts', ['tag' => 'sports']);