Overriding setter/getter in Symfony

07-02-2010 przez damian Zostaw odpowiedź »

Overriding methods should not be a problem, but it can make you confused if you don’t know how magic functions are used in Symfony 1.4 models.

In this short article I will explain why usual overriding does not work in Symfony models and how to override methods handled by magic functions.

Suppose, we have a base model class BaseTopic:

abstract class BaseTopic extends sfDoctrineRecord
{
public function setTableDefinition()
{
$this->setTableName('topic');
$this->hasColumn('name', 'string', 255, array(
'type' => 'string',
'notnull' => true,
'length' => 255,
));
$this->hasColumn('updates_count', 'integer', null, array(
'type' => 'integer',
));
}
}

and our class:

public class Topic extends BaseTopic
{
}

Now we want to update updates_count field each time we modify name field.

First guess is to do the following:

public class Topic extends BaseTopic
{
public function setName($name) {

$this->updates_count++;

return parent::setName($name);

}
}

However it will not work unless you have declared method setName in BaseTopic literally (magical __call does not count).

Upper method will do the following:

  1. Increment updates_count field
  2. Call setName method from BaseTopic (which does not exist literally) so it will look for this method in parents
  3. Because there is no setName in any parent class, it will go to Doctrine_Record and call __call method which will find setName method in Topic class
  4. Call setName from Topic class again

To solve this problem you have to use _set function from Doctrine_Record class:

public class Topic extends BaseTopic
{
public function setName($name) {

$this->updates_count++;

return $this->_set('name', $name)

}
}

Remember to use function _set(), not set().

Of course there is no problem if you have defined setName method in any of Topic‘s parent classes literally.

Reklama

Dodaj komentarz

Flexmaniaks on Facebook