PHP code example of ph-7 / dependency-injection-container

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

    

ph-7 / dependency-injection-container example snippets


use PierreHenry\Container\Container;
use PierreHenry\Container\Providable;
use Symfony\Component\HttpFoundation\Request;

$container = new Container();

// Register your container
$container->register(
    'example.symfony.httprequest',
    new class implements Providable
    {
        public function getService(): Request
        {
            return Request::createFromGlobals();
        }
    }
);

// Retrieve the container
$httpRequest = $container->get('example.symfony.httprequest');

// Use it
$request = $httpRequest->request; // $_POST body params
if ($request->get('get_var')) {
    echo '$_POST["get var"] exists';
} else {
    echo '"get_var" has not been requested';
}

use DateTime;
use DateTimeZone;
use PierreHenry\Container\Container;
use PierreHenry\Container\Providable;

$container = new Container();
$container->register(
    'stubs.date.datetime',
    new class implements Providable
    {
        public function getService(): DateTime
        {
            return new DateTime('now', new DateTimeZone('America/Chicago'));
        }
    }
);

// Retrieve the container
$date = $container->get('stubs.date.datetime');

// Use it
echo $date->format('m-d-Y H:i:s');