In this article, you will learn how to work with the three PHP libraries in the Symfony Components library:
These libraries were once an integrated part of the Symfony project, but now they represent a separate Symfony project. Because the Symfony Components are standalone PHP classes, you can both use them without the Symfony MVC framework and integrate them very easily in any PHP project.
You can install each of the Symfony Components in the same, very simple manner. All you need to do is download the source code (a TAR or a ZIP archive) from the project page.


YAML (which stands for YAML Isn't Markup Language) is a human-friendly data serialization standard for all programming languages. YAML is a great format for configuration files because YAML files are as expressive as XML files and as readable as INI files.
Symfony YAML is a PHP library that can parse YAML strings and convert them to PHP arrays. It can convert PHP arrays to YAML strings, as well. The Symfony YAML library consists of two main classes:
The main sfYaml class offers convenience methods to load and dump YAML.


$yaml = new sfYamlParser();
$value = $yaml->parse(file_get_contents('file.yaml'));

echo 'Receipt:  '.$value['receipt'].'<br />';
echo 'Customer:  ';
echo '<br />';

//Load the file.yaml
$loader = sfYaml::load('file.yaml');


Here is the file.yaml file from the above example:
receipt:     Octavia Anghel Invoice
date:        2010-05-01
    given:   Marie
    family:  Vlad
The output of the yaml_parser_loader.php is:
Receipt: Octavia Anghel Invoice
Customer: Array ( [given] => Marie [family] => Vlad ) 
Array ( [receipt] => Octavia Anghel Invoice [date] => 1272661200 [customer] => Array ( [given] => Marie [family] => Vlad ) ) 
The next application example dumps an array into a YAML file using the SfYamlDumper class. Here is the code for dumping an array into a YAML file:


$array = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                  "numbers" => array ( 1,
$dumper = new sfYamlDumper();

//$yaml = $dumper->dump($array,1);
$yaml = $dumper->dump($array,2);
file_put_contents('file_result.yaml', $yaml);

Here is the output of yaml_dumper.php:
fruits: { a: orange, b: banana, c: apple }
numbers: [1, 2, 3, 4, 5, 6]

  a: orange
  b: banana
  c: apple
  - 1
  - 2
  - 3
  - 4
  - 5
  - 6

Symfony Event Dispatcher

Symfony Event Dispatcher facilitates communication between PHP classes and provides a simple implementation of the Observer design pattern. An object maintains a list of its dependents (observers) and noti?es them automatically of any state changes, usually by calling one of their methods. An event dispatcher is a central object that manages connections between subjects and observers. It is a powerful mechanism to extend applications without having to change the objects themselves.
You can use this library to make your code more flexible and readily extensible by others. Third-party code listens to specific events by registering PHP callbacks and the dispatcher calls them whenever your code notifies these events.

The Event Objects

The event object of class sfEvent stores information about the notified event. Its constructor takes three arguments:
Most of the time an event is called from an object context, so the first argument is almost always $this:
$event = new sfEvent($this, 'user.change_culture', array('culture' => $culture));
The event object has several methods to get event information, including:
The first application example implements a dispatcher object, stores some information about the notified event, and then returns the identifier of the event using the getName method:

require_once 'sfEvent.php';
require_once 'sfEventDispatcher.php';

//sfEventDispatcher implements a dispatcher object
$dispatcher = new sfEventDispatcher();

//The event object of class sfEvent, stores information about the notified //event
$event = new sfEvent($dispatcher, 'event.user_name', array('user' => $user));

// Returns the identifier of the event
echo 'The event name:  '.$event->getName().'<br />';

Here is the output of this application:
The event name: event.user_name
The second application example, a dispatcher object, connects a listener to the dispatcher. The response will be an instantiation of the Response class, which uses the send method to filter a given value and then list the result using the getReturnValue method:

require_once 'sfEvent.php';
require_once 'sfEventDispatcher.php';

class Response
protected $content,$dispatcher;

public function __construct(EventDispatcher $dispatcher, $content)
    $this->dispatcher = $dispatcher;
    $this->content = $content;

public function send()

  //An event is called from an object context
  $event = new sfEvent($this,'response.filter_content');

  //The 'filter()' method asks all listeners to filter a given value,
  //passed by the notifier as its second argument, and retrieved by the
  //listener callable as the second argument


  echo $event->getReturnValue();

//sfEventDispatcher implements a dispatcher object
$dispatcher = new sfEventDispatcher();

$listener = function (Event $event,$content)
return '*'.$content.'*';

//Connecting a listener to the dispatcher

$response = new Response($dispatcher,'Hello');

The output of this application is:


The Symfony Templating component provides all the tools needed to build any kind of template system. This component is a thin and flexible layer on top of PHP that provides simple but powerful features, covering most common templating needs.
It is centered on a main class, sfTemplateEngine, which provides the features that are common to all templating systems (inclusions, template inheritance, slots, helpers, and so on), and three main sub-components: template loaders, template renderers, and template helpers.
The template loader, implemented by the sfTemplateLoaderFilesystem class, is used to load templates from the filesystem. The template renderer, implemented by the sfTemplateRendererPhp class, renders plain PHP templates.
The application example below renders a template named index.php, which should exist in the current directory and list the HTML form.
Listing template.php:
require_once 'sfTemplateAutoloader.php';
$loader = new sfTemplateLoaderFilesystem('%name%.php');
$engine = new sfTemplateEngine($loader);
echo $engine->render('index', array('name' => 'Fabien'));
The index.php listing:
<title>HTML Form for uploading image to server</title>
<form action="" method="post">
<input type="file" name="pictures[]" >
<input type="submit" value="Send" >
The output of the template.php listing is:
The next application example renders the index2.php template (which is in the same directory with the template2.php PHP script) listed below:
The template2.php listing:

require_once 'sfTemplateAutoloader.php';

//$engine = new sfTemplateEngine($loader, array('php' => $renderer));
$loader = new sfTemplateLoaderFilesystem('%name%.php');
$engine = new sfTemplateEngine($loader, array('php' => new sfTemplateRendererPhp()));

echo $engine->render('index2', array('name' => 'Nume'));

The index2.php template is:


<TD><B>Phone Number</B></TD>

The output of the template2.php is:
Name   Surname Phone Number
Ionescu Bogdan    123456 
Stancu   George     567890


You can use helpers, the PHP functions used to return HTML code, in templates. Helpers save you from complex coding and make the process of writing templates very easy. Below is a list of several helpers that are available by default in every template; they don't need declaration. These helpers are of the following helper groups:
The line below turns all URLs and email addresses into clickable links using the TextHelper helper:
<?php echo auto_link_text('Please visit the website to read interesting articles.') ?>

Please visit the website <a href="'">'</a> to read interesting articles.
The following application example presents a brief list of frequently used default helpers and the HTML code returned:
Listing using_helpers.php:
// Using a Helper named HN- using the HelperHelper helper
<?php use_helper('HN') ?>
<?php use_helper('HN1', 'HN2') ?>
// Creating a Tag group – using the TagHelper helper
<?php echo tag('input', array('name' => 'HN', 'type' => 'text')) ?>

// Alternative options syntax to list a tag
<?php echo tag('input', 'name=HN type=text') ?>  

<?php echo content_tag('textarea', 'helper name', 'name=HN') ?>
// Using an Url group – using the UrlHelper helper
<?php echo link_to('click', '/php/') ?>
<?php echo auto_link_text auto_link_text('Please visit website to read interesting articles.') ?>

// Using the AssetHelper helper group
//Returns an <img> image tag for the asset given as argument
<?php echo image_tag('php_image', 'alt=mypicture size=640x400') ?>

//Returns a <script> include tag per source given as argument
<?php echo javascript_include_tag('my_js_script') ?>

//Returns a CSS <link> tag per source given as argument
<?php echo stylesheet_tag('style') ?> 
The output of the above helpers is:
=> <input name="HN" type="text" />
=> <textarea name="HN">helper name</textarea>
=> <a href="/php/">click </a> 
=> Please visit website <a href="'">'</a> to read interesting articles.
=> <img src="/images/php_image.jpg" alt="mypicture" width="640" height="400"/>
=> <script language="JavaScript" type="text/javascript" src="/js/my_js_script.js"></script>
=> <link href="/stylesheets/style.css" media="screen" rel="stylesheet"type="text/css" />

What Have You Learned?

In this article, you have learned the basics of working with the Symfony Components library: the YAML, Templating, and Event Dispatcher PHP libraries.
About the Author
Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies -- XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests. to e-mail her.