Inject variables from Controller to Blocks? I have a Product module that implement's an entity, a Repository, a Controller and 2 Blocks

The problem is, in the product page, I'm querying the entity in every block and also in the Controller. I'm trying to find a way to query ONLY ONE TIME, and then pass the result to the 3 parts (Blocks and Controller).

So for example, I have:

class SidebarProductBlock extends BlockBase {

  $repository = new ProductRepository();

  $product_id = $route_match-&gt;getParameter('id');
  $productObject = $repository-&gt;getProductByProductId($product_id);

  // Some more processing and return 
}

class StoresGridProductBlock extends BlockBase {

// Here I query AGAIN

  $repository = new ProductRepository();

  $product_id = $route_match-&gt;getParameter('id');
  $productObject = $repository-&gt;getProductByProductId($product_id);

  // Some more processing and return 
}

// And in the Controller I query AGAIN.


How can I manage to query the database just one time and use pass the result in all 3 parts?

The Blocks are always rendered in the same page
You can't inject variables from a controller to a block.

Generally it would help to put the repository in a service, so that you don't have to instantiate it multiple times and are able to cache product objects queried before.

In this case you don't even need to call the repository in each controller/block, because Drupal upcasts entities to objects in routes and you can get the object directly from the route match, as long as the product entity is using the standard way to generate entity routes with param converter.