Tutorial Askeet dia 1: iniciando um projeto

O Desafio

O advento do calendário symfony é um conjunto de 24 tutorias publicados dia-após-dia entre 1º de dezembro e o natal. É isso mesmo, todo dia incluindo finais de semana um novo tutorial será publicado. Cada tutorial foi criado para durar no máximo uma hora de leitura, esta será a oportunidade de ver o desenvolvimento de uma aplicação web 2.0 de A a Z desde o início. No Natal, o resultado final será posto no ar e o código fonte terá sido disponibilizado como open-source. Está aplicação visa ser usável, interessante, útil e principalmente divertida de desenvolver.

Vinte e quatro vezes, menos que uma hora por vez, isso significa menos de um dia, e é exatamente o que achamos que um desenvolvedor precisa para aprender symfony. Todo dia novas características são adicionadas à aplicação e nós tiramos vantagem desse desenvolvimento para mostrar como aproveitar ao máximo as funcionalidades do tanto quanto as melhores práticas de desenvolver projetos web usando o symfony. Todo dia você deverá perceber quão rápido e eficiente é desenvolver aplicações web com o symfony e desejará aprender mais.

Considerando que não seria suficiente um desafio com apenas isso, e também porque somos pessoas preguiçosas, não temos planos para o dia 21. O recurso que a comunidade mais solicitar será adicionado na a aplicação nesse dia, sem preparação, e nós vamos fazê-la funcionar. Será o dia obtenha-um-symfony-guru-por-um-dia.

O Projeto

A aplicação poderia ser desenvolvida dentro de um modelo trivial de aplicações voltadas para o aprendizado como uma lista de tarefas, uma agenda de contatos ou uma livraria. Mas nós queremos usar o symfony para um projeto mais original, algo útil, com várias características e de médio porte. O intuito é realmente provar que o symfony pode ser usado em situações complexas para desenvolver aplicações profissionais com estilo e pouco esforço.

Também esperamos que várias pessoas realmente utilizem a aplicação, a fim de mostrar que um website symfony pode suportar uma carga de utilização importante. É por isto que a aplicação necessita fornecer um serviço real, e responder uma necessidade existente - ou criar uma nova. O lançamento do website será um teste de stress ao vivo; isto também significa que nós precisaremos de vocês, humildes leitores, para fuçar/bookmark/blog o tise e falar sobre ele na vida real para verificar quantas visitas ele pode suportar.

O conteúdo do projeto será mantido em segredo para outro dia. Ainda teremos muito a fazer sem descrever uma aplicação com recursos completos da web 2.0. Isto deve dar a você algum tempo para imaginar e lançar hipótesis adicionais. Entretanto, necessitamos de um nome, então vamos chama-la: askeet.

O que temos para hoje

O objetivo do dia é mostrar uma página da aplicação no navegador, e configurar um ambiente de desenvolvimento profissiona. Isto inclui a instalação do symfony, criação de uma aplicação, configuração do servidor web, e a configuração de um sistema de controle de versão de códigos fonte.

Deverá ser fácil para aqueles que já seguiram os tutoriais anteriores, e não muito difícil para os demais. E todos deverão aprender alguma coisa nova.

Assumiremos que você utiliza um sistema semelhante ao Unix com Apache, MySQL e PHP 5 instalado. Se você está utilizando um sistema Windows, não entre em pânico: também deverá funcionar perfeitamente nele, você terá apenas que digitar algumas linhas na janela de comandos (cmd).

Symfony installation

The simplest way to install symfony is to use the PEAR package. However, to be able to use channels - and access the symfony channel - you need to upgrade to PEAR 1.4.0 or greater (unless you run PHP 5.1.0, which includes PEAR 1.4.5):

$ pear upgrade PEAR

Note: if you experience any problem while using PEAR, refer to the installation book chapter.

Now you can add the 'symfony' channel:

$ pear channel-discover pear.symfony-project.com

You are ready to install the latest stable version of symfony together with all its dependencies:

$ pear install symfony/symfony-beta

If you don't have the phing package, you will need to install it as well:

$ pear install http://phing.info/pear/phing-current.tgz

Check that symfony is installed by using the command line to check the version:

$ symfony -V

If you are curious about what this new command line tool can do for you, type symfony -T to list the available options. You might also want to read the installation book chapter to see how to install symfony from a tgz archive or the svn repository. A community contribution also details a non-PEAR installation in the symfony wiki.

Project Setup

In symfony, applications sharing the same data model are regrouped into projects. For the askeet project, we can already disclose the fact that there will be a frontend and a backend: that makes two applications. The project being the shell of the applications, it has to be created first. To do that, all you need is a directory and a symfony init-project command line:

$ mkdir /home/sfprojects/askeet
$ cd /home/sfprojects/askeet
$ symfony init-project askeet

Now it is time to create the frontend application with the symfony init-app command:

$ symfony init-app frontend

Wow, that was fast.

Note: Windows users are advised to run symfony and to setup their new project in a path which contains no spaces - this includes the Documents and Settings directory.

Web service setup

Web server configuration

Now it is time to change your Apache configuration to make the new application accessible. In a professional context, it is better to setup a new application as a virtual host, and that's what will be described here. However, if you prefer to add it as an alias, find how in the web server configuration book chapter.

Open the httpd.conf file of your Apache/conf/ directory and add at the end:

<VirtualHost *:80>
  ServerName askeet
  DocumentRoot "/home/sfprojects/askeet/web"
  DirectoryIndex index.php
  Alias /sf /usr/local/lib/php/data/symfony/web/sf

  <Directory "/home/sfprojects/askeet/web">
   AllowOverride All
  </Directory>
</VirtualHost>

Note: the /sf alias has to point to the symfony folder in your PEAR data directory. To determine it, just type pear config-show. Symfony applications need to have access to this folder to get some image and javascript files, to properly run the web debug toolbar and the AJAX helpers.

In Windows, you need to replace the Alias line by something like:

  Alias /sf "C:phppeardatasymfonywebsf"

Declare the domain name

The domain name askeet has to be declared locally.

If you run a Linux system, it has to be done in the /etc/hosts file. If you run Windows XP, this file is located in the C:WINDOWSsystem32driversetc directory.

Add in the following line:

127.0.0.1         askeet

Note: you need to have administrator rights to do this.

If you don't want to setup a new host, you should add a Listen statement to serve your website on another port. This will allow you to use the localhost domain.

Test the new configuration

Restart Apache, and check that you now have access to the new application:

http://askeet/

Congratulations

Note: symfony can use the mod_rewrite module to remove the /index.php/ part of the URLs. If you don't want to use it or if your web server does not provide an equivalent facility, you can remove the .htaccess file located in the web/ directory. If your version of Apache is not compiled with mod_rewrite, check that you have the mod_rewrite DSO installed and the following lines in your httpd.conf:

AddModule mod_rewrite.c
LoadModule rewrite_module modules/mod_rewrite.so

You will learn more about the smart URLs in the routing chapter.

You should also try to access the application in the development environment. Type in the following URL:

http://askeet/frontend_dev.php/

The web debug toolbar should show on the top right corner, including small icons proving that your Alias sf/ configuration is correct.

web debug toolbar

Once again, the setup is a little different if you want to run a IIS server in a Windows environment. Find how to configure it in the related tutorial.

Subversion

One of the good principles of lazy folks is not to worry about breaking existing code. As we want to work fast, we want to revert to a previous version if a modification is inefficient, we want to allow more than one person to work on the project, and we also want you to have access to all the daily versions of the application, we are going to adopt source version control. We will use Subversion for this purpose. Assuming you have already installed a subversion server or have access to a subversion server.

Fist, create a new repository for the askeet project:

$ svnadmin create $SVNREP_DIR/askeet
$ svn mkdir -m "layout creation" file:///$SVNREP_DIR/askeet/trunk file:///$SVNREP_DIR/askeet/tags file:///$SVNREP_DIR/askeet/branches

Next, you have to do the first import, omitting the cache/ and log/ temporary files:

$ cd /home/sfprojects/askeet
$ rm -rf cache/*
$ rm -rf log/*
$ svn import -m "initial import" . file:///$SVNREP_DIR/askeet/trunk

Now get rid of the original application directory and use a checkout of the SVN version:

$ cd /home/sfprojects
$ mv askeet askeet.origin
$ svn co file:///$SVNREP_DIR/askeet/trunk/ askeet/
$ ls askeet

$ rm -rf askeet.origin

There is one remaining thing to setup. If you commit your working directory to the repository, you may copy some unwanted files, like the ones located in the cache and log directories of your project. So you need to specify an ignore list to SVN for this project.

$ cd /home/sfprojects/askeet
$ svn propedit svn:ignore cache

The default text editor configured for SVN should launch. Add the sub directories of cache/ that SVN should ignore when committing:

*

Save and quit. You're done.

Repeat the procedure for the log/ directory:

$ svn propedit svn:ignore log

And enter only:

*

Now, make sure to set the write permissions on the cache and logs directories back to the appropriate levels so that your web server can write to them again. At the command line:

$ chmod 777 cache
$ chmod 777 log

Note: Windows users can use the great TortoiseSVN client to manage their subversion repository.

If you want to know more about source version control, check the project creation chapter in the symfony book.

Note: The askeet SVN repository is public. You can access it at:

  http://svn.askeet.com/

Go ahead, check it out.

Today's code has been committed, you can checkout the release_day_1 tag:

  $ svn co http://svn.askeet.com/tags/release_day_1/ askeet/

See you Tomorrow

Well, it's already one hour! We talked a lot, and did nothing new for the symfony early adopters. But just have a look at what will be revealed for our second day of the symfony advent calendar:

  • what the application will do
  • building the data model and generating the object-relational mapping
  • scaffolding a module

In between, if you want to keep in touch with the latest askeet news, you can subscribe to the askeet mailing-list or go to the dedicated forum.

Make sure you come back tomorrow!