Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 service is not a singleton

Tags:

php

symfony

I'm creating a simple pastebin web application on top of Symfony2, but I can't make a global/singleton/"container-scoped" service. I'm probably making a beginner mistake.

The symfony2 service container doc says services are "only created once and the same instance is returned each time you ask for the service", but my service constructor is being called on every request.

I can verify this pretty easily from the logs. I just refresh /p/new and I see another

[2012-03-31 21:32:56] app.INFO: InMemoryPasteService::__construct() [] []

I've also confirmed by logging the result of

spl_object_hash($this->get('twobulb_paste_service'))

In the controller (and the hash is different for every request).

The environment (app/prod) doesn't seem to matter.

How to work with Scopes says the default scope is "container", so I take that to mean there should only be one instance of my service class.

I started with the Symfony standard distribution (without vendors) version 2.0.12.

Source code:

  • my service, my service config
  • a controller using my service

Possibly similar posts:

  • https://stackoverflow.com/questions/8873824/symfony2-service-definition-issue
  • Symfony2 Service Container - does get() return objects by reference or copy?
  • How Service Container create object declared in services.yml?

Any ideas?

like image 801
Adam Monsen Avatar asked Dec 10 '22 01:12

Adam Monsen


2 Answers

There is no state saved between requests in this way. You can consider it as if the PHP interpreter is rebooted between each request. That's just how PHP works.

like image 109
Chris M. Welsh Avatar answered Jan 01 '23 18:01

Chris M. Welsh


According to this post spl_object_hash creates md5 hash of the internal pointer of the object. So it is normal that it gives different hash between requests. The hash does not change in same request cycle.

like image 40
Mun Mun Das Avatar answered Jan 01 '23 17:01

Mun Mun Das