Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "propel setter foreignkey"

Customise propel getters and setters

The problem

The problem is the following. Assume that you have two tables, say Book and Author. Each book has one author so the getter method to get the author of a book is getAuthor().

Now assume that you modify your model to have a second author. You have two references from the Book table to the Author table. Now your code doesn't work anymore because the propel method names have changed! The propel method names are now pretty cumbersome. They look like getAuthorReferencedByAuthor for the first author and getAuthorReferencedBySecondAuthor for the second one. Bleh!

The solution

Here is a very simple solution to customise all the getters and setters of propel. The idea is to give any name you want in the schema.xml file in the following manner (in the book table for instance):

<foreign-key foreignTable="author" localName="AsFirstAuthorBook" foreignName="Author">
  <reference local="author_id" foreign="id"/>
</foreign-key>
<foreign-key foreignTable="author" localName="AsSecondAuthorBook" foreignName="SecondAuthor">
  <reference local="second_author_id" foreign="id"/>
</foreign-key>

Now with the method i suggest propel will generate getters like getAuthor (for the main author) and getSecondAuthor which seems perfectly logical. To get a list of books that an author wrote as second author you would use getAsSecondAuthorBooks which is not so bad.

For this to work you'll have to add one file in the symfony directory. Put the following in the symfony/addon/propel/builder directory under the name of MyObjectBuilder.php.

<?php
require_once 'symfony/addon/propel/builder/SfObjectBuilder.php';
 
class MyObjectBuilder extends sfObjectBuilder
{
    public function getFKPhpNameAffix(ForeignKey $fk, $plural = false)
    {
    $fkName = $fk->getAttribute('foreignName');
    return $fkName . ($plural ? 's' : '');
    }
 
    public function getRefFKPhpNameAffix(ForeignKey $fk, $plural = false)
    {
        $fkName = $fk->getAttribute('localName');
        return $fkName . ($plural ? 's' : '');
    }
 
}

Now if you want to use that customising feature in a project you only need to change propel.ini on the line in front of propel.builder.object.class and replace SfObjectBuilder with MyObjectBuilder and you are done. That project will use the customising feature. Other projects will use the usual propel naming conventions.

Additional remarks

by Olivier Verdier on 2006-07-17, tagged foreignkey  getter  propel  setter