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?