1

According to Symfony docs, doing shared: false on a service should mean that each time you call a service, you get a new instance. However, this doesn't seem to work for me. I am using Drupal 9 which runs on Symfony 4.4.

My services.yml :

services:
  my_module.arbitrary_data:
    class: Drupal\my_module\Services\ArbitraryData
    arguments: ['@another_module.contextual_uid']
    shared: false

https://symfony.com/doc/4.4/service_container/shared.html

I've also tried the deprecated scope: prototype and scope: request methods to no avail. If I load a page, my services outputs unchanged data from the last time the page was loaded until I clear cache.

Regardless of doing this, the services fail to run after the first page load after clearing cache and just proceed to output unchanged data every time. This feels like "unwanted caching".

Edit 11/15 3:47PM The render array from the plugin using the service, as requested:

$service = \Drupal::service('my_module.arbitrary_data');
$data = $service->get('acr');
$data = array_shift($data);

return [
  '#markup' => $data['value'],
];
7
  • I agree that according to drupal.org/docs/drupal-apis/services-and-dependency-injection/… this is supposed to be supported. I don't, however, understand the symptoms you described in the way you described them.
    – cilefen
    Nov 15, 2022 at 21:18
  • Where are you invoking the service? Inside a hook which is cached maybe? What does the cache look like on the render array which is outputting the data?
    – Clive
    Nov 15, 2022 at 21:35
  • Setting a service to not shared only has an effect on the service properties in memory, not the Drupal cache data stored in the database.
    – 4uk4
    Nov 15, 2022 at 21:35
  • @Clive It's being used in a controller that is not being cached, in fact the route that calls the controller is set to no_cache.
    – pixel5
    Nov 15, 2022 at 21:38
  • @cilefen Imagine you have a custom service which returns the current time. On the first request, the service returns the time. On the second request, the same time as the first request is returned. I have a feeling that there is a cache context that needs to be changed somewhere, I just don't know where or what.
    – pixel5
    Nov 15, 2022 at 21:40

1 Answer 1

2

Thanks to user @Clive 's questioning, it led me to assess this issue as a Plugin problem rather than a Service problem. Since the service is being used in a plugin, and the plugin was being cached (by default), my output was not changing.

Implementing cache max-age into the plugin's render array fixed this issue.

return [
  '#markup' => $data['value'],
  '#cache' => [
    'max-age' => 0,
  ],
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.