简体   繁体   中英

What is the advantage of using constructor injection in a repository in laravel 5?

I am building a laravel 5 app and I have a repository like below:

use App\Unit

class UnitRepository implements IUnitRepository
{
     public function get_all_units()
    {
        return Unit::all();
    }

    // More methods below
}

In about 6 methods in the repository, I am doing something like Unit::someMethod. Now I am wondering if I should use constructor injection like so

class UnitRepository implements IUnitRepository
{
    public function __construct(Unit $unit){ 
        $this->unit = $unit
    }

    public function get_all_units()
    {
        return $this->unit->all();
    }

    // More methods below
}

So what would be the advantage of using constructor injection in my case. Is they some kind of performance improvement considering that I am using the facade in about 6 methods?

Appreciate help

It's not just a matter of performance (btw: the difference in terms of performance of the two cases is negligible).

As your Unit model is going to be accessed in almost any method of the repository, using constructor injection is a clear way to explicit the direct dependency of your repository to the Unit class

Besides, if you inject the dependency in you constructor, and in future you'll change the Unit class, all you have to do is to change the constructor's parameter. Instead, using facades, you'd have to change all the facades calls in all of your methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM