#native_company# #native_desc#
#native_cta#

Working with the Symfony Components PHP Libraries

By Octavia Andreea Anghel
on May 11, 2010

In this article, you will learn how to work with the three PHP libraries in the Symfony Components library:
  • YAML
  • Templating
  • Event Dispatcher
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

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:
  • sfYamlParser: This class is used to parse YAML strings.
  • sfYamlDumper: This class dumps a PHP array to a YAML string.
The main sfYaml class offers convenience methods to load and dump YAML.

<?php

require_once('sfYaml.php');
require_once('sfYamlParser.php');
require_once('sfYamlDumper.php');

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

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

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

print_r($loader);

?> 

Here is the file.yaml file from the above example:

receipt:     Octavia Anghel Invoice
date:        2010-05-01
customer:
    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:

<?php

require_once('sfYaml.php');
require_once('sfYamlParser.php');
require_once('sfYamlDumper.php');

$array = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     )
              );
 
$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]

fruits:
  a: orange
  b: banana
  c: apple
numbers:
  - 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:
  • The subject of the event (Most of the time, this is the object notifying the event, but it can also be null.)
  • The event name
  • An array of parameters to pass to the listeners (an empty array by default)
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:
  • getName(): Returns the identifier of the event
  • getSubject(): Gets the subject object attached to the event
  • getParameters(): Returns the event parameters
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:

<?php

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:

<?php

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

  $this->dispatcher->filter($event,$this->content);

  echo $event->getReturnValue();
  }  
}

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

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

//Connecting a listener to the dispatcher
$dispatcher->connect('response.filter_content',$listener);

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

?>

The output of this application is:

Hello