PHP code example of stubbles / ioc

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

    

stubbles / ioc example snippets


interface Car {
    public function moveForward($miles);
}
interface Person {
    public function sayHello();
}
interface Tire {
    public function rotate();
}
interface Engine {
    public function start();
}

class BMW implements Car {
    private $driver;
    private $engine;
    private $tire;

    public function __construct(Engine $engine, Tire $tire, Person $driver) {
        $this->engine = $engine;
        $this->tire   = $tire;
        $this->driver = $driver;
    }
    public function moveForward($miles) {
        $this->driver->sayHello();
        $this->engine->start();
        $this->tire->rotate();
    }
}

class Schst implements Person {
    public function sayHello() {
        echo "My name is Stephan\n";
    }
}

class Goodyear implements Tire {
    public function rotate() {
        echo "Rotating Goodyear tire\n";
    }
}

class TwoLitresEngine implements Engine {
    public function start() {
        echo "Starting 2l engine\n";
    }
}

    $tire   = new Goodyear();
    $engine = new TwoLitresEngine();
    $schst  = new Schst();

    $bmw    = new BMW($engine, $tire, $schst);
    $bmw->moveForward(50);

$binder = new \stubbles\ioc\Binder();
$binder->bind('Car')->to('BMW');
$binder->bind('Tire')->to('Goodyear');
$binder->bind('Person')->to('Schst');
$binder->bind('Engine')->to('TwoLitresEngine');

$injector = $binder->getInjector();
$engine = $injector->getInstance('Engine');
var_dump($engine);

    $injector = $binder->getInjector();
    $car = $injector->getInstance('Car');
    var_dump($car);