Symfony2 service is not a single
I am building a simple pastebin web application on top of Symfony2, but I cannot make a global / singleton / "container scope". I am probably wrong.
The symfony2 service container add-on says that services are "created only once and the same instance is returned every time you request a service" but my service constructor is called on every request.
I can verify this quite easily from the logs. I just update /p/new
and I see another
[2012-03-31 21:32:56] app.INFO: InMemoryPasteService::__construct() [] []
I have also verified by logging the result
spl_object_hash($this->get('twobulb_paste_service'))
In controller (and hash is different for every request).
The environment (app / prod) doesn't seem to matter.
How to work with scopes says that scopes are "container" by default, so I suppose that means there should only be one instance of my service class.
I started with the standard (no vendor) Symfony distribution 2.0.12.
Source:
- my service , my service config
- the controller using my service
Possibly similar messages:
- https://stackoverflow.com/questions/8873824/symfony2-service-definition-issue
- Symfony2 Service Container - returns () returned objects by reference or copy?
- How does a service container create an object declared in services.yml?
Any ideas?
Therefore, state is not persisted between requests. You can think of it as if the PHP interpreter is being reloaded between each request. This is exactly how PHP works.
According to this post spl_object_hash
creates an md5 hash of the internal object pointer. So it's ok that it gives different hashes between requests. The hash does not change in the same request.