PHP code example of devtronic / injector

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

    

devtronic / injector example snippets




use Devtronic\Injector\ServiceContainer;

$serviceContainer = new ServiceContainer();

$serviceContainer->register('app.my_service', function ($name) {
  return 'Hello ' . $name;
}, ['Your Name']);

$serviceContainer->getRegisteredServices(); // Contains the registered Service 



use Devtronic\Injector\ServiceContainer;

$serviceContainer = new ServiceContainer();

$serviceContainer->register('app.another_service', function () {
    return [
        'name' => 'injector',
        'developer' => 'Julian',
    ];
});

$serviceContainer->register('app.my_service', function (array $anotherService) {
    return "Name: {$anotherService['name']}, developer: {$anotherService['developer']}";
}, ['@app.another_service']);



use Devtronic\Injector\ServiceContainer;

$serviceContainer = new ServiceContainer();

class Car
{
    /** @var int */
    public $maxSpeed = 0;

    /** @var string */
    public $color = '';

    public function __construct($maxSpeed, $color)
    {
        $this->maxSpeed = $maxSpeed;
        $this->color = $color;
    }
}

$serviceContainer->register('app.my_car', Car::class, [250, 'red']);

$myCar = $serviceContainer->get('app.my_car');
echo "My Car: Speed: {$myCar->maxSpeed}, Color: {$myCar->color}"; // My Car: Speed: 250, Color: red




use Devtronic\Injector\ServiceContainer;

$serviceContainer = new ServiceContainer();

$serviceContainer->register('app.another_service', function () {
    return [
        'name' => 'injector',
        'developer' => 'Julian',
    ];
});

$serviceContainer->register('app.my_service', function (array $anotherService) {
    return "Name: {$anotherService['name']}, developer: {$anotherService['developer']}";
}, ['@app.another_service']);

echo $serviceContainer->get('app.my_service'); // Name: injector, developer: Julian



use Devtronic\Injector\ServiceContainer;

$serviceContainer = new ServiceContainer();

$serviceContainer->addParameter('database.host', 'localhost');
$serviceContainer->register('my.service', function ($hostname) {
    return 'Connecting to ' . $hostname;
}, ['%database.host%']);