Support the ongoing development of Laravel.io →
posted 11 years ago
IOC

I have one abstract class AbstractValidator.

Currently, I have two subclasses, LoginValidator and SignupValidator , which extend from AbstractValidator.

I have two Services.

class LoginService {
  //how to make sure this $validator will always be LoginValidator
  function __construct(AbstractValidator $validator){}

}

class SignupService {
  //how to make sure $validator will always be SignupValidator
  function __construct(AbstractValidator $validator){}
}

Two ServiceProviders

LoginServiceProvider.php

 $this->app->bind('AbstractValidator','LoginValidator');

SignupServiceProvider.php

 $this->app->bind('AbstractValidator','SignupValidator');

And then add these two services providers to app.php

If I bind them in this way, obviously, the former one will be overwritten by the latter one. In this case, the AbstractValidator will always be resolved to SignupValidator in both LoginService and SignupService

My question :

Is there any way to make sure LoginService always has LoginValidator while SignupService always has SignupValidator

Last updated 3 years ago.
0

You dont have to have to do that. Just inject the right class in the constructor. In my opinion theres no need to try and abstract any more away, than what you have already done.

use PathToClass\LoginValidator;

class LoginService {

  protected $validator;

  function __construct(LoginValidator $validator){
    $this->validator = $validator;
  }

}
Last updated 3 years ago.
0

Thanks @Herlevsen

That's what I'm doing now.

I'm pretty new to OOP and I'd like to stick to the best practice all the time.

Saw some laravel videos doing this for subclass so I think I should do this too and then stuck at this...

Last updated 3 years ago.
0

Why wouldn't this be best practice? Your Login Service will ALWAYS be validated by the LoginValidator. Even if you some time want to switch to a more advanced (Login)Validator, you can still extend LoginValidator, so that the injection still works.

It doesn't make sense to use an abstract validator, when you know which one it will be.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

wppd wppd Joined 12 Feb 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.

© 2025 Laravel.io - All rights reserved.