Symfony2 控制器外部的会话数据
您好,我在将对象保存在推进模型类中时尝试获取登录用户。
我从 symfony2 上的所有文档中看到,您可以通过以下方式获取用户:
$this->get('security.context')->getToken()- >getUser()
和内部 twig
app.user
但如何从模型/实体内部获取相同的信息
编辑:
好吧,我的内容更多一点试图做,因为我不知道如何做到这一点。我看过依赖注入注入,但不确定它是否真的适合我想做的事情。
我在 Event->postSave() 中有一个名为 Event 的实体类,另一个名为 UserToEvent 我想创建 UserToEvent 对象并将其使用新的 event.id 和 user.id 保存到数据库中
我真的不认为这需要此处定义的“服务”,因为这表示服务是“某种”全球“任务”并每次我想保存新对象时都必须将用户注入到事件对象中,这似乎也有点浪费。通常我希望能够按照 Application::getUser(); 的方式做一些事情但这似乎不可能。
Hi I am trying to get the logged in user while I am saving an object in a propel model class.
I see from all the docs on symfony2 that you get the user by:
$this->get('security.context')->getToken()- >getUser()
and inside twig
app.user
but how do I get the same information from inside the model/entity
EDIT:
Ok so a bit more of what I am trying to do as I cannot see really how to do this. Ive looked at dependency injection injection but not sure it is really right for what I want to do.
I have a entity class called Event and another called UserToEvent in Event->postSave() I want to create the UserToEvent object and save that into the database with the new event.id and the user.id
I dont really think this requires a "service" as defined here as this says a service is "some sort of "global" task" and to have to inject the user into the Event object every time I want to save the a new object also seems a bit of a waste. Usually I would expect to be able to do something along the lines of Application::getUser(); but this does not appear to be possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用依赖注入。
将安全上下文或用户注入到您需要的类中。这是您在使用 Symfony2 应用程序时应该开始遵循的方法。
您可以手动或使用 DIC 注入服务。由于您想在实体类中使用它,您可能需要
在构造函数中传递依赖项:
或设置器:
或作为方法参数:
关于依赖项注入的好系列文章:http://fabien.potencier.org/article/11/what-is-dependency-injection
Use dependency injection.
Inject security context or user to the class you need it. It's the approach you should start following while working with Symfony2 apps.
You can inject services either manually or using DIC. Since you want to use it inside the entity class you'll probably need to pass the dependency
in a constructor:
or setter:
or as a method parameter:
Good series of articles on dependency injection: http://fabien.potencier.org/article/11/what-is-dependency-injection