Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lraveri's avatar

Managing Dynamic Service Dependencies in Laravel

I'm working on a Laravel app where several services depend on a dynamic parameter ($shop), determined at runtime (from a request or job). I need to initialize external clients (e.g., ShopifyClient, AWSClient) based on this parameter. Currently, I pass $shop manually and initialize the clients in every method, which feels inefficient and repetitive.

What are the best practices for managing dynamic dependencies like this in Laravel, while keeping the code clean and avoiding re-initialization logic in every method? Any suggestions?

0 likes
1 reply
krisi_gjika's avatar

you can initialize these clients once, wherever you have access to the current $shop, and bind them in the application container. example:

$shop = Shop::query()->findOrFail($shop_id);
// if you have an interface for this class you can bind the interface instead
app()->bind(MyShopifyClient::class, MyShopifyClient::makeForShop($shop));
// or singleton to use the same instance in every call

// than you can dependency inject your class everywhere the container is used to resolve dependencies, like controllers, jobs, events, etc.
class ShopController
{
  public function show(Request $request, MyShopifyClient $client)
....

// or get the instance out of the container yourself
class ShopService
{
  public function __constuct()
  {
    $this->client = app(MyShopifyClient::class);
...

Please or to participate in this conversation.