symfony2 服务不是单例 [英] symfony2 service is not a singleton
问题描述
我正在 Symfony2 之上创建一个简单的 pastebin web 应用程序,但我无法创建全局/单一/容器范围"服务.我可能犯了一个初学者的错误.
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.
symfony2 服务容器文档 说服务只创建一次,并且每次请求服务时都会返回相同的实例",但是每次请求都会调用我的服务构造函数.
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.
我可以很容易地从日志中验证这一点.我只是刷新 /p/new
并且看到另一个
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.
我从 Symfony 标准发行版(无供应商)2.0.12 版开始.
I started with the Symfony standard distribution (without vendors) version 2.0.12.
源代码:
可能类似的帖子:
- https://stackoverflow.com/questions/8873824/symfony2-service-definition-issue一个>
- Symfony2 服务容器 - 得到() 通过引用或复制返回对象?
- Service Container 如何创建在 services.yml 中声明的对象?
有什么想法吗?
推荐答案
请求之间不会以这种方式保存状态.您可以将其视为在每个请求之间重新启动 PHP 解释器.PHP 就是这样工作的.
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.
这篇关于symfony2 服务不是单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!