Symfony2 Setter Injection不起作用

时间:2014-03-03 10:58:25

标签: symfony model code-injection propel setter

我用推动力构建我的业务逻辑。所有模型都扩展了一个抽象模型,我想在其中注入安全上下文:

Services.yml

parameters:
    Abstract.Model : 'FooBundle\Model\AbstractModel'

services:
    Abstract.Model:
        class: 'FooBundle\Model\AbstractModel'
        calls:
            - [setSecurity, ["@security.context"]]

AbstractModel

abstract class AbstractModel extends BaseObject
{
    /**
     * @param $security \Symfony\Component\Security\Core\SecurityContext
     */
    protected $security;

    /**
     * Sets the security context
     *
     * @param $security \Symfony\Component\Security\Core\SecurityContext
     */
    public function setSecurity($security)
    {
        $this->security = $security;
    }

    /**
     * Code to be run before persisting the object
     *
     * @param PropelPDO $con
     * @return boolean
     */
    public function preSave(\PropelPDO $con = null)
    {
        $token = $this->security->getToken();
    }
}

如果propel运行preSave方法,它会以500:

响应
FatalErrorException: Error: Call to a member function getToken() on a non-object

任何人都知道这里出了什么问题?

问候

Update_01:

public function save(PropelPDO $con = null, $skipReload = false)
{
    ...
    $ret = $this->preSave($con);
}

1 个答案:

答案 0 :(得分:1)

无法实例化抽象类。

扩展您的Abstract类:

class MyModel extends AbstractModel 
{
}

并将此类用作服务:

services:
    My.Model:
        class: 'FooBundle\Model\MyModel'
        calls:
            - [setSecurity, ["@security.context"]]