Symfony Resources Central

Web development made simple

Wednesday, April 30 2008

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->notifyUntil(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

Monday, April 21 2008

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());
  /* ... */
}

Monday, March 17 2008

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?

Tuesday, February 26 2008

I'd like to hear a Kwatuor play nice symfonic music

Today's post is a bit special.

This can be took as a question.

Or a call to developpers that have specific blogging needs.

Since quite a moment I used dotclear for blogging. That suit my needs, in some way, but maybe I'm more adaptating my needs to dotclear's capabilities. Maybe you're using wordpress. or any other. And I guess that must be the same for you, thinking for example of integrating one of those all-in-one blogging/cms platforms cleanly in another website, for example, is being more than utopian...

By clean I mean integrating it without having to duplicate the template. Neither having to use all functionalities if you only need a simple article list somewhere... And without being limited if you need to display the headers of those on another website...

I'd better not speak of blog networks communicating, or taking content from RSS/XML/anything feed in a flexible way.

So today I'd like to announce the birth of Kwatuor. Kwatuor is a blog platform project using symfony and doctrine, that will in the near future use doctrine migrations to get content from an existing dotclear/wordpress project, or any other source platform someone has enough need with he'd take the time to write migration classes for.

Templating system will be different. I'm still hesitating between a generator approach (generated partials from a dynamic skeleton, that all can be customizable) and a real proper template system (but still any part would be customizable). Only major difference with blogging platform would be the total forbidding of DRY-breaks a dotclear-like templating system is doing everyday. And this extends to integrated blogs, in wider projects.

In fact I started developing it for my own needs, but I think this is typically the kind of project everybody would need someday. Maybe you hate being jailed in your obscure, yet very good, but specific and... even more obscure blog platform.

So I'm wondering now, if people (you :p) would be interested in this project. If so, I'll make a public SVN/trac next week, so concerned users will be able to give feedback with code in their hands. Would this be usefull to you? Would you contribute to this open-source project? Do you have good (or bad :p) ideas about concepts to take in consideration from the beginning?

Related links

Thursday, January 31 2008

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:

Monday, January 7 2008

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.

Sunday, December 30 2007

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.

Monday, December 24 2007

Basic config handler

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 :-)

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.

Sunday, November 4 2007

sfGeshi plugin release

The sfGeshi plugin has been updated today to use latest GeSHi improvements, and to add some features. The SVN path changed too, to comply with symfony-project.com plugin repository naming conventions, so be sure to check out the documentation.

sfGeshi::getLanguages()

This static methods allow you to get an associative array of languages, with GeSHi language identifiers as keys and human readable language names as values.

<?php echo select_tag('language', options_for_select(sfGeshi::getLanguages(), $language)); ?>

sfGeshi::getPluginPath()

This convenience method has been added to allow you to call sfGeshiPlugin directory differently. It should be used if you need direct access to GeSHi files (like language highlighting definition files in /geshi/).

<?php
$files = sfFinder::type('file')->name('*.php')->in(sfGeshi::getPluginPath().'/geshi/');

foreach ($files as $file)
{
  echo $file . '=>' . basename($file, '.php');
}

Tuesday, October 30 2007

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.

Continue reading...

Sunday, October 28 2007

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.

Continue reading...

Sunday, October 21 2007

A new index.php controller for subdomains

The default behaviour of symfony, is to create one myapp.php and one myapp_dev.php public controller by application, knowing that the first application you create will have its prod controller renamed to index.php (default application). But this behaviour can be easily overriden to take advantage of subdomains.

Continue reading...

Wednesday, August 1 2007

sfGeshi plugin

sfGeshi's aim is a symfony plugin that integrates the Generic Syntax Highlighter PHP library (GeSHi) into the Symfony Framework. Supports 75 different languages, and you can add more by writing simple php files.

Related links:

Monday, February 19 2007

Symfony 1.0 is out!

Despite the DIGG side effects of which symfony project server suffered because of heavy traffic brought by the well known social bookmarking site's homepage anouncing symfony's first "stable" release, the long awaited 1.0 version is here!

For thoose who don't know it, Symfony is a MVC (Model-View-Component) PHP5 framework aiming to Rapid Application Development and good codinig practices like the DRY (Don't Repeat Yourself) principle. Their main contributors, french developpers from Sensio Labs Fabien Potencier and François Zaninotto have written a very good documentation book about it, that you can either buy at amazon (for thoose who like holding a real book), or download/read freely on the symfony project website as a PDF file.

Supported by a large community, you'll find support about symfony in diverse flavour, from the symfony forum to different languages mailing lists, going thru #symfony and #symfony-fr (for french developpers) on Freenode IRC network.

As the official release note is saying: At last, the long-awaited 1.0 stable version of symfony is just released. For all those who waited for the "stable" status to dive into symfony, the time has come.

Some reference:

© Copyright daKrazy. All rights reserved. Designed by: hartym@dakrazy