How do I set a custom mutator with Doctrine YAML Schema? How do I set a custom mutator with Doctrine YAML Schema? codeigniter codeigniter

How do I set a custom mutator with Doctrine YAML Schema?


(Just a note to clarify: we are talking about Doctrine 1.x here and not Doctrine 2.x)No, there is no a way to define mutators directly in your YAML schema. Are you sure you must register the mutator there?

You could get around this limitation by creating you own doctrine behavior. Doctrine behaviors can be assigned to your models in the YAML schema. Read more here:

http://www.doctrine-project.org/projects/orm/1.2/docs/manual/behaviors/pl

In your case the behavior would look something like this:

class EbonhandsTemplate extends Doctrine_Template{    public function setUp()    {        $this->hasMutator('password', '_encrypt_password');    }    public function _encrypt_password    ....}

And in your yaml schema:

EbonhandsModel:  actAs: [EbonhandsTemplate]


I ended up solving this by adding a new method to the generated User.php model as follows:

public function setPassword($pass){  $this->_set('password', $this->_encrypt_password($pass));}

It achieves the same end result as the tutorial linked above (e.g. allowing modifications to the User model schema via YAML without losing code), but doesn't feel as elegant or general-purpose.

I'm marking Olof's answer as correct/accepted, as his solution feels more extensible and OO - mine "smells" a bit


There is one important thing to notice about mutators if you loading data from YAML files.

As in tutorial you mentioned if your User class is like:

class User extends ModelBaseUser{    public function setUp() {        parent::setUp();        $this->hasMutator('password', '_encryptPassword');    }    protected function _encryptPassword($value) {        $salt = $this->_get('salt');        $this->_set('password', md5($salt . $value));    }}

and you using loadData() to fill your database from YAML file make sure you load salt field first as shown below:

ModelUser:    User_Admin:        username: admin        salt: $secret_        password: adminPa$$        email: admin@promosquare.com

instead of:

ModelUser:    User_Admin:        username: admin        password: adminPa$$        salt: $secret_        email: admin@promosquare.com