The blog of COil : PHP, symfony & Web 2.0

Strangebuzz...?

Réduire au titre / collapse all

13/09/2009

» New 1.2 symfony plugin + tutorial: sfTaskLoggerPlugin

Hi symfonians ! ^^

Again, that's quiet a long i didn't post something on symfony. Well i suppose releasing a new is a good occasion for this. Let me introduce the sfTaskLoggerPlugin plugin:

The sfTaskLoggerPlugin plugin allows you to run tasks and store the results. Results are stored in the database in a specific table and also in a log file. Each task has its own log file, witch is stored in a specific directory depending on its namespace and name. (`/log/tasks/:TASK_NAMESPACE/:TASK_NAME`).

The database record stores the following informations:

  • Options of the task
  • Arguments of the task
  • An error code
  • Start and end time
  • A success flag
  • The log file path
  • Extra comments (for admin)

It's very useful, I've already used on several project i worked on (from 1.0 to 1.2). You to have a clean and "easy to access" historic (through an admin gen module for example) of all run tasks and their results. How to use it ? Well Very easy !!

Note: The plugin is Doctrine and Propel friendly, it you are using Doctrine, the /lib/config/doctrine/schema.yml will be used whereas using Propel the /lib/config/schema.yml will be used.

Installation

  • Install the plugin
       $ symfony plugin:install sfTaskLoggerPlugin


(or download it and unzip in your /plugins directory)

  • Clear you cache
       $ symfony cc


Configuration


The plugin comes with a base task class witch is named sfBaseTaskLoggerTask Therefore your tasks must extend this one. Because there is no autoloading at the task level, one must include the base class manually:

   require_once(dirname(FILE). '/sfBaseTaskLoggerTask.class.php');

Note: Of course you will have to change this path depending on where is located your task. For example if it is located in the `/lib/task` folder of your project, the include directive should look like this:

   require_once(dirname(FILE). '/../../plugins/sfTaskLoggerPlugin/lib/task/sfBaseTaskLoggerTask.class.php');


Usage


1 - Create a new class that extends the plugin base class:


<?php
class sfTaskLoggerSampleTask extends sfBaseTaskLoggerTask
?>


2 - Implement the configure() method as you would do with a standard task:


[php]
<?php
/**
 * Main task configuration.
 */
protected function configure()
{
  $this->addArguments(array(
    new sfCommandArgument('arg_1', sfCommandArgument::OPTIONAL, 'Test argument 1', 'arg_1_value'),
    new sfCommandArgument('arg_2', sfCommandArgument::OPTIONAL, 'Test argument 2', 'arg_2_value'),
  ));

  $this->addOptions(array(
    new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'Environment used', 'prod'),
    new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'Application used', 'frontend'),
  ));

  $this->namespace = 'sf_task_logger';
  $this->name      = 'sample';

  $this->briefDescription = 'This is a sample task !';

  $this->detailedDescription = <<<EOF
The task [sf_task_logger:sample|INFO] doesn't do that much.
It logs itself in the database and in the file system:

  [./symfony sf_task_logger:sample --env=prod|INFO]
EOF;
}
?>


Now there are 2 specific methods to implement:

3 - checkParameters()


[php]
<?php

        /**
         * Advanced check of task parameters.
         */
        protected function checkParameters($arguments = array(), $options = array())
        {
          /* // Stupid example test
          if ($this->args['arg_1'] != 'arg_1_value')
          {
            throw new InvalidArgumentException('The value for argument 1 is not valid ! Check the help of the task.');
          }
          */
    
          return true;
        }
?>


Note: This method can be usefull if you have advanced controls to do on task parameters or arguments. Just return `true` if you don't have to use it.

4 - doProcess()


[php]
<?php
        /**
         * Main task process.
         */
        protected function doProcess()
        {
          try
          {
            $this->printAndLog(' - This is a log info !!');
            $this->task->setErrorCode(self::ERROR_CODE_SUCCESS);
            $this->setOk();
          }
          catch (Exception $e)
          {
            $this->task->setErrorCode(self::ERROR_CODE_FAILURE);
            $this->setNOk($e);
          }
        }
?>


Note: This is the main method of your task process. `$this->task` is the database object that will be saved. As you can see the `setOk()` and `setNOk` methods allow to set the flag of the record automatically depending on the success or failure of the task.

If you want more control on the task process you can also re-implement the `execute()` method of the base class witch is responsible for calling all others sub functions:

[php]
<?php
    /**
     * Global process of the task.
     *
     * @see sfTask
     */
    protected function execute($arguments = array(), $options = array())
    {
      $this->setParameters($arguments, $options);
    
      $this->checkParameters($arguments, $options);
    
      $this->initDatabaseManager();
    
      $this->initLogger();
    
      $this->logStart();
    
      $this->doProcess();
    
      $this->logEnd();
    }
?>


Notes:

The plugin is bundled with a sample task: `/lib/task/sfTaskLoggerSampleTask.class` witch can be run with the following command:

   ./symfony sf_task_logger:sample


TODO

  • Include Propel and Doctrine admin generator module

Support


Please report bugs or feature request on this post.

Changelog


See you. COil ^^

PS: I have published this tutorial quiet quickly, please help me by reporting typos and errors.
PS2: The official README file is far more readable
PS3: As always, any contribution will be welcome !

07/12/2008

» Jobeet: An alternative tutorial for Day 3

Hi symfonians ! ^^

Well, i didn't post very often during these last months. So let's try to write something interesting. In this post i will show you an alternative way to build your database with symfony, propel and the DB4 tool. This tutorial is not really an "alternative" to the official tutorial. :) Let's say that we will just see another way to build our database, i won't be as exhaustive as Fabien did in the Jobeet Day 3 tutorial, therefore, for all details please refer to the official Jobeet tutorial.

Pre-requisites:

  • Having done at least day 1 and 2 of the Jobeet tutorial. (or you already know symfony, in this case you will need a fresh symfony 1.2 project)
  • Not being too angry with Propel :p

What you will learn:

  • Using the sfDB4toPropelPlugin to build your schema.yml without writing a single line of this file.


What you will NOT learn:

  • How wonderful symfony is. For this, read the official Jobeet tutorial of Fabien. :)


So let's go... We will start at this part of the Jobeet 3 tutorial.

Start


1 - Plugin installation


First we will install the sfDB4toPropel plugin, i did not released any package for the symfony 1.2 version yet, so we will install it via SVN. (edit: i've just released the 1.0.2 version for sf 1.2.0)

   $ cd plugins
   $ mkdir sfDB4toPropelPlugin
   $ cd sfDB4toPropelPlugin
   $ svn co http://svn.symfony-project.com/plugins/sfDB4toPropelPlugin/branches/1.2


Be careful not to check out the root of the plugin but the branch related to the symfony version you want to use, actually 1.1 or 1.2)

(PS: You can also set an svn external to the plugin if your project already uses a svn repository)

...

» Lire la suite / read all «

09/09/2008

» new symfony 1.1 / 1.2 plugin + tutorial : sfDB4toPropelPlugin

1 - sfDB4toPropelPlugin presentation


I've just released a new plugin, it is called sfDB4toPropelPlugin, what is this ? Can it make coffee ? Not yet. ;) Well this one add to symfony a new task: propel:db4-to-propel that allows you to convert a DB4 schema (A DBDesigner 4 schema) into a valid propel schema.yml file. It can handle:

  • I18n tables
  • Foreign keys
  • phpNames of tables
  • Name of propel connection
  • Comments for all fields
  • Name of target schema
  • Lib package name
  • And several other options...


You can read a complete tutorial for this plugin in the full version of this post.
Of course, i'll be glad to have some feedback here, to know what you like / dislike and what could be improved.

See you. COil ;)



Related posts:


PS: Reading the related posts, it seems that i did not use the "last version", so i'll check what can be included in the next version of the plugin.

...

» Lire la suite / read all «

04/02/2007

» Snippet : Strip comments of propel classes

[En] In Symfony, comments generated by Propel can sometimes be quiet big. With the 0.6.3 version there was no feature to do this. That's why i made this little batch. We could also imagine extend this snippet to remove all the comments off all php files of an application (for production). If you are using 1.0.0 just add in your "config/propel.ini" (1) :


[Fr] Dans Symfony, les commentaires générés par Propel peuvent parfois être assez gros. Avec la version 0.6.3, il n'y a pas de fonctionnalité pour ne pas les créér. C'est pourquoi j'ai fait ce petit batch. On pourrait aussi imaginer d'étendre ce snippet pour supprimer l'ensembles des commentaires des fichiers php d'une application. (en production). Si vous utilisez la 1.0.0, pas besoin de ce batch cette fonctionnalité est désormais incluse, ajouter dans votre "config/propel.ini" :

(1)

 propel.builder.addIncludes = false
 propel.builder.addComments = false