mardi 2 avril 2019

What should I use Dependency Injection or Binding in Laravel 5?

I have the class UserRepository

class UserRepository
{
    public function getUsersByCompany(Company $company)
    {
    }
}

For use this class in the controller I use Dependency Injection

class UserController extends Controller {

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function index(Company $company)
    {
        retrurn $this->repository->getUsersByCompany($company);
    }
}

Also, I can use Binding

class AppServiceProvider extends ServiceProvider
{
   /**
    * Bootstrap any application services.
    *
    * @return void
    */
   public function boot()
   {
   }
   public function register()
   {
         $this->app->singleton('user-repository', function ($app) {
               return $this->app->make(UserRepository::class);
         });
   }
}

class UserController extends Controller {

   public function index(Company $company)
   {
       retrurn app('user-repository')->getUsersByCompany($company);
   }
}

I do not understand which way is better? What should I give priority to?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2CQmFsV
via IFTTT

Aucun commentaire:

Enregistrer un commentaire