The blog of COil : PHP, symfony & Web 2.0

Strangebuzz...?

Réduire au titre / collapse all

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)
You plugin folder should now look at this now:

plugin structure


2 - Creating the database


2.1 - Create your database: (using UTF8) (or with PhpMyadmin)


   $ mysqladmin -uroot -pmYsEcret create jobeet


2.2 - Set up the database settings:


   $ php symfony configure:database "mysql:host=localhost;dbname=jobeet" root mYsEcret


(you can leave the password blank)

3 - Using the DB4 tool


3.1 - Install it, check out the instructions on the DB4 website:

Now we are ready to design our database.

3.2 - Updating the database name


1st we need to change the name of the connection that will be used by symfony. The default database name is propel, to use this setting, in DB4 -> main menu -> options -> model option, in this screen put propel for the model name option.

3.3 - Creating the tables


Add a table using the following button (the one at the top)

Create table button


And name this table 'jobs' (we will use plural for tables names but singular for the phpNames like in the official tutorial). Now enter the list of the fields, note that you can:

  • Tell if the field is an auto-increment one
  • Put the default value of the field
  • Add a comment to describe the field

Now let's modify the phpName of the table, fot this, just enter the phpName in the comment field of the table: JobeetJob (if you leave this field blank the default phpName will be used)
Save into the /doc/database/db4.xml file (relative to the root of your project), this is the default path that will use the plugin, so let's keep this path for now. Your jobs table should look like this now:

Fields of the jon table


Note the phpName entered at the bottom.

3.4 - Others tables


Now repeat the operation for the category and affiliate tables. (don't forget the phpName of each table) Your schema should look like this now:

Tables without relations


3.5 - Setting the relations between tables


Now that we have our 3 main tables, it's time to set up the relations. (buttons on the left)

  • Create a 1-n relation from the category table to the job one
  • Create a n-m relation between the category and affiliate tables
  • Double click on the relation between job and category and rename the field to category_id (you can also put a comment and set the onUpdate and onDelete instructions)
  • Rename the relations of the categories_affiliates table to category_id and affiliate_id

Your schema should look like this now:

All Tables


That's it, finally we have our DB4 schema. :) Now let's see how to use it with symfony.

3.6 Generating our schema.yml


Now that we have our db4.xml file we want to generate our schema.yml that will be used by symfony and propel (that's the goal of this tutorial) Launch the following script (chmod +x the file before)

   $ ./plugins/sfDB4toPropelPlugin/bin/db4.sh


In fact this batch will help us re-generating all that we need after a modification on the DB4 schema. But it just does the following task:

  • Converts the db4.xml file into a schema.yml file
  • Launch the propel:build-all-load command
  • Clears the cache

Now open your /config/schema.yml file it should look like the one provided by Fabien but there are some differences:

  • There is an additional section, in the one of fabien, it is not written because the default values are used.
   propel:
     _attributes:
       defaultIdMethod: native
       package: lib.model
  • If you have put comments in your fields, then you also have them in you schema.yml (usefull to quicky remember the use of a field)


   is_public: { type: BOOLEAN, required: true, default: '1', description: 'Tells if the job is public or not' }
  • The id declaration for our 3 main tables is not the same, once again it's a symfony convention, the ~ tells that we will use default settings.
  • Physical tables names are not the same, that's true but that's not a problem, because in your application we will always use the phpNames of the tables and not is physical names.
  • OMG ! No.. There is a big mistake, we don't have unique index on the email field of the Affiliate table and neither on the token field of the Job table, let's see how to correct this.


3.7 - Setting up the index


Open the Job table details with DB4, in the Indices section at the bottom, click on the add button, name your index 'jobs_unique_token' for example. Now drag and drop the token field to the columns section at the bottom right. Save. Launch our db4 batch. If you open your schema.yml you will see a new section for the Job table:

   _uniques: { jobs_unique_token: [token] }


Now repeat the operation for Affiliate email field. Launch the script. Check the results.

4 - Conclusion


As we have seen, with the help of this plugin we were able to create a clean schema.yml file for our project without having to write a single line of code. I am using this plugin for almost 2 years (the 1.0 version was never published), it just works well, especially when you start a new project from scratch. What is great is even if you want to do major modifications on your database at an early stage of your development, you can do it and very quickly. You will save a lot of time.
For the next version, i'd like to see what is possible to do with MySQL Workbench, i did not tested it yet for now but it looks really nice. (the creator of DB4 is now in the MySQL Workbench team) Moreover it would be also nice to be able to do the same thing for Doctrine... If anyone wants to help, your are welcome. ;)


Related posts:



PS: I have published this tutorial quiet quickly, please help me by reporting typos and errors. ;)

09/09/2008

» new symfony 1.1 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 «

18/06/2008

» Allomatch V3 powered by symfony !

Well the V2 was also powered by symfony (V1.0) and the V1 was powered by Joomla. ;) What is Allomatch ? It's a website where you can see the pubs where you can see sports events on television, like actually with the Eurocup 2008. You've got a match, then you have the google map of France, you just have to click on the region or to enter your address to see what is the closest pub were you will be sure to be able to see the match. This V3 mainly adds some "community features", for example you can tell to others members where you will see the match, give you thought on the "match wall", if you like a bar... and so on.

It was a pleasure to work with you, thanks to Fabrice and Benoit and i wish you the best for the future. :)

PS: The Hall's beer tavern the pub of the Paris "sfPot" is one of the Allomatch pubs ! ;)
PS2: Try and test the "Pouet" feature (the counters), one of the most addictive of the site ! ;)

allomatch

02/05/2008

» PHP_Debug V2.1.3 released

This is just a small update to correct and close minor bugs that were on the Pear bug tracker. I have also finally added the sources on the php csv server. The last step will be to do the end user documentation in the DocBook format so it can be available in the official pear documentation.

:)

03/04/2008

» symfony 1.0 tutorial : Extending the admin generator

[En] Tutorial content:

  • Creating a plugin with a custom admin generator theme
  • Extending the sfActions class
  • Extending the sfPropelAdminGenerator class


Here is little contribution for the symfony code sprint, a symfony tutorial about the admin generator. :) Do you know about it ? I think it's one of my favourite symfony tool, i have developed several applications with symfony and for 75% of them i have made a custom admin generator theme. And as said in the symfony documentation, the admin generator is very very very powerful. ;)
In this tutorial we will see a concrete example on how to extend it to provide a useful new feature. Witch feature ? Well it was one of the things a customer asked me, "I want to be able to delete several rows at a time with check boxes" ... Ahhhhh indeed, it's not a native feature of the admin generator. So.... let's do it... :)

::: Pre-requisite :::


Well i will not explain here how to install symfony as there are lots of tutorials about this on the symfony website and in the wiki. So i will assume you have a clean symfony installation so you can type the symfony command in cli. I used the 1.0.13 version for this tutorial.

::: Creating and setting a new project :::


:: Creating the new project ::


First we will create the new project that we will call tutorial, create a new folder tutorial and launch the init-project task into it.

symfony init-project tutorial

Now let's create the backend application:

symfony init-app backend

As it is always better to have a submain for our application add the following in you apache httpd.conf file and change it with your own path

## COil symfony tutorial n°1 : Extending the admin generator ##

<VirtualHost *:80>
  ServerName dev.tutorial.com
  DocumentRoot "C:\wamp\www\tutorial\web"
  DirectoryIndex index.php
  Alias /sf "c:\wamp\bin\php\php5.2.5\PEAR\data\symfony\web\sf"
  
  <Directory "C:\wamp\www\tutorial\web">
    AllowOverride All
  </Directory>
</VirtualHost>

Add the sub-domain in you hosts file:

127.0.0.1 dev.tutorial.com

Ok, at this point we should have our "Project created!" page. So Let's try to browse http://dev.tutorial.com/backend_dev.php

tuto1-1


:: The database ::


Create a local database, let's call it tutorial again. (same as the project name)
Modify the database settings in the config/database.yml and config/propel.ini file, your database.yml file should look like this:

all:
  propel:
    class:          sfPropelDatabase
    param:
      dsn:          mysql://root@localhost/tutorial


Now we need a schema, let's take the one of Askeet


Ok now let's try to build the database:

symfony.bat propel-build-all-load backend

Oops, it seems there are some errors. :) As we are quite lazy just delete the password columns and the QuestionTag section of the /datas/fixtures/test_data.yml file.
Let's try again to run the last command. If your are successful you should now have some tables and data in your tutorial database. If not, you probably missed something. ;) At this point we have a valid application with a database, some tables and fixtures. Settings are ok, so can go to the next step.

...

» Lire la suite / read all «

25/03/2008

» symfony 1.0 : traduction FR de la cheatsheet Ajax

[FR] J'avais traduis il y a quelque temps la cheatsheet sur les helpers ajax realisée par Andréia Bohner. En fait il ne m'avait pas répondu très vite donc elle était un peu tombée aux oubliettes. J'avais fais cette traduction un peu vite fait et mot à mot donc le résultat n'est pas tip-top. :/ Donc si vous avez des propositions de modifications à n'hésitez pas, je peux les regrouper et envoyer la mise à jour à Andréia. Sinon ça pourra toujours servir à quelqu'un ne parlant pas un mot d'anglais ni de portugais. ;)

Traduction française de la cheatsheet ajax symfony



18/03/2008

» Symfony 1.0 tip : Registration of plugin routes

[En] Here is a little tip Fabien gave me. I am actually developing a plugin witch has quiet a lot of routes (about 40). Normally you can add the routes with the prependRoute function, like does the sfGuardplugin.

<?php
if (sfConfig::get('app_sf_guard_plugin_routes_register', true) && in_array('sfGuardAuth', sfConfig::get('sf_enabled_modules', array())))
{
  $r = sfRouting::getInstance();
 	
  // preprend our routes
  $r->prependRoute('sf_guard_signin', '/login', array('module' => 'sfGuardAuth', 'action' => 'signin'));
  $r->prependRoute('sf_guard_signout', '/logout', array('module' => 'sfGuardAuth', 'action' => 'signout'));
  $r->prependRoute('sf_guard_password', '/request_password', array('module' => 'sfGuardAuth', 'action' => 'password'));
}
?>


But for each prependRoute call an array_merge is done on all existing routes.

<?php
  /**
   * Adds a new route at the beginning of the current list of routes.
   *
   * @see connect
   */
  public function prependRoute($name, $route, $default = array(), $requirements = array())
  {
    $routes = $this->routes;
    $this->routes = array();
    $newroutes = $this->connect($name, $route, $default, $requirements);
    $this->routes = array_merge($newroutes, $routes);
 
    return $this->routes;
  }
?>


So the tip here is to save all routes, clear them, add the routes of the plugin and then append the saved routes. Witch can be done like this:

<?php
  // Save and clear all routes
  $r = sfRouting::getInstance();
  $routes = $r->getRoutes();
  $r->clearRoutes();
  
  // Plugin home
  $r->connect('plugin_home', '/my_super_plugin/homepage', array(
    'module' => 'my_plugin_module', 
    'action' => 'my_plugin_action',
    'additional_parameter'   => 1
    ));
 
  // Another route
  $r->connect('plugin_home', '/my_super_plugin/section1', array(
    'module' => 'my_plugin_module', 
    'action' => 'my_plugin_action_section1',
    'additional_parameter'   => 2
    ));
 
  // ... other routes
 
  // Then merge new routes with the saved one
  $r->setRoutes($r->getRoutes() + $routes);
?>


That's it. :) Of course it is always better to have all routes of the application in the routing.yml but in my case it was not possible.

02/03/2008

» sfLightboxPlugin 1.0.6

[En] New version with the last version of lightbox (2.03.3) + new helpers. You can check the demo here on my blog.

  • Updated lightbox library to v2.03.3
  • 3 new helpers (light_image_text, light_slide_image, light_slide_text)
  • New parameter for images slideshows to allow to display images as a html list (li..)
  • Slideshow navigation with the keyboard (left, right, ESC)


Thanks for your feedback ! Enjoy. :)



[Fr] Nouvelle version incluant la dernière version de lightbox (2.03.3) et quelques nouveaux helpers. Vous pouvez visualiser la demo ici sur mon blog.

  • Mise à jour de la librairie lightbox pour la version v2.03.3
  • 3 nouveaux helpers (light_image_text, light_slide_image, light_slide_text)
  • Nouveau paramètre pour les slideshows pour afficher les images comme une liste html (li..)
  • Navigation dans le slideshow à l'aide du clavier (gauche, droite, ESC)


Merci pour votre feedback ! Enjoy. :)

sfLightboxPlugin 1.0.6

01/01/2008

» PHP_Debug 2.1.2 is out !

[En] First of all, happy new yeaaaarrrrr !!!!!!!!! ;)

Just a little update of PHP_Debug, here is the changelog:

  • Added credits to symfony for the idea of the floating div renderer
  • Added a link for a direct input W3C validation
  • Added warning for local W3C validation
  • Corrected html validation in the W3C tab (dooh!)
  • Changed main version number for the pear one
  • Switched package to stable state
  • Fixed typo in the database debug tab
  • [12078] Moved examples to doc role
  • [10919] Created a setStartTime method for the php_debugline class


Enjoy ! See you. COil :)

PS: Be carefull, the main version number is now the pear one. The pear version of this version is 1.0.0 stable whereas the SourceForge version is 2.1.2

PS: You can also check the project homepage

PHP_Debug 2.1.2

25/12/2007

» Un éléphant ça bug énormément

[FR] A défaut d'avoir le courage d'écrire des articles intéressants à propos de Symfony ou de mettre à jour mes plugins; voici quelques photos de mon nouvel "ami de bureau", très sociable, pas si encombrant qué ça malgré la réputation qu'il traîne. :) Le voilà donc dans diverses poses. Vous pouvez le commander sur le site de Nexen entre autres.

J'ai mon éléphant PHP
J'ai mon éléphant PHP
J'ai mon éléphant PHP
J'ai mon éléphant PHP



PS: Ah au fait, joyeux Noël à tous ;)

» Autres billets / Other post

1 2 3 4 >