Symfony __toString() generation

I’ve recently had to look at Symfony, and, while OK, it’s made me realize how much I like Grails.  :)

For example, in Symfony, you generate Model classes based on a schema file.  You then generate Form objects for the Models, then tie them together in ‘CRUD’ screens.  All of this is generatable pretty easily, once you know how to do this.  This has changed (and been a bit more complicated since the 1.0 release I used last year).

Anyway, if there are relations (an Author has a Book, for example). the generated forms will complain that the generated Models need a __toString() method to be used in the Form/View.  In grails, this is the case, but every domain (corresponding to a Symfony ‘model’) has an implicit toString() method already generated, which return the string “<domain>:<id>”.  For most production work, you’ll want to override it with whatever you need the string to read, but for prototyping, it’s fine.

In Symfony’s case, I have to explicitly go add a toString() method before I can do anything else.  So, I found the object builder in the symfony core and added this to the addClassClose() method (line 351)

$script .= ”
public function __toString() {
return \””.$this->getTable()->getPhpName().” : \”.\$this->id;

The file I added this to is: /usr/share/php/symfony/plugins/sfPropelPlugin/lib/propel/builder/SfObjectBuilder.php

IMO something like this should be in the symfony core.  Does anyone else agree?  Or is this something already in the works for 1.2?

I'm currently working on a book for web freelancers, covering everything you need to know to get started or just get better. Want to stay updated? Sign up for my mailing list to get updates when the book is ready to be released!

Web Developer Freelancing Handbook

Leave a Reply