Support the ongoing development of Laravel.io →
IOC Architecture
Last updated 2 years ago.
0

The first method that you are using is taking advantage of the dependency injection container that is built into Laravel. If you ever want to unit test this code, you'll be much happier with the first method. It will allow you to mock out your A dependency during unit testing of B, which is impossible if you use the second method.

For example: (this is adapted from https://phpunit.de/manual/current/en/test-doubles.html):

public function test_some_data_is_set_on_istantiation()
{
    // Create a stub for the A class.
    $stubA = $this->getMockBuilder('A')
                 ->getMock();

    // Configure the stub.
    $stubA->method('parseSomeData')
         ->willReturn('parsedData');

    $b = new B($stubA); // You can't do this with the second method
    $this->expectEquals('parsedData', $b->someData); 
}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Luddinus luddinus Joined 18 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.