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:
{
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:
{
}
Now we want to update updates_count field each time we modify name field.
First guess is to do the following:
{
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:
- Increment updates_count field
- Call setName method from BaseTopic (which does not exist literally) so it will look for this method in parents
- 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
- Call setName from Topic class again
To solve this problem you have to use _set function from Doctrine_Record class:
{
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.