Ce blog — désormais archivé — est en lecture seule. Pour continuer à lire mes tribulations, rendez-vous sur le blog d'Akei, ma société.

Prendre un Café

L'espace d'expression de Nicolas Perriault

Aller au contenu | Aller au menu | Aller à la recherche

mercredi 2 décembre 2009

Saving Search Filters in Symfony's Doctrine Admin Generator

Yesterday I made some consulting in a company where people asked me if it was possible/hard to setup some kind of search filtering persistence in a doctrine-admin-generated module in Symfony. I told them:

Well, it’s a twenty minutes job.

They logically answered me:

Haha, prove it.

Challenge and stress then started.

The examples below are based on the simple model I took for my previous blog post about embedding relations in Doctrine forms, which I will add fancy bookmarks tagging facilities to:

 yaml
# in ./config/doctrine/schema.yml
User:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true
  relations:
    Bookmarks:
      type: many
      class: Bookmark
      local: id
      foreign: user_id
      onDelete: CASCADE

Bookmark:
  actAs:
    I18n:
      fields: [name]
      actAs:
        Sluggable:
          fields: [name]
          uniqueBy: [name, lang]
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true
    url:
      type: string(255)
      notnull: true
    user_id:
      type: integer(4)
      notnull: true
  relations:
    User:
      type: one
      local: user_id
      foreign: id
    Tags:
      class: Tag
      refClass: BookmarkTag
      local: bookmark_id
      foreign: tag_id
      foreignAlias: Bookmarks

Tag:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true

BookmarkTag:
  columns:
    bookmark_id:
      type: integer(4)
      primary: true
      notnull: true
    tag_id:
      type: integer(4)
      primary: true
      notnull: true

No need to say you should rebuild your model, right?

Updated fixtures file:

 yaml
# in ./data/fixtures/fixtures.yml
User:
  niko:
    name: niko

Bookmark:
  niko_bookmark1:
    User: niko
    name: Slashdot
    url: http://slashdot.org/
    Tags: [geek_tag, tech_tag, php_tag]
  niko_bookmark2:
    User: niko
    name: Delicious
    url: http://delicious.com/
    Tags: [geek_tag, tech_tag]
  niko_bookmark3:
    User: niko
    name: Digg
    url: http://digg.com/
    Tags: [geek_tag, php_tag]

Tag:
  geek_tag:
    name: geek
  php_tag:
    name: php
  tech_tag:
    name: tech

Generate the Bookmark admin

Let’s generate a backend app and a Bookmark admin module:

$ ./symfony generate:app backend
$ ./symfony doctrine:generate-admin backend Bookmark

Now let’s enhance a bit our admin by modifying the generator.yml file:

 yaml
generator:
  class: sfDoctrineGenerator
  param:
    model_class:           Bookmark
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              Bookmark
    plural:                Bookmarks
    route_prefix:          bookmark
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~
      fields:  ~
      list:
        display: [=name, url, User]
      filter:  ~
      form:    ~
      edit:    ~
      new:     ~

You should be able to browse the generated bookmarks admin interface:

basic.png

Storing filters in a dedicated Doctrine table, and managing them from the controller

We’ll use Doctrine to store saved filters, so let’s define a new Doctrine table definition in our schema.yml file to store stored filters:

 yaml
SavedFilter:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
    type:
      type: enum
      values: [Bookmark, User]
      notnull: true
    filter:
      type: string()

Of course, still no need to say that you have to rebuild your model, right?

Okay, now we’re going to save the serialized filter values in the filter column, the name one will provide a convenient way to reference a filter set. The type column will reference the Doctrine table familly of the filtered object. Nothing difficult here.

In the admin generator module, the filters are storedin the tableName.filters attribute of the user session (where tableName is the name of the admin module where the filter parameters are operated[1]).

So let’s add a new executeSaveFilter() method in the bookmarkActions controller. And while we’re at it, let’s also add executeLoadFilter() and executeDeleteFilter() methods as well:

 php
<?php
# in apps/backend/modules/bookmark/actions/actions.class.php
class bookmarkActions extends autoBookmarkActions
{
  public function executeDeleteFilter(sfWebRequest $request)
  {
    $this->forward404Unless($filter = Doctrine::getTable('SavedFilter')->findOneByTypeAndId('Bookmark', $request->getParameter('id')), sprintf('Bookmark filter #%d not found', $request->getParameter('id')));
    
    $filter->delete();
    
    $this->getUser()->setFlash('notice', sprintf('Bookmark saved filters "%s" deleted', $filter->getName()));
    
    $this->redirect('bookmark');
  }

  public function executeLoadFilter(sfWebRequest $request)
  {
    $this->forward404Unless($filter = Doctrine::getTable('SavedFilter')->findOneByTypeAndId('Bookmark', $request->getParameter('id')));
    $this->setFilters(unserialize($filter->getFilter()));
    
    $this->getUser()->setFlash('notice', sprintf('Bookmark saved filters "%s" loaded', $filter->getName()));
    
    $this->redirect('bookmark');
  }
  
  public function executeSaveFilter(sfWebRequest $request)
  {
    $name = trim($request->getGetParameter('name'));
    $savedFilter = new SavedFilter();
    $savedFilter->fromArray(array(
      'name'   => $name ? $name : 'Untitled filter',
      'type'   => 'Bookmark',
      'filter' => serialize($this->getUser()->getAttribute('bookmark.filters', array(), 'admin_module')),
    ));
    $savedFilter->save();
    
    $this->getUser()->setFlash('notice', 'Bookmark filters saved');
    
    $this->redirect('bookmark');
  }
}

Of course, we’ll need to add the corresponding routes to our routing.yml file:

 yaml
# in apps/backend/config/routing.yml
bookmark_filter_delete:
  url: /bookmark/filter/:id/delete
  param: { module: bookmark, action: deleteFilter }
  requirements:
    id: \d+

bookmark_filter_load:
  url: /bookmark/filter/:id/load
  param: { module: bookmark, action: loadFilter }
  requirements:
    id: \d+

bookmark_filter_save:
  url: /bookmark/filter/save
  param: { module: bookmark, action: saveFilter }

Wait, we don’t have any link to save a filter from the admin interface! Let’s add one next to the Reset link of the filters column by overriding the _filters.php generated partial template:

 php
// in apps/backend/modules/bookmark/templates/_filters.php from line 11
[...]
<tfoot>
  <tr>
    <td colspan="2">
      <?php echo $form->renderHiddenFields() ?>
      <a href="<?php echo url_for('@bookmark_filter_save') ?>" onclick="document.location = this.href+'?name='+prompt('Enter a name:');return false">
        <?php echo __('Save') ?>
      </a>
      <?php echo link_to(__('Reset', array(), 'sf_admin'), 'bookmark_collection', array('action' => 'filter'), array('query_string' => '_reset', 'method' => 'post')) ?>
      <input type="submit" value="<?php echo __('Filter', array(), 'sf_admin') ?>" />
    </td>
  </tr>
</tfoot>
[...]

Notice that a javascript prompt will ask you for a name before saving a filter set:

prompt.png

So we can now save a filter set in our database. Now, what about listing them below the filters form?

Listing existing saved filters

To me, the best suited place to retrieve saved filtered searches is the bookmarkGeneratorConfiguration class, which has been generated in the lib/ subfolder of the bookmark admin module. Let’s add a new getSavedFilters() method to it:

 php
<?php
<?php
# in apps/backend/modules/bookmark/lib/bookmarkGeneratorConfiguration.class.php
class bookmarkGeneratorConfiguration extends BaseBookmarkGeneratorConfiguration
{
  public function getSavedFilters()
  {
    return Doctrine::getTable('SavedFilter')
      ->createQuery()
      ->where('type = ?', 'Bookmark')
      ->execute()
    ;
  }
}

So in the _filters partial template, which has already access to a generator configuration instance, we’re now able to iterate over retrieved saved filter objects to list them:

 php
// in apps/backend/modules/bookmark/templates/_filters.php from line 11
  [...]
  <tr>
    <td colspan="2">
      <h3><?php echo __('Saved filters') ?></h3>
      <?php if (count($savedFilters = $configuration->getSavedFilters())): ?>
      <ul>
      <?php foreach ($savedFilters as $filter): ?>
        <li>
          <a href="<?php echo url_for('@bookmark_filter_load?id='.$filter['id']) ?>">
            <?php echo $filter['name'] ?>
          </a>
          (<a href="<?php echo url_for('@bookmark_filter_delete?id='.$filter['id']) ?>"></a>)
        </li>
      <?php endforeach; ?>
      </ul>
      <?php else: ?>
        <p>No filters saved</p>
      <?php endif; ?>
    </td>
  </tr>
</tbody>

So you can now save and list filters, load and run them against your objects list, and delete existing ones. If you thoroughly followed the steps of this tutorial, you should now see something like this below the filters form:

withlist.png

Twenty minutes, job done. Even if very quick and dirty.

Conclusion

Yes, I can hear you Symfony nerds, this could be heavily refactored, enhanced and maybe abstracted to provided generic filtering storage accross every generated admin module, but in 20 minutes? Really? ;-) Then, I’d say…

Haha, prove it :-)

Notes

[1] I’m not definitely sure of this, but who really cares?

dimanche 29 novembre 2009

Embedding Relations in Forms with Symfony 1.3 and Doctrine

Symfony 1.3 and 1.4 have been released some days ago in RC2 and you should really take a look at it, because they improve a lot the way you work with the framework, especially the forms one. It’s been a couple of days I started to implement a new bookmarks management feature on a project I’m working on currently, and the new model relationship embedding feature of 1.3’s forms framework just saved me a lot of days.

Here’s a quick and dirty example on how to setup a willingly simplistic bookmarks management system using it

The schema

Here’s the naive Doctrine schema I’ll use for this example:

 yaml
# in config/doctrine/schema.yml
User:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true
  relations:
    Bookmarks:
      type: many
      class: Bookmark
      local: id
      foreign: user_id
      onDelete: CASCADE

Bookmark:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true
    url:
      type: string(255)
      notnull: true
    user_id:
      type: integer(4)
      notnull: true
  relations:
    User:
      type: one
      local: user_id
      foreign: id

As you can see, it’s really naive. Anyway.

Some fixtures

What would be a Doctrine schema without fixtures? Quite nothing I guess, so here we go:

 yaml
# in data/fixtures/fixtures.yml
User:
  niko:
    name: niko

Bookmark:
  niko_bookmark1:
    User: niko
    name: Slashdot
    url: http://slashdot.org/
  niko_bookmark2:
    User: niko
    name: Delicious
    url: http://delicious.com/
  niko_bookmark3:
    User: niko
    name: Digg
    url: http://digg.com/

Building stuff

You guessed it, after having suited the config/databases.yml file to set up a database of our choice, we can now build the database, all the classes we need and load the previously defined fixtures:

$ ./symfony doctrine:build --all --and-load

A basic user’s bookmarks management form

What we want do do now is to manage one User’s bookmarks in a single form. Let’s do it now in a new UserBookmarksForm.class.php file where we’ll build a form extending the autogenerated UserForm one:

 php
<?php
// lib/form/doctrine/UserBookmarksForm.class.php
class UserBookmarksForm extends UserForm
{
  public function configure()
  {
    // We don't want to edit the User object
    unset($this['name']);

    // Existing bookmark forms
    $this->embedRelation('Bookmarks');
    
    $this->widgetSchema->setNameFormat('user_bookmarks[%s]');
  }
}

All the magic is done by calling the embedRelation() method here: all BookmarkForm instances will be embedded and managed automatically in and by our form.

Let’s use a simple controller to manage the form[1]:

 php
<?php
class testActions extends sfActions
{
  public function executeBookmarks(sfWebRequest $request)
  {
    $this->form = new UserBookmarksForm($user = Doctrine::getTable('User')->findOneByName('niko'));
    if ($request->isMethod('post') && $this->form->bindAndSave($request->getParameter('user_bookmarks')))
    {
      $this->getUser()->setFlash('notice', 'Bookmarks list updated');
      $this->redirect('test/index');
    }
  }
}

And a basic template:

 php
<form action="." method="post">
  <?php echo $form->renderHiddenFields() ?>
  <?php echo $form->renderGlobalErrors() ?>
  <table>
    <?php echo $form ?>
    <tr>
      <td></td>
      <td><input type="submit"/></td>
    </tr>
  </table>
</form>

You should see something like this:

simple.png

The form is functional, you can edit several bookmarks at one. Neat? But wait, we can’t add a new one!

Embedding a bookmark creation form

Let’s enhance our form by embedding an empty BookmarkForm form instance in order to add a new bookmark:

 php
<?php
// lib/form/doctrine/UserBookmarksForm.class.php
class UserBookmarksForm extends UserForm
{
  public function configure()
  {
    unset($this['name']);
    
    // Bookmark creation form
    $newBookmarkForm = new BookmarkForm();
    $newBookmarkForm->setDefault('user_id', $this->object->id);
    $this->embedForm('new', $newBookmarkForm);
    
    // Existing bookmark forms
    $this->embedRelation('Bookmarks');
    
    $this->widgetSchema->setNameFormat('user_bookmarks[%s]');
  }
  
  protected function doBind(array $values)
  {
    if ('' === trim($values['new']['name']) && '' === trim($values['new']['url']))
    {
      unset($values['new'], $this['new']);
    }
    
    parent::doBind($values);
  }
}

Here I just override the doBind() method to remove the bookmark creation embedded form if nothing has been submitted by the user in its fields; that’s probably because he just wants to edit existing bookmarks[2].

By refreshing the page you should now be able to see the new form:

withAdd.png

So now you’re able to add a new Bookmark and/or edit existing instances within the same simple form. Neat? Wait, we can’t delete existing bookmarks!

Deleting existing bookmarks

So you would like to have a checkbox next to every existing bookmark embedded form to schedule its deletion on saving the form? Wow, that’s getting tricky, I like that.

The Symfony forms framework has evolved a lot, but what we’re trying to achieve here will involve some fine-tunning. Don’t be too much afraid seeing the code ;)

First, we’ll have to add the checkbox widget to the BookmarkForm form, but only if an existing Bookmark object has been bound to it:

 php
<?php
// lib/form/doctrine/BookmarkForm.class.php
class BookmarkForm extends BaseBookmarkForm
{
  public function configure()
  {
    $this->widgetSchema['user_id'] = new sfWidgetFormInputHidden();
    $this->validatorSchema['url'] = new sfValidatorAnd(array(
      new sfValidatorString(array('max_length' => 255)),
      new sfValidatorUrl(),
    ));
    
    if ($this->object->exists())
    {
      $this->widgetSchema['delete'] = new sfWidgetFormInputCheckbox();
      $this->validatorSchema['delete'] = new sfValidatorPass();
    }
  }
}

Refreshing the form page should display something like that:

withAddAndDelete.png

The UserBookmarksForm now holds this code:

 php
<?php
// lib/form/doctrine/UserBookmarksForm.class.php
class UserBookmarksForm extends UserForm
{
  /**
   * Bookmarks scheduled for deletion
   * @var array
   */
  protected $scheduledForDeletion = array();  
  
  /**
   * Configures the form
   *
   */
  public function configure()
  {
    unset($this['name']);
    
    // Bookmark creation form
    $newBookmarkForm = new BookmarkForm();
    $newBookmarkForm->setDefault('user_id', $this->object->id);
    $this->embedForm('new', $newBookmarkForm);
    
    // Existing bookmark forms
    $this->embedRelation('Bookmarks');
    
    $this->widgetSchema->setNameFormat('user_bookmarks[%s]');
  }
  
  /**
   * Here we just drop the bookmark embedded creation form if no value has been 
   * provided for it (it somewhat simulates a non-required embedded form)
   *
   * @see sfForm::doBind()
   */
  protected function doBind(array $values)
  {
    if ('' === trim($values['new']['name']) && '' === trim($values['new']['url']))
    {
      unset($values['new'], $this['new']);
    }
    
    if (isset($values['Bookmarks']))
    {
      foreach ($values['Bookmarks'] as $i => $bookmarkValues)
      {
        if (isset($bookmarkValues['delete']) && $bookmarkValues['id'])
        {
          $this->scheduledForDeletion[$i] = $bookmarkValues['id'];
        }
      }
    }
    
    parent::doBind($values);
  }
  
  /**
   * Updates object with provided values, dealing with evantual relation deletion
   *
   * @see sfFormDoctrine::doUpdateObject()
   */
  protected function doUpdateObject($values)
  {
    if (count($this->scheduledForDeletion))
    {
      foreach ($this->scheduledForDeletion as $index => $id)
      {
        unset($values['Bookmarks'][$index]);
        unset($this->object['Bookmarks'][$index]);
        Doctrine::getTable('Bookmark')->findOneById($id)->delete();
      }
    }

    $this->getObject()->fromArray($values);
  }
  
  /**
   * Saves embedded form objects.
   *
   * @param mixed $con   An optional connection object
   * @param array $forms An array of forms
   */
  public function saveEmbeddedForms($con = null, $forms = null)
  {
    if (null === $con)
    {
      $con = $this->getConnection();
    }

    if (null === $forms)
    {
      $forms = $this->embeddedForms;
    }
    
    foreach ($forms as $form)
    {
      if ($form instanceof sfFormObject)
      {
        if (!in_array($form->getObject()->getId(), $this->scheduledForDeletion))
        {
          $form->saveEmbeddedForms($con);
          $form->getObject()->save($con);
        }
      }
      else
      {
        $this->saveEmbeddedForms($con, $form->getEmbeddedForms());
      }
    }
  }
}

The code should be self-explanatory… or not. But anyway, you should now be able to add a new bookmark and delete existing ones as well, in a single form and process, and we’re still using the very same controller from the beginning!

Okay, let’s admit it, we’re reaching the limits of Symfony and probably those of my knowledge of it as well, but… IT WORKS.

But, what about the templating?

As of now we’ve used the convenient <?php echo $form ?> trick, but we now want to have full fine-grained control over the way our embedded form fields will look like.

Let’s update the form template accordingly:

 php
<form action="." method="post">
  <?php echo $form->renderHiddenFields() ?>
  <?php echo $form->renderGlobalErrors() ?>
  <!-- Embedded new bookmark form -->
  <fieldset>
    <legend><?php echo __('Create a new bookmark') ?></legend>
    <?php echo $form['new']->renderError() ?>
    <div class="form-row">
      <?php echo $form['new']['name']->renderLabel() ?>
      <div class="form-field">
        <?php echo $form['new']['name']->render() ?>
        <?php echo $form['new']['name']->renderError() ?>
      </div>
    </div>
    <div class="form-row">
      <?php echo $form['new']['url']->renderLabel() ?>
      <div class="form-field">
        <?php echo $form['new']['url']->render() ?>
        <?php echo $form['new']['url']->renderError() ?>
      </div>
    </div>
  </fieldset>
  <!-- /Embedded new bookmark form -->
  <!-- Embedded existing bookmark forms -->
  <?php foreach ($form['Bookmarks'] as $i => $eForm): ?>
    <fieldset>
      <legend><?php echo sprintf(__('Edit bookmark #%d'), $i+1) ?></legend>
      <?php echo $eForm->renderError() ?>
      <div class="form-row">
        <?php echo $eForm['name']->renderLabel() ?>
        <div class="form-field">
          <?php echo $eForm['name']->render() ?>
          <?php echo $eForm['name']->renderError() ?>
        </div>
      </div>
      <div class="form-row">
        <?php echo $eForm['url']->renderLabel() ?>
        <div class="form-field">
          <?php echo $eForm['url']->render() ?>
          <?php echo $eForm['url']->renderError() ?>
        </div>
      </div>
      <div class="form-row">
        <div class="form-field">
          <?php echo $eForm['delete']->render() ?>
          <?php echo $eForm['delete']->renderError() ?>
          <?php echo $eForm['delete']->renderLabel(__('Delete this bookmark')) ?>
        </div>
      </div>
    </fieldset>
  <?php endforeach; ?>
  <!-- /Embedded existing bookmark forms -->
  <input type="submit" value="<?php echo __('Update your bookmarks') ?>"/>
</form>

Now you can really control the semantics of the HTML code of the form, field by field.

As always, if you have better solutions in mind, feel free to post them in the comments.

Notes

[1] I’ll leave you to create an app, module and route, okay?

[2] Of course this can be a lot improved, but the example is kept as simple as possible to ease understanding.

mercredi 4 novembre 2009

An Interactive PHP Shell: phpsh

Just found this nice project contributed by the Facebook team, phpsh. Basically, it’s an interactive and advanced command line interface to php, a kind of super-php -r similar to what you can find in Python or Ruby. Ironically enough, phpsh is mostly written in Python, by the way.

To install phpsh, just get it from github[1]:

$ git clone git://github.com/facebook/phpsh.git
$ cd phpsh
$ python setup.py build
$ sudo python setup.py install

To run phpsh:

$ phpsh
Starting php
type 'h' or 'help' to see instructions & features
php> ="hello world"
hello world
php> =2 + 2
4
php> $a = 8

php> =$a
8

Note that you don’t have to open or close <?php tags, you can print something just by prepending an = sign to the command, and no need to type semicolum at the end of a call. Easy[2].

You can access a function documentation by just prepending the d keyword to its name:


php> d strlen

# strlen

(PHP 4, PHP 5)

strlen -- Get string length

### Description

int strlen ( string $string )

Returns the length of the given string . 

### Parameters

string     

The [string][1] being measured for length. 

### Return Values

The length of the string on success, and 0 if the string is empty. 

### 

   [1]: #language.types.string

You can define your own classes and functions, and run them:

php> function foo($a){echo $a.'!';}
php> foo('bar')
bar!

Same goes for classes:

php> class Foo {public function bar($a){echo $a.'!';}}
php> $f = new Foo()
php> $f->bar('baz')
baz!

You can even execute shell command from there:

php> ! ls -la

Of course, you can import include and require files. As a concrete example, let’s roughly play with the symfony API:

php> ! symfony -V
symfony version 1.2.2-DEV (/Users/niko/Sites/vendor/symfony12/lib)
php> c /Users/niko/Sites/vendor/symfony12/lib/autoload/sfCoreAutoload.class.php
Extra includes are: ['/Users/niko/Sites/vendor/symfony12/lib/autoload/sfCoreAutoload.class.php']
php> sfCoreAutoload::register()
php> =sfYaml::load('foo: bar')
array(
  "foo" => "bar",
)
php> =sfYaml::dump(array('foo' => array('bar' => 'baz')))
"foo:\n  bar: baz\n"

Last but not least, when enough playing, type q or press ctrl + d to quit phpsh.

Notes

[1] So yeah, so you need git. And Python, of course.

[2] Anybody putting "rather use python then" will have serious troubles, even if I strongly agree.

lundi 12 octobre 2009

A Symfony 1.3 Gem: Open Files Listed in Exceptions with the Editor of your Choice

I’ve just stumbled upon a nice new feature of Symfony 1.3, the ability to open any linked file within standard exception page with the text editor of your choice, at least if it provides an url scheme/protocol to open them. Texmate provides natively this feature, so let’s see how to configure a symfony project to allow its files to be opened directly in textmate when encountering a stack trace.

In the config/ folder of the project, create a settings.yml file with this content:

 yml
dev: #yeah, we never know
  .settings:
    file_link_format: "txmt://open?url=file://%f&line=%l"

That’s it. Now any standard exception page (in dev environment only, right?) will provide a txmt:// link to every PHP file listed in the stack trace. And at the correct line number. Neat.

lundi 12 octobre 2009

Scrum.py, présentation et conférence Scrum et Python le 23 octobre à Montpellier

Si comme moi vous effectuez une veille quotidienne autour des outils et technologies Web, vous n’avez certainement pas pu passer à côté de l’engouement massif pour le langage Python ces derniers temps. De plus en plus de développeurs PHP passent sur ce langage[1], souvent par l’entremise de l’excellent framework Django, que présentera mon camarade de jeu David Larlet le vendredi 23 octobre prochain à Montpellier à l’occasion d’une conférence donnée dans le cadre de l’évènement Scrum.py.

L’efficacité potentielle du meilleur outil technique étant réduit à néant s’il n’est pas efficacement encadré par une méthodologie de conduite de projet adapté aux contraintes d’un métier souvent difficile, Claude Aubry, un des tous meilleurs experts français sur le sujet, présentera quand à lui les avantages et intérêt de Scrum durant cette même journée d’information gratuite, à laquelle je vous invite à vous inscrire en ligne dès à présent.

David proposera également un atelier Django les 18, 19 et 20 novembre prochains, tandis que Claude animera une formation Scrum les 2, 3 et 4 décembre.

L’évènement est organisé par le collectif Particul.es, et les places, tant pour les conférences que pour les formations, sont limitées ; alors n’hésitez pas à vous inscrire rapidement.

Notes

[1] Et j’avoue me réfréner fortement à faire de même tant les inconsistances de PHP me portent quotidiennement sur les nerfs

mardi 6 octobre 2009

Simple Continuous Integration of a Symfony Project using Hudson

I love tests, I just cannot program without them anymore, especially with Symfony. And as I write a lot of them on a daily basis, the full test suite can take a very long time to be executed ; running a symfony test:all command before every granular commit suppose you have to wait sometimes more than 5, 10 minutes or more for the whole tests to be ran: hardly acceptable. Post commit hooks can be a solution, but what if a lot of devs are working simultaneously on the same project? Added to the previously seen test execution duration, it can become a problem difficult to deal with.

Here comes continuous integration : regularly, eg. every hour, the symfony project will be built up and configured from scratch, then the full test suite will be executed and the resulting log will be aggregated. It’s a very convenient way to keep an eye on the overall code quality and integrity of the project.

There are several open source continuous integration software available on the market: Cruise Control (and phpUnderControl), Continuum, Integrity, the uncertain but awesomely looking Sismo which powers the Symfony continous integration server… But I recently had the opportunity to test Hudson, a java based one. It’s very simple to install, setup and configure, and has tons of plugins. So let’s see how it can be used to test a Symfony project.

img hudson_tests_weather

Hudson Installation

That’s really not the hardest part, because you just need a working JRE 1.5 installation on your machine, and to retrieve the latest version of the program.

Then, you can launch it directly from a shell prompt:

$  java -jar /path/to/hudson.war

If you fear to break something or just want to give it a go without the hassle of firing a term, just launch the available Java Web Start version.

On debian/ubuntu, it’s just as easy as:

$ sudo echo deb http://hudson-ci.org/debian binary/ >> /etc/apt/sources.list
$ sudo apt-get update
$ sudo apt-get install hudson
$ sudo /etc/init.d/hudson start

Configuration and Symfony Project Integration

Once Hudson is installed an running, head up to http://localhost:8080/ and start playing with the web based user interface of Hudson. The navigation and configuration forms are quite obvious, and therefore efficient. Creating a project following the provided guidelines is easy and can be achieved within minutes:

First, create a new Job, choosing the Build a free-style software project option.

Then, configure the subversion repository[1] used by your project by entering its base URL in the Source Code Management field You can schedule builds, watch for SCM activity and even trigger builds from remote script using a neat XMLRPC interface[2].

img hudson_svn

img hudson_hudson_scheduling

Configuring the building process is as easy as writing down some commands, like the one you’d execute to setup your project on a new box:

img hudson_build_commands

As of Symfony 1.3, test result logs can be exported in a jUnit XML file, so Hudson will be able to parse them and provide some useful reports, metrics and charts:

huson_test_results.png

Of course, you can configure failure notifications: email, atom feed, there’s even a twitter plugin!

As a conclusion, Hudson is a very simple but efficient continous integration tool which can easily be configured to monitor the quality of your Symfony projects… at least if you write tests ;)

Notes

[1] If you’re not using Subversion, lot of plugins are available for other SCM in the huge Hudson plugins repository

[2] Useful if you wish to use post-commit build hook

mardi 15 septembre 2009

Optimize your Doctrine Workflow with Specialized Queries

I’m currently working on a big Symfony project, with a lot of Doctrine models and complex queries to write. I found a way to organize all of them in an object-oriented and cleaner way than using the traditionnal addNamedQuery() and createNamedQuery() methods workflow[1].

The idea is to create dedicated query classes for a given model ; this way, you can provide useful methods to build the business-related parts of your query.

As usual, the theory is more understandable with a concrete example. Let’s consider this simple Doctrine model[2] :

Disclaimer: The provided examples have been written in a hurry, so mistakes might have been not detected by my attentive proof-reading ;)

 yaml
BlogAuthor:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true  
    name:
      type: string(255)
  relations:
    Post:
      type: one
      class: BlogPost
      local: id
      foreign: author_id

BlogPost:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    author_id:
      type: integer(4)
      notnull: true
    title:
      type: string(255)
    content:
      type: string(65535)
  relations:
    Author:
      type: one
      class: BlogAuthor
      local: author_id
      foreign: id
    Comments:
      type: many
      class: BlogComment
      local: id
      foreign: post_id

BlogComment:
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    post_id:
      type: integer(4)
      notnull: true
    author:
      type: string(255)
    content:
      type: string(5000)
  relations:
    Post:
      type: one
      class: BlogPost
      local: post_id
      foreign: id

Now let’s imagine a Query class dedicated to query the BlogPost table:

 php
<?php 
class BlogPostQuery extends Doctrine_Query
{
  static public function create($conn = null, $class = null)
  {
    return parent::create($conn, 'BlogPostQuery')
      ->from('BlogPost p');
  }
  
  public function addPosts($fields = 'p.*')
  {
    return $this->addSelect('p.*');
  }
  
  public function addComments($fields = 'c.*')
  {
    return $this
      ->addSelect($fields)
      ->leftJoin('p.Comments c')
      ->addGroupBy('c.id');
  }
  
  public function addAuthors($fields = 'a.*')
  {
    return $this
      ->addSelect($fields)
      ->leftJoin('p.Author a')
      ->addGroupBy('a.id');
  }
  
  public function addCommentsCount($alias = 'nb_comments')
  {
    return $this
      ->addSelect(sprintf('COUNT(c.id) as %s', $alias))
      ->addGroupBy('c.id');
  }
  
  public function filterByAuthorName($authorName)
  {
    return $this
      ->andWhere('a.name = ?', $authorName);
  }
}

So how can we use this query object? Here are some sample uses:

 php
// Retrieve all posts
$posts = BlogPostQuery::create()
  ->addPosts()
  ->fetchArray();

// Retrieve all posts with comments
$posts = BlogPostQuery::create()
  ->addPosts()
  ->addComments()
  ->fetchArray();

// Retrieve all posts with comments and their count per post
$posts = BlogPostQuery::create()
  ->addPosts()
  ->addComments()
  ->addCommentsCount('yataa')
  ->fetchArray();

// Retrieve all post with chuck as its author and related comments
$posts = BlogPostQuery::create()
  ->addAuthors()
  ->addPosts()
  ->addComments()
  ->filterByAuthorName('chuck')
  ->fetchArray();

// and so on...

Of course, this example of use is not really relevant as our model is really simple, but when you’re dealing with dozens of internationalized objects, it can help cleaning your model classes, controllers and improving the organization of your work.

Update and important precisions

Some people are having negative feedback regarding this technique, claiming it will encourage people using the custom query object directly in the controllers; that’s absolutely not the case as the queries are to be used only within the model layer, for example in the BlogPostTable class:

 php
<?php
class BlogPostTable extends Doctrine_Table
{
  static public function getPostsWithCommentsByAuthor($authorName)
  {
    return BlogPostQuery::create()
      ->addPosts()
      ->addComments()
      ->filterByAuthorName($authorName)
      ->fetchArray()
    ;
  }
}

And in a controller:

 php
class blogActions extends sfActions
{
  public function executeListByAuthor(sfWebRequest $request)
  {
    $this->posts = BlogPostTable::getPostsWithCommentsByAuthor($request->getParameter('author'));
  }
}

Notes

[1] … or raw queries written directly within controllers, but you may know that this is really bad ;)

[2] I’m using Doctrine 1.2 beta (bundled with upcoming symfony 1.3) in the provided example.

vendredi 4 septembre 2009

30 Symfony Best Practices, the slides from my talk at SymfonyDay Cologne '09

Hey there, it’s been a while, huh?

Today I gave a talk about Symfony best practices at the Symfony Day event in Cologne, Germany; you can get the slides on slideshare or directly browse them below:

The Symfony Day event has been purely awesomely incredibly well organized, many kudos and thanks to Interlutions and to all the attendees. You’re all great people. Thanks.

Symfony Day '09 Cologne

- page 2 de 73 -