PHP code example of mts7 / php-dependency-injection

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

    

mts7 / php-dependency-injection example snippets


$container = new Container();

// set an alias with a reference to the class name
$container->set('car', Car::class);
$car = $container->get('car');

// set the name to the class name and provide an instantiated object
$container->set(Car::class, new Car());
$car = $container->get(Car::class);

// provide only the name of the class and get an instantiated object
$container->set(Car::class);
$car = $container->get(Car::class);

// the factory would create a new Container, then call ->load($config) with the appropriate values
$container = ContainerFactory::create();

$car = $container->get(Car::class);
$car->setName('Taco');
echo $car->getName();

$container = new Container();
$container->load([Color::class, Car::class]);

// there is no need to pass `Color` to the container since all dependencies load automatically
$car = $container->get(Car::class, ['Alice']);
// getting the color comes from Car's dependency rather than an outside influence
$car->getColor()->setHex('#F0F8FF');
echo $car->getName() . ' is ' . $car->getColor()->getHex();
shell
composer