Overview of symfony 1.1 event dispatcher

As you may now by now, Symfony 1.1 introduces a new powerfull event dispatcher inspired by Apple Cocoa’s NotificationCenter. Basically, it allows any entity to “listen” to events, and get a call on the registered callback if this event ever happens.

Symfony 1.1 provides some default events you can listen to, but of course you can create your own events if you need.

Listen to an event

To listen to an event, you need to use the “connect” method on the event dispatcher instance. The first parameter is the event name, and the second is a PHP callable that will get called if the event happens.

$dispatcher->connect('user.change_culture', array($this, 'listenToChangeCultureEvent'));

Create a custom event

To use the dispatcher for your own needs, you just need to define your event name in your project specifications, and send notifications to it. Depending on the behaviour needed, three options are offered:

Simple notifications

The simpliest way is to notify all listeners with the ->notify method.

$dispatcher->notify(new sfEvent($this, 'my.super.cool.event'));

Notifications until something

Sometimes, you prefer to notify all listeners until one says “Ok guys, I handled this one. Don’t worry about it anymore”.

$dispatcher->notifyUntil(new sfEvent($this, 'my.super.cool.event'));

The first listener that will return non-false value will stop the event chain.

Filtering notifications

The last notifying method is called filtering. You set this up when you want to permit anything to act as a filter on something, meaning any listener can modify a source object.

$dispatcher->filter(new sfEvent($this, 'my.super.cool.event'), $objectToFilter);

Every listener must return the filtered value (or the original object if nothing was done) to pass to the next listener.

Practical use: Register routes in your plugins

One of the first practical applications that came to me was the new way of registering routes in plugins. In symfony 1.0, a coincidence made possible to use the routing in a plugin’s config.php but that’s not possible anymore in symfony 1.1, so you have to use the event dispatcher. To accomplish this, we’re going to set up a routing.load_configuration listener in the plugin’s config.php:

$this->dispatcher->connect('routing.load_configuration', array('myPluginRouting', 'listenToRoutingLoadConfigurationEvent'));

Then you just need to create the callback class/method:

class myPluginRouting
{
  /**
   * Listens to the routing.load_configuration event.
   *
   * @param sfEvent An sfEvent instance
   */

  static public function listenToRoutingLoadConfigurationEvent(sfEvent $event)
  {
    $r = $event->getSubject();

    // preprend our routes
    $r->prependRoute('my_route', '/my_plugin/:action', array('module' => 'myPluginAdministrationInterface'));
  }
}

Here we go :-D

Leave the first comment

Don’t be fooled by awkward view.yml js/css positionning syntax!

Short post today about advanced view.yml configuration (in symfony 1.0, and 1.1) for assets.

You can give additional options to “javascripts:” and “stylesheets:” sections, but the sin equa non condition is to know about the yet very un-documented view.yml assets syntax.

So here it is:

  javascripts: [ jquery: { position: first } ]
  stylesheets: [ mycss: { position: last, media: screen } ]

I don’t know if there are others options like thoose available, but taken the ‘position’ attribute apart, which is extracted to become the $position method argument of sfWebResponse::addJavascript() and ::addStylesheet, any other option is passed in the $options array.

Methods prototypes below:

class sfWebResponse ...
{
  /* ... */
  public function addJavascript($js, $position = '', $options = array());
  public function addStylesheet($css, $position = '', $options = array());
  /* ... */
}
Leave the first comment

HashBin now available in open-source flavor

Our first violin missed his plane yesterday, so Kwatuor is still not available in the upcoming unusable buggy pre-alpha (that miss all the functionalities anyway).

But while we’re waiting for him to be available, I released HashBin in open-source, so anybody can dive into the code, and help me making it evolve. It still needs many attention, but hey, time is not the most available resource I have, and that’s one of the two major reasons to give it to the community. Another one is that there is not so much open source symfony applications, and even less open source doctrine applications. After the doctrine 1.0 feature-freeze announcement, this could be a step to have simple sample applications (I hear little sarcastic laughs in the background…) people could dive in to learn this amazing ORM.

Well stop talking, here is the code.

SVN access is read-only for anyone, if you ever want to contribute, I’ll be glad to grant you a commit access either on trunk or branch (still have to make up my mind, but at beginning that’s not very important). Just ask me on IRC (hartym@freenode).

What amazing feature will you invent today?

Leave the first comment

Complex relations population in propel

Since quite a bit, I’ve been faced with an annoying problem on every projects I use propel on. Propel builders only generates some specific cases selection methods, which consists of pretty ugly copy paste of the same code to populate the objects, and if your needs are not satisfied by the finite little number of propel handled cases, you’ll have to either use pure SQL, or write a custom doSelect method. That seems okay at first sight, but it is not. In fact, you’re about copypasting the propel generated method, and that’s a rude violation of D.R.Y. principle.

I found no solutions during the two last years, but maybe things will change soon with the new sfPropelImpersonatorPlugin. This plugin is aiming at doing arbitrary object population based on informations provided by propel’s introspection methods (DatabaseMap/TableMap/ColumnMap) to link populated objects.

The plugin is currently in very early stage, but is working pretty well for my needs, and I’m looking forward to know what others are thinking about it.

Related links:

Leave the first comment

sfForms11Plugin: use symfony 1.1 form/validation framework in symfony 1.0 or non-symfony project

The new symfony 1.1 form/validation framework is 100% symfony-independant, and though is not limited to the (very) awaited 1.1 stable release. To use it in your own symfony 1.0 projects, you can use sfForms11Plugin. It’s content is very thin: it only sets up externals to symfony 1.1 form/widget/validator libraries.

To use it, simply add the following external to your project:

sfForms11Plugin http://svn.symfony-project.com/plugins/sfForms11Plugin

Or check it out from your project base directory:

svn co http://svn.symfony-project.com/plugins/sfForms11Plugin plugins/sfForms11Plugin

Let’s try it…

Now you’ll be able to define sfForm sub-classes to materialize forms:

class HelloWorldForm extends sfForm
{
  public function configure()
  {
  }

  public function setup()
  {
    $this->setWidgetSchema(new sfWidgetFormSchema(array(
            'name' => new sfWidgetFormInput(),
            )));

    $this->setValidatorSchema(new sfValidatorSchema(array(
            'name' => new sfValidatorString(array('required'=>true, 'min_length'=>1, 'max_length'=>50)),
            )));

    $this->widgetSchema->setNameFormat('hello[%s]');
    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    parent::setup();
  }
}

This class define the model of your HelloWorldForm, and you can now use it in your actions:

class testActions extends sfActions
{
  function executeHelloWorld()
  {
    $this->form = new HelloWorldForm();

    if ($this->getRequest()->getMethod() == sfRequest::POST)
    {
      if (null !== ($hello = $this->getRequestParameter('hello', null)))
      {
        $this->form->bind($hello);

        if ($this->form->isValid())
        {
          $this->redirect('@hello?name='.$this->form->getValue('name'));
        }
      }
    }
  }
}

At this point, the only little detail still missing is the view, containing actual form display:

<form method="POST">
<table>
<?php echo $form; ?>
<tr>
  <td colspan="2" align="right">
    <input type="submit" value="Greetings, Mr Computer!" />
  </td>
</tr>
</table>
</form>

That’s it! You now have a simple form, self-validating, protected against CSRF attacks and redirecting to some place if values entered matched our sfValidatorSchema.

Leave the first comment

Tired of spam? Try dkAntispamPlugin

After last week hashbin’s new release, I decided to publish dkAntispamPlugin. That’s an early release, and by now it is not very feature-full, but it’s doing the job we ask it, and since now, proved efficient on HashBin to make not public the pretty large amount of spam I get on it.

In One week, we got 40 messages with spam_value<10 (all checked, no spam), 14 more with spam_value<20, some of those were not spam but either inconsistent, or URL-full, 97 more between 20 and 50 (100% spam) and 498 more over this, which i’ll consider as spam (don’t really feel like reviewing all those).

For now, the plug-in only makes some reg-exp check, length check and URL count checks, but I’m planning in adding IP check and refining reg-exps to be less CPU eating. If any of you have anymore ideas to improve it… You’re all welcome :-)

At the same time, I refactored sfGeshiPlugin to dkGeshiPlugin, to leave sf prefix for official symfony plugins, so be sure to check the wiki or documentation if you’re using it.

Leave the first comment

Creating custom config handlers in symfony 1.0

When writing plugins, you often want to do it the symfony way, by putting configuration stuff in YAML files to allow the final user to override your default values in a harmless way.

To do this, the correct way is to create a config handler, extending sfConfigHandler, or its child class sfYamlConfigHandler.

Here is a simple one, just dumping YAML data found in your config file into an sfConfig::get()-able PHP dataset.

class myStupidConfigHandler extends sfYamlConfigHandler
{
  public function execute($configFiles)
  {
    // retrieve yaml data
    $config = $this->parseYamls($configFiles);

    $code = sprintf("<?php\n" .
                    "// auto-generated by myStupidConfigHandler\n" .
                    "// date: %s\n" .
                    "sfConfig::set('my_stupid_config_entry', %s);",
                    date('Y-m-d H:i:s'), var_export($config, 1));

    return $code;
  }
}

We could enhance it a bit, to take advantage of symfony’s environments and permit an ‘all’ (as a default section) and as many environment specific sections as you want. Here is it.

class myStupidConfigHandler extends sfYamlConfigHandler
{
  public function execute($configFiles)
  {
    // retrieve yaml data
    $config = $this->parseYamls($configFiles);

    // get current environment
    $environment = sfConfig::get('sf_environment');

    // merge default and environment specific config
    $config = sfToolKit::arrayDeepMerge(isset($config['all'])?$config['all']:array(), isset($config[$environment])?$config[$environment]:array());

    $code = sprintf("<?php\n" .
                    "// auto-generated by myStupidConfigHandler\n" .
                    "// date: %s\n" .
                    "sfConfig::set('my_stupid_config_entry', %s);",
                    date('Y-m-d H:i:s'), var_export($config, 1));

    return $code;
  }
}

Next step will be to tell symfony which configuration file patterns should be loaded using our class. To do this, add the following entry to config/config_handlers.yml (whether in your app, plugin or module, depending on the scope of your config handler)

config/stupid.yml:
  class:    myStupidConfigHandler

Once this is done, the very little remaining last step is to mak sure you include the compiled yml.php file with the following magic command, that will rebuild it when unexistant or outdated:

require_once(sfConfigCache::getInstance()->checkConfig('config/stupid.yml'));
/* ... */
$stupid_config = sfConfig::get('my_stupid_config_entry');

easy one :-)

One comment so far, add another

Hashbin v3 just went to public beta

I’m proud to annouce that HashBin v3 is out, using the latest improvements to dkGeshi (old sfGeshi, soon public) and the brand new dkAntispamPlugin, which can give a text a note about its probability of being spam, or junk. If everything goes well with hashbin, and after some required (i guess) tuning to the plugin, it will go opensource to let you take advantage of it.

For thoose who never used it, HashBin is a free PasteBin service, a collaborative debugging tool allowing developpers to share source code snippets. Hashbin is powered by the Symfony Framework and PHP Doctrine ORM.

Leave the first comment

Using DBMS functions with sfDoctrine

I recently had a peek on symfony forum, and seen someone asking “How can I make a SELECT count(*) FROM …. with doctrine?”. An answer to such a question should be pretty obvious as it’s of everyday use, but the question seems to have come to life many times as well on IRC than on the forum/mailing list. Here is my two-cents how-to.

Using builtin DQL aggregate functions

Basically, you can add aggregate functions (functions that operates on a group of records instead of one record, also called GROUP BY functions) to your DQL query the same way you’d do in SQL, provided the fact you’re using one of the builtin DQL aggregate functions (COUNT, MAX, MIN, AVG, SUM).

$result = Doctrine_Query::create()
     ->select('COUNT(t.id) cnt')
     ->from('Table t')
     ->execute()
     ->getFirst();

echo $result['cnt'];

Using DBMS specific aggregate functions

If the function you need is in the list, no need to go further. But some functions are DBMS specific, for example MySQL provides a GROUP_CONCAT() function. It would be nonsense for DQL to provide that, as it would not be translatable in some of the other DBMS SQL, but it would also be nonsense to restrict functionalities to the smallest common functionnalities set of every DBMS that Doctrine supports.

The way to go is to change the portablility level of doctrine, to match your needs. As the name implies, you’re loosing in portability between the different DBMS, but you’re gaining specific functionnalities of yours.

The following code, running in PORTABILITY_ALL mode, will throw a Doctrine_Query_Exception:

Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_PORTABILITY, Doctrine::PORTABILITY_ALL);
   
$result = Doctrine_Query::create()
     ->select('GROUP_CONCAT(t.value) concatedstring')
     ->from('Table t')
     ->execute()
     ->getFirst();

Now remove the Doctrine::PORTABILITY_EXPR bit to this attribute, and you will get the correct result (with mySQL):

Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_PORTABILITY, Doctrine::PORTABILITY_ALL ^ Doctrine::PORTABILITY_EXPR);
   
$result = Doctrine_Query::create()
     ->select('GROUP_CONCAT(t.value) concatedstring')
     ->from('Table t')
     ->execute()
     ->getFirst();

echo $result['concatedstring'];

Extending to other functions

Ok aggregate functions are usefull, but other functions can be very handy too, string functions for example. Doctrine manual tells us that builtin DQL string functions are CONCAT, SUBSTRING, TRIM, LOWER, UPPER, LOCATE and LENGTH.

Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_PORTABILITY, Doctrine::PORTABILITY_ALL);
   
$results = Doctrine_Query::create()
     ->select('LENGTH(t.value) val_len, t.value')
     ->from('Test t')
     ->execute();

foreach ($results as $result)
{
  echo $result['value'] . ' => ' .$result['val_len'] ."\n";
}

This code will display all records’ value fields, followed by their character length computed by the DBMS, in PORTABILITY_ALL mode.

Now let’s say you want to use BIT_LENGTH MySQL function…

Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_PORTABILITY, Doctrine::PORTABILITY_ALL ^ Doctrine::PORTABILITY_EXPR);
   
$results = Doctrine_Query::create()
     ->select('BIT_LENGTH(t.value) val_len, t.value')
     ->from('Test t')
     ->execute();

foreach ($results as $result)
{
  echo $result['value'] . ' => ' .$result['val_len'] ."\n";
}

This is the way to go again.

No need to say, this extends to every type of functions available in the different DBMS.

Leave the first comment

Testing Symfony 1.1

Wondering what symfony 1.1 will look like? Well, I couldn’t hold my curiosity neither, so I upgraded one of my websites to symfony 1.1, and I describe here how to setup a box to run both versions. The upgrade process being definitive for a given project, make backups or svn commit before upgrading.

WARNING: Symfony 1.1 is a development version, and should not be used for production. Use it at your own risks.

First of all, i did not want the upgrade to be definitive, I needed a simple way to go back to older version. But SVN would handle this, no problem. On an other side, I needed to keep the two symfony version running on the same box, as other sites are running on it.

My approach to it was to checkout the symfony trunk/lib and trunk/data in /usr/share/pear/symfony1.1 and /usr/share/pear/data/symfony1.1 respectively. This way, i can switch any project I want to symfony 1.1 by changing the config/config.php to use the development version paths.

cd /usr/share/pear/
svn co http://svn.symfony-project.com/trunk/lib symfony1.1
svn co http://svn.symfony-project.com/trunk/data data/symfony1.1

That should retrieve a local copy of the latest development version on your computer.

Upgrading a 1.0 project

To upgrade a project, your first need is to tell the symfony batch script where to find its libraries. Hopefully, symfony’s structure permits to set per-project library paths by changing config/config.php. Edit this file and replace the file content by the new 1.1 paths

// symfony directories
$sf_symfony_lib_dir  = '/usr/share/pear/symfony1.1';
$sf_symfony_data_dir = '/usr/share/pear/data/symfony1.1';

You can test your changes were effective by typing symfony in your project directory. You should now see the new namespaced pake tasks that come with symfony 1.1. As in every version, an upgrade pake task that automates the changes you have to make to your project to make it work with the new version is given, and you can do:

symfony project:upgrade1.1
symfony cache:clear

(Note that old symfony cc alias still exists for the cache:clear task)

At this point, I tryed to see if my project would be working, but a nice uncaught LogicException was showing up in development environment, and I had to manually change %project_dir%/apps/*/config/config.php (look at spl_autoload_register line…).

After a little investigation, i found that running the task twice would autocorrect it, and that it was a little problem in lib/task/project/upgrade1.1/sfAutoloadingUpgrade.class.php, so i sent a ticket on Symfony’s TRAC.

Now you should have your project up and running.

Generating a new 1.1 project

That’s easier than upgrading, but the only (little) difficulty comes from the fact that ’symfony’ script will look for 1.0 libraries. For this, you’ll create a copy of /usr/bin/symfony to /usr/bin/symfony1.1 (you’ll need to be root for this), and change its content to:

#!/usr/bin/env php
<?php

/*
 * This file is part of the symfony package.
 * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

// project exists?
if (file_exists('config/config.php'))
{
  include('config/config.php');
}

if (!isset($sf_symfony_lib_dir))
{
  if (is_readable(dirname(__FILE__).'/../../lib/VERSION'))
  {
    // SVN
    $sf_symfony_lib_dir  = realpath(dirname(__FILE__).'/../../lib');
    $sf_symfony_data_dir = realpath(dirname(__FILE__).'/..');
  }
  else
  {
    // PEAR
    $sf_symfony_lib_dir  = '/usr/share/pear/symfony1.1';
    $sf_symfony_data_dir = '/usr/share/pear/data/symfony1.1';

    if (!is_dir($sf_symfony_lib_dir))
    {
      throw new Exception('Unable to find symfony libraries');
    }
  }
}

include($sf_symfony_data_dir.'/bin/symfony.php');

You can now run

symfony1.1 generate:project

in a new directory to have a 1.1 project skeleton built there.

Have fun with it, I’ll post articles about the new form/validation system and upgrading your doctrine schemas to the rewritten sfDoctrinePlugin (that works both in 1.0 and 1.1) soon.

Leave the first comment