Search code examples
symfonymodelcode-injectionpropelsetter

Symfony2 Setter Injection doesnt works


I build my business logic with propel. All the models extends an abstract model, in which I want to inject the security context:

Services.yml

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

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

The 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();
    }
}

If propel runs the preSave method, it responses with a 500:

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

Anyone know whats going wrong here?

Greetings

Update_01:

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

Solution

  • An abstract class cannot be instantiated.

    Extend your Abstract class:

    class MyModel extends AbstractModel 
    {
    }
    

    and use this class as service:

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