0

I have a restful api of a b2c store and now I need to implement it for a b2b store using the same endpoints, everything works different in both types so the implementation is different. Right now one exemplo of a endpoint would be like this:


use App\Service\Calculator;

class CartController extends Controller
{
    private $calculator;

    public function __construct(Request $request, Calculator $calculator)
    {
        parent::__construct($request);
        $this->calculator = $calculator
    }

    public function index()
    {
        $this->calculator->calculate();
        return response()->json(['ok'], 200);
    }

}

So I thought in inject an interface and let the provider decide which implementation use. Like this:


namespace App\Service;

interface CalculatorInterface
{
    public function calculate();
}

namespace App\Service;

class Service1 implements CalculatorInterface
{
    public function calculate() { /** */ }
}

namespace App\Service;

class Service2 implements CalculatorInterface
{
    public function calculate() { /** */ }
}

use App\Service\CalculatorInterface;

class CartController extends Controller
{
    private $calculator;

    public function __construct(Request $request, CalculatorInterface $calculator)
    {
        parent::__construct($request);
        $this->calculator = $calculator
    }

    public function index()
    {
        $this->calculator->calculate();
        return response()->json(['ok'], 200);
    }
}

To decide which type use (b2b or b2c) I need the user logged which I can't get when registering a provider. I could decide in the controller which implementation user, but I have many endpoint and would have to do that manually in all of them. So what I need is alternate between the implementation in the dependency injection based on the user. Maybe pass a parameter in the header of the request and so in the provide I check that?

fajuchem
  • 181
  • 2
  • 11
  • Using a factory class which gets the service based on user might be helpful IMHO. I'm not an expert of design patterns, but this thought came to my mind first. – Taha Paksu Feb 04 '19 at 20:01
  • You can use dyamic app binding basedon your case to set which implementation of interface should be injected. See if this helps : https://laravel.com/docs/5.7/container#binding-interfaces-to-implementations – Mihir Bhende Feb 04 '19 at 20:13
  • This is a possible duplicate of https://stackoverflow.com/questions/54549640/how-to-register-and-resolve-multiple-application-life-time-scope-objects-with-sa/54549786#54549786. – Robert Perry Feb 06 '19 at 09:06

0 Answers0