Archive for the 'Symfony' Category

Ten reasons why Symfony rocks – Part 2

If you weren’t convinced by the first 5 reasons why Symfony rocks, you will certainly be today.

Symfony’s closest competitors are probably RoR or rolling your own framework. Using a pre-made framework instead of rolling your own has several advantages:

  • Easy collaboration between coders, because of standardized approach
  • A framework developed by many will include nice features which you wouldn’t bother to implement on your own
  • You can outsource part of your development easily, or if you serve customers they receive a product their own developers can easily work on.
  • Working in a framework not developed by you teaches you the practices of other developers (some of which might be good)

Lets see the final 5 reasons why Symfony rocks. My chosen 10 are just a small subset of the powerful capabilities of Symfony and I will link to all good blog posts covering this topic. (Current Symfony version as of writing is 1.0.7)

1 – Internationalization and Localization (i18n & L10n)

Symfony offers a really fantastic suite of internationalization tools. I suppose the fact that the creators are in France has something to do with it. The simple comment example of the last post actually gives us a nice start to show the possibilities. We will support these nice languages: (English, Dutch, Italian and Romanian – the last two thanks to my girlfriend).

As mentioned Symfony provides a full solution. For the basic translation needs Symfony uses a helper function with two underscores, as such: __(‘text which will be translated’). The text which needs to be translated can be exported to an XLIFF format using a plugin (Will be part of Symfony in 1.1.0) . For those wondering the XLIFF format looks like this:

<trans-unit id="5">
<source>Your name</source>
<target>Uw naam</target>

A simple config setting deals with the usage of utf-8; Formatting for numbers and dates are available and use the culture automatically. format_date() and format_number() automatically adjust their output depending on the culture.

Best of all the data model supports the concept of I18n tables. This allows you to have translations of items in your database (for instance products) and leave all the logic of dealing with this to Symfony. More advanced translation needs such as sentences, which depending on the database results need to be pluralized are also supported.

Lets look at the possibilities using the simple comment example. Implementing these languages is achieved in a few simple steps:

Firstly Symfony needs to be configured to support translations. This feature is turned off by default for performance reasons. To do this simply uncomment the commented lines in frontend/config/i18n.yml and set the following settings in frontend/config/settings.yml:

standard_helpers: [i18n]
charset: utf-8
i18n: on

Secondly we need to tell Symfony how to change the URLs, which we do in routing.yml. We will use URLs like this symfony-examples/nl/comment. Thirdly we need to actually use the interface translation helper __ on all our text, as such:
__('All Comments:')
I happened to forget the submit button the first time around. This is a rather tedious process and you would usually do this while you create the template and not afterwards.

So now the fun of actually translating. First we create the and run the command: symfony i18n extract frontend ro. This command uses the plugin to extract the text, which needs translating. After some translating we now have a nicely internationalized version of the comment example. Go see and click the flags!

Those cute flags were created by famfamfam

Flags by famfamfam

Read More: Internationalization in the Manual

2 – Caching

Caching is essential to the performance of any website. In many situations you can mess everything else up as long as your caching is good.
When reading about frameworks you will likely read that Symfony is somehow slow. Now off course you start to wonder whether this is true given that Yahoo uses it for its bookmark service. My impression is that these tests either use oversimplified ‘hello world’ examples or forget to query the database efficiently. A proper tests of speeds has to my knowledge not yet been conducted. Symfony is in fact lighting fast and offers a wide array of caching tools:

  • Cache of an action (with or without the layout)
  • Cache of a partial, a component, or a component slot
  • Cache of a template fragment
  • (plugin) sfArrayCachePlugin to cache an array
  • (plugin) sfSuperCache Plugin to cache pages fully statically
  • (snippet) Some work on a memcached plugin has already been done, which will be interesting for our developers fortunate enough to need it. (didn’t test this personally)
  • Function result caching with sfFunctionCache
  • sfProcessCache for memory caching with the help of PHP accelerators

In order to make the nice comment example nice and fast we will add some simple caching to it.

in myapplication/mymodule/config/cache.yml:

enabled: on
with_layout: false
lifetime: 3600

This enables the cache, however we do want to clear the cache when someone submits a new comment. This is easily achieved by adding the following to your update action:

$sf_root_cache_dir = sfConfig::get('sf_root_cache_dir');
$cache_dir = $sf_root_cache_dir.'/frontend/*/template/*/all';

This looks a bit complicated, but these four lines of code deal with deleting the cache for all languages.

Read more: Caching in Symfony
Read more: Memcached

3 – Development environments

Environments are a great way of running a few different set of configurations next to each other. This comes in extremely handy for development. By default Symfony has two environments: production and development. In the later all the caching is disabled, errors are displayed and the WebDebug toolbar is available.

When I wanted to setup caching these environments came in very handy. Somehow my comment form was not updating as it should. To diagnose the situation I added another environment called test (accessible by frontend_test.php), similar to dev, but with caching enabled. It quickly became clear that the problem originated from caching, client side to be specific.

For every larger application you will need to keep track of these different sets of configurations and Symfony enables this with great ease. To access the various environments simply browse to the corresponding front controller (index.php for production, frontend_dev.php for development, frontend_test.php for testing.)

To set the configuration settings, simply specify the config files as follows (example from standard frontend/config/settings.yml):

escaping_strategy: both
escaping_method:   ESC_ENTITIES
standard_helpers:  [i18n, Partial]
charset:           utf-8
i18n:              on
cache:             on

no_script_name:           on

# E_ALL | E_STRICT = 4095
error_reporting:        4095
web_debug:              on
cache:                  off
no_script_name:         off
etag:                   off

# E_ALL | E_STRICT & ~E_NOTICE = 2047
error_reporting:        4095
cache:                  on
web_debug:              on
no_script_name:         off
etag:                   on

Read more about: Development Environments

4 – Do not repeat yourself!

All coders live by the rule of not repeating yourself. Symfony tries to make this as easy as possible for you. This is completely integrated into all aspects of Symfony. You can for instance write your own: Propel Behaviors, Filters, Validators and pretty any piece of normal code. This is one of the things which you will really like in Symfony. As a starter and to keep it short I’ll just cover the DRY tools in the view layer.

In Symfony there are four important methods to not repeat yourself in the view layer:

  • Partials
  • Components
  • Slots
  • Component Slots

A partial is a simple piece of repeated template code. Say that you want to have the ability to add comments on multiple parts of your website. Simply stash the template code for adding comments in a partial. Partials are stored in the template directory with a _ (single underscore) before the partial name. When you want to include them simply use:

<?php include_partial('module/partial',array('varinpartial' => $myvar)) ?>

When the code to repeat becomes more complex and also requires some logic we can separate the logic and template code by using a component. Suppose for instance that you created a blog using Symfony and want to display the latest blog posts. The logic part of querying the database goes in a components.class.php file and the template in a partial. This gives you a very convenient way to reuse code. Including goes as follows:

<?php include_component('blog', 'latestposts') ?>

Slots are placeholders. You can define its content anywhere in the view layer. This is great if you for instance want to have a default sidebar in your layout, with the ability to overwrite it in the template.

The really interesting one is the component slot. This combines the power of the configuration file with logic and view separation. It functions very similar to a component, except that logic part to execute is indicated by a config file. As follows:

sidebar: [bar, user]
sidebar: []
sidebar: [bar, options]

This would make the component slot display a user related sidebar by default, but on the index page display no sidebar and on the page displaying the user data display a sidebar with options.

Read more: Symfony’s View Layer

5 – Bridges to other frameworks

A short, but important point. Both the Zend framework and EZ components offer quite some valuable tools. Symfony feautures bridges to both of these, giving you access to two large arrays of tools.

This allows for nice things, such as an instant search engine for your site, using Zend Search Lucene (released just days ago). There is always a lot of discussion regarding the so called best framework, but I believe that eZComponents and Zend are actually pretty complimentary to Symfony.

These 10 points showed some of the power of Symfony. Hope you enjoyed them and will run over straight to The Symfony Documentation. If you like Symfony then Digg this post up and spread the word!

PHP &Symfony &Web Development tschellenbach 08 Sep 2007 186 Comments

Updating the Askeet tutorial


Halfer just suggested to update the Askeet tutorial.

When I started out with Symfony this Askeet tutorial made me wonder if Symfony really is the best out there… Should I use RoR or Zend, those were my thoughts. Currently I think I made the right choice by sticking with Symfony. For me it has been a great learning experience and highly productive coding.

An important part of the value of a framework comes with its adoptance. Rewriting the askeet tutorial will go a long way towards achieving that.

Sign me up for a day!

PHP &Symfony &Web Development tschellenbach 07 Sep 2007 Comments Off on Updating the Askeet tutorial

Symfony Camp and the framework’s blazing progress

Symfony has been producing some amazing music lately. The eagerly awaited version 1.1 progressing rapidly with the delegation of 1.0 development; Plugins are developing at an amazing speed (example, example); Great posts are being written to further enhance one’s understanding of Symfony: such as Understanding Behavior and tomorrow will be the start of the highly anticipated Symfony Camp.

Hope that all the participants will have a great time. With speakers such as

It should certainly be a good event. Congrats to Stefan Koopmanschap and the entire team at Dutch Open Projects for setting up a nice event in The Netherlands. IT is not very progressive in our little country and it is great to see such an event being organized!

Since I am currently on vacation in Romania I will have to miss the great event, but I surely hope everyone will blog and post the slides online!


Fabien’s Slides 


Events &PHP &Symfony &Web Development tschellenbach 06 Sep 2007 4 Comments

Ten reasons why Symfony rocks – Part 1

In the short attention span of most fellow PHP developer’s, here the first 5 great reasons to use Symfony. (Update: part 2 is here.) This is by no means a full explanation of Symfony, but just enough to get you running over to the documentation to learn more.

Few general highlights first:

  • Enterprise Ready – (used for Yahoo bookmarks)
  • Many Plugins available (eg. authentication, authorization, client side validation, thumbnail, rss)
  • Actively developed
  • Good documentation

1 – Ajax and Javascript

With all the hype surrounding web II.0, any major PHP framework has to add some Javascript and Ajax support. Symfony gives you a few nice building blocks. Small example:

<?php echo form_remote_tag(array(
'url' => 'project/addReply',
'update' => 'replys',
'complete' => visual_effect('highlight', 'replys').
'position' => 'bottom',
), 'id=addReply style=display:none;') ?>
<?php echo input_hidden_tag('id', $project->getId()) ?>
<?php echo textarea_tag('body') ?><br />
<?php echo submit_tag('submit') ?>
<?php echo link_to_function('Add a reply', visual_effect('toggle_appear', 'addReply')) ?>

This little snippit gives you an AJAX form, which submits its data to project/addReply (module/action). With a nice visual effect for appearance. Extremely fast to implement and extend. Have a look at my ajax comment form example.

Read More: Ajax in Symfony

2 – Instant admin interface: Advanced crud generation for admin interface

Useful for almost any type of website. Say you have a job listing website, run the command:
symfony propel-init-admin backend listing listings
and there you have your crud admin interface ready. Pretty, friendly, fully featured and without writing a single line of code.

Admin Generator Example

But wait, what if I want to include feature X in the admin interface? Symfony uses a generator.yml configuration file which allows you to set filters and customize your admin interface. Most of the time this will more than fulfill your needs and you will easily create complete and functional backends.

See it happening: Generator Movie

3 – Nice Urls: The Routing System

Symfony uses a frontend controller, in which all requests are managed through a single frontend. This makes creating nice urls simpler than ever.
url: /weblog/:title
param: { module: post, action: permalink }
url: /latest_posts
param: { module: post, action: list }

How does that compare to writing htaccess files?
If you for instance would want the url for member profiles on your site to be you would simply use:
url: /members/:membername
param: { module: users, action: show }

The url indicates how you want the url to look and the param value tells Symfony where the code is located.

Read More: Links and the routing system

4 – Form Handling: Fillin, Validation and Creation

One of the areas where Symfony really shines is the handling of forms. The code for generating forms is clean and easy to understand and learn.

<?php echo select_tag('name', options_for_select(array(
'Steve' => 'Steve',
'Bob' => 'Bob',
'Albert' => 'Albert',
'Ian' => 'Ian',
'Buck' => 'Buck'
), 'Ian')) ?>
=> <select name="name" id="name">
<option value="Steve">Steve</option>
<option value="Bob">Bob</option>
<option value="Albert">Albert</option>
<option value="Ian" selected="selected">Ian</option>
<option value="Buck">Buck</option>

Furthermore validation and re-filling the form is done in a configuration file. This keeps your code and templates nice and clean. An example:fillin:
enabled: true
msg: The name field cannot be left blank
min: 2
min_error: This name is too short (2 characters minimum)
max: 100
max_error: This name is too long. (100 characters maximum)

With some simple config lines you can take care of fillin and validation. For the skeptics, off course you can define your own validators. As far as I’ve experienced you can pretty much extend Symfony any way you like, with minimal effort. If you want client side validation as well you can opt to do so by installing one of the many plugins.

Read More: Forms in Symfony

5 – Debugging on Steroids

We all wish our code to run smoothly in the first try. However the only way to achieve this is to never try anything new. If we have to Debug, let it at least be fast. Symfony provides us with a few awesome tools. First one is the developer toolbar.

Developer Toolbar

Showing you: 1. your application variables (useful for multiple development environments) 2. logs and messages (all the steps used for executing the page, perfect for debugging) 3. the number of queries and their sql 4. the size of the page 5. the load time throughout various points of the code.


If you do something wrong related to Symfony, it gives you a nice explanation of the problem, through it’s custom error display. Installing the famous Xdebug extension further increases the amount of information displayed.

Read More: Application Management Tools

All these little things together make developing with Symfony a joy. More goodness to come up in part two of this post.

(Watch out with installing Symfony though. It will take you anywhere between 30 seconds and two days. Depending on your experience with PEAR. There are some great install guides on the Symfony Wiki.)

Part 2 has been published: Ten Reasons why Symfony rocks – part 2

PHP &Symfony &Web Development tschellenbach 18 Aug 2007 1,078 Comments

« Previous Page