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:
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?
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.