Adam Monsen
Adam Monsen

Reputation: 9420

symfony2 service is not a singleton

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:

Any ideas?

Upvotes: 5

Views: 7238

Answers (2)

Mun Mun Das
Mun Mun Das

Reputation: 15002

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.

Upvotes: 2

Chris M. Welsh
Chris M. Welsh

Reputation: 477

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.

Upvotes: 13

Related Questions