dimanche 3 décembre 2017

Dependency injection wrongly implemented?

I have been told that my implementation below doesn't need dependency injection, however Jeffrey Way uses DI in two similar examples in this tutorial: http://ift.tt/1x4Q22T and that is confusing me. Testing is an important aspect in my application, if that makes any difference.

This is the code I implemented so far.

Is my code incorrect?


Model Bus.php

namespace App\Models;

class Bus {

    private $screen;
    private $isStopped;

    function __construct(Screen $screen)
    {
        $this->screen = $screen;
    }

    public function stops()
    {
        $this->isStopped = true;
        $this->screen->hideRequestedSign();
    }

    public function starts()
    {
        $this->isStopped = false;
    }
}


Model Screen.php

namespace App\Models;

class Screen {

    private $buttons;
    private $isSignDisplayed;

    public function displayRequestedSign()
    {
        $this->isSignDisplayed = true;
    }

    public function hideRequestedSign()
    {
        $this->isSignDisplayed = false;
    }

    public function isSignDisplayed()
    {
        return $this->isSignDisplayed;
    }
}


Model Button.php

namespace App\Models;

class Button {

    private $screen;
    private $pressed = false;

    function __construct(Screen $screen)
    {
        $this->screen = $screen;
    }

    public function press()
    {
        $this->pressed = true;
        $this->screen->displayRequestedSign();
    }

    public function isPressed()
    {
        return $this->pressed;
    }

}


Test BusStopRequestTest.php

class BusStopRequestTest extends TestCase {

    public function test_press_button()
    {
        $button = new Button(new Screen);

        $button->press();

        $this->assertTrue($button->isPressed());

    }

    public function test_screen_display_requested_stop_sign()
    {
        $screen = new Screen();
        $button1 = new Button($screen);
        $button2 = new Button($screen);
        $button3 = new Button($screen);

        $button1->press();

        $this->assertTrue($screen->isSignDisplayed());

    }

    public function test_bus_stops_and_resets_sign()
    {
        $screen = new Screen();
        $button1 = new Button($screen);
        $button2 = new Button($screen);
        $button3 = new Button($screen);

        $bus = new Bus($screen);

        $button1->press();
        $bus->stops();
        $bus->starts();
        $button2->press();

        $this->assertTrue($screen->isSignDisplayed());

    }
}

Aucun commentaire:

Enregistrer un commentaire