dimanche 13 août 2023

Laravel: Using resolve or inject from __construct?

I'm new to Laravel, recently I've learned what Service Container can do. After some researching, I found that either using resolve method or injecting dependency from constructor, I can always mock class and test my class. So I wonder is there any benefits to inject class into constructor?

example:

class Cat 
{
    public function speak()
    {
        return 'Meow!!';
    }
}

1- using dependency injection

class PetService
{
    public function __construct(Cat $cat)
    {
        $this->cat = $cat;
    }
    

    public function testFunc()
    {
        return $this->cat->speak();
    }
}

2- using resolve method

class PetService
{
    public function testFunc()
    {
        $cat = resolve(Cat::class);
        return $cat->speak();
    }
}

in testing-

class TestContainerTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function test_example()
    {
        $mock = $this->mock(Cat::class, function (MockInterface $mock) {
            $mock->shouldReceive("speak")->andReturn("test");
        });


        $node = resolve(PetService::class);
        dd($node->testFunc());
    }
}

both 2 ways can print "test". It means the mock success. Using constructor to inject may lead to heavy code in constructor, instead using resolve I can call class anywhere.

Aucun commentaire:

Enregistrer un commentaire