1

I'm using a YAML configuration to wire my dependencies, and I need to provide some runtime information to get a useful object back. I was going to run a setter method from my code once the object has been injected, but I Was wondering if there was a better way of doing it (or if there's something I'm missing).

This is the gist of my configuration:

services:
    example_object : "myObject"
        arguments : ["%object_parameter1%"] 
parameters:
    object_parameter1 : Some Static Data
    object_parameter2 : #Rutime info required
4

2 回答 2

1

您不应尝试将动态值直接添加到 DI 配置中。Symfony 服务配置由编译后的 DI 容器反映,重新编译是非常繁重的操作。

如果您不想直接将您的服务与 Symfony 的安全系统耦合,您可以添加您的自定义“用户提供者”服务作为依赖项。然后,如果信息来源发生变化,您将需要重写此服务。它也可能很容易被嘲笑。

您还可以使用工厂来注入用户对象而不是用户提供者服务。

于 2013-10-28T10:19:50.957 回答
1

要在任何服务中检索当前登录的用户,请注入security.context. 在这种情况下,我使用 setter 注入来简单地模拟用户注入。

namespace Acme\ExampleBundle\Foo;
use Symfony\Component\Security\Core\SecurityContextInterface;

class MyService
{
    private $param;
    private $user;

    public function __construct($param)
    {
        $this->param = $param;
    }

    /**
     * Retrieve the current logged in user from the security context.
     */
    public function setUserFromContext(SecurityContextInterface $context)
    {
        $this->user = $context->getToken()->getUser();
    }

    /**
     * Set any user object.
     *
     * Usefull for testing, to inject a simple user mock.
     */
    public function setUser($user)
    {
        $this->user = $user;
    }

    public function doSomething()
    {
        // do something with the user object
    }
}

定义服务:

services:
    my_service:
        class: Acme\ExampleBundle\Foo\MyService
        arguments: ["%object_parameter1%"]
        calls:
            - [ setUserFromContext, [@security.context] ]
于 2013-09-30T14:13:39.003 回答