I am working on a Symfony project and I currently have this:
<?php echo preg_replace('/\n/','<br />', $review->getComments()); ?>
and would very much like to be able to make all getters add html line breaks so i don’t have to pepper my code with preg_replace. the $object->getFieldname methods are work automatically so I am looking to extend this somewhere to globally add a new method. What is the best approach here?
I think the best idea would be to add a getCommentsHtml() method onto your review object, which does something like:
Then you can use $review->getCommentsHtml() to format them using HTML. Also as Charlie mentioned, maybe str_replace would be better to use, as using a regular expression to change \n’s into <br />’s may be a little bit of overkill 🙂
So if you don’t want to have your code littered with replaces like this, I think putting a helper method on the classes that you’d like to format nicely would be the best way to go 🙂