Getting started with Symfony – A PHP Framework – Part 1

Hello Friends,

Since past few weeks I have been pushed into something which I have never favored i.e. using a framework for my development. Using a framework can become even more harder if you know all the actual HTML, CSS, JS, PHP coding. Then you just wonder WHY? WHY? WHY?

Anyways I had to do it using Symfony PHP framework and there was no way out. As I couldn’t find much help outside http://symfony-project.com , it made even more difficult for me to implement and understand symfony.  So I thought of writing a tutorial, which can help many others like me out there and also act as a reference for me in future. Here instead of giving a theory lecture straight up, we will learn along with little hands-on developments.

Installation:
Before installing Symfony I assume we already have Apache, PHP 5 and MySQL installed on your system. If you don’t have them already installed, read this post of mine on how to configure WAMP on your windows. How to Install Apache, PHP 5 and MySQL on Windows?

This method works equally on Windows and Unix systems. On windows open your command line and on Unix open a terminal window.

  1. Go to My Computer -> Right Click -> Click on Properties -> Advanced Tab -> Environment Variables -> Create a PATH variable if it doesn’t already exists -> Add C:PHP as the PATH variable value.
  2. Go to Start -> Run -> Type cmd -> Type C:> pear channel-discover pear.symfony-project.com
  3. Type C:> pear install symfony/symfony-1.0.18 , it will install symfony latest stable version for you. (1.0 at the time of writing this tutorial)
  4. If you are having trouble installing, post a message here or refer http://www.symfony-project.org/installation/1_0 for more details.

So now you have symfony framework installed and we will learn how to build our first project in symfony.

My first Project:
Before we go ahead in making our first php project using symfony, just a little theory without which its impossible to understand the flow. Symfony projects are designed as follows:

       My First Project –> Application 1 —-> Module 1
                                  |                              |
                                  |                              –> Module 2
                                  |
                                  -> Application 2 —-> Module 1
                                  |                              |
                                  |                              –> Module 2
                                  |                              |

                                  |                              –> Module 3
                                  |
                                  -> Application 3 —-> Module 1

So in your Project your can have multiple Applications and inside every application you can have multiple Modules.

  1. Go to your Apache Web Folder (Document Root) which in my case is C:Workspace.
  2. Create a folder called Symfony. We will keep all our symfony related development work in this folder.
  3. Go inside the folder C:WorkspaceSymfony and create another folder for our 1st project. Lets name it HelloWorld
  4. Open your command line and go to the above folder path i.e. type ‘cd C:WorkspaceSymfonyHelloWorld’ on your command line.
  5. Type ‘symfony init-project HelloWorld’ and press enter. This will automatically create the project directory structure for you. Don’t be afraid if you see some 10 folders being create by the last command.

Don’t close the command line window, we will need that throughout.

So by now we have our first symfony project folder ready (structurally). But to view this on your browser we need atleast 1 application and atleast 1 module in that application. Lets create them quickly.

  1. Type ‘symfony init-app HelloWorld’ and press enter. This will create an application folder C:WorkspaceSymfonyHelloWorldappsHelloWorld. Now lets create a module inside this application
  2. Type ‘symfony init-module HelloWorld HelloWorld’ and press enter. This command means, create a module named HelloWorld inside application HelloWorld. Generic level syntax is ‘symfony init-module [application] [module]’

So we have our first symfony project ready. Type http://localhost/Symfony/HelloWorld/web in your browser window and press enter. You will see a page like this:


Figure 1

But this is not what it should be. If you read the page, it says “If you see no image in this page, you may need to configure your web server so that it gains access to the symfony_data/web/sf directory”.

So all you need is to copy folder C:php5peardatasymfonywebsf (in my case) to C:WorkspaceSymfonyHelloWorldwebsf. If you don’t find sf folder at the specified place, kindly search for it on your system. It was created when we were installing symfony.

After copying the folder refresh your web page again and see if you see any difference. For me it looks like:


Figure 2

Well Congratulations ! You just made your first symfony project. But unfortunately you know 0% of what did. Right? Lets understand what exactly is going in the background.

A bit about MVC Architecture:
Symfony follows MVC (Model-Viewer-Controller) Architecture to the core. If you haven’t worked with MVC architectural frameworks before, it can really take sometime to get a feel of it. I took about a week to actually understand what goes in the background.

MVC Architecture is nothing but breaking your whole page code into three parts namely Model (Database) , Viewer (Frontend HTML Pages) and Controller (Which fetches data from Model i.e. database and provide it in required format to Viewer i.e. what we finally see on our browsers). This is a very layman definition which I have given. We will slowly and gradually see each aspect of MVC in Symfony.

A bit about ORM (Object Relational Mapping):
This is yet another programming technique which you will find in each and every framework. In layman language, ORM provides you an object to handle your database. You need not write a SQL Query in actual at any point in your project. You will access all your database rows using this ORM Object.

Strange it may seem at first, but consider a big project running on MySQL with a lot of INSERT queries. Now at some point in time when database size reaches > 50 Gb or so and you are finding MySQL not efficient enough to handle such a large database, you would want to change to a database like Oracle. In such a scenario, ORM takes all the headache off from you, as you need not care about the actual SQL queries that goes in the background. ORM automatically takes care of this stuff.

Understanding Symfony Directory Structure:
The Symfony directory structure of our first project will look like this:


Figure 3

Remember we still don’t have anything dealing with the databases, hence I can say that Model layer is still missing from the directory structure. But let us first complete our targeted “Hello World” application.

  1. Go to HelloWorld/apps/HelloWorld/config folder and open the file rounting.yml
  2. Change the 4th line in that file from – param: { module: default, action: index } to param: { module: HelloWorld, action: index }
  3. We will learn about all .yml files which you see, but as of now lets focus on what we just did. By default our Symfony project points to a default module created by Symfony. Thats why we see Figure 2 above. By changing the above piece of code, we are telling our HelloWorld application inside HelloWorld project that, by default point to my HelloWorld Module. Confusing! Read the last line again and continue reading 😉
  4. Go to HelloWorld/apps/HelloWorld/modules/HelloWorld/actions and open the file actions.class.php
  5. Comment the following php code $this->forward(‘default’, ‘module’); inside executeIndex() method.
  6. Go back to your command line and type: ‘symfony clear-cache’
  7. Type http://localhost/Symfony/HelloWorld/web in your browser window and press enter.

Bingo! You see a blank white page. Lets understand what we actually did. But before that just a few points on how a page is actually displayed in Symfony.

  1. When we type http://localhost/Symfony/HelloWorld/web in our browser, index.php in the web folder goes to routing.yml file
  2. Routing file then tells which module to follow by default. By following Step 2 above, we directed the flow to our HelloWorld module.
  3. Then flow goes to the actions.class.php file of the module provided by Routing file. Hence in our case it must have gone to actions.class.php file of HelloWorld module.
  4. It looks for executeIndex() method in the class file, executes it and
  5. Finally goes to indexSuccess.php file placed under the template folder of our HelloWorld Module.

But since our actions class method was already diverting the flow to the default module, flow won’t have come to step 5 above and would have gone to default symfony module. By commenting out the line in step 5 above, we actually skip this forwarding and the flow comes to indexSuccess.php file under templates module. And finally since indexSuccess.php file is a blank file, we see a blank page. 🙂

Read the above 2 point charts carefully. If you can understand this flow, you already conquered half the symfony.

Note: All this will go waste if you forget ‘symfony clear-cache’ in step 6 above. As a rule of thumb, always run this command when ever you make any changes to any of the .yml files.

My First Project “HelloWorld”
Open indexSuccess.php and type <h1>Hello World</h1> into it. Run http://localhost/Symfony/HelloWorld/web in our browser, and thats it 🙂 You will see a page like below.

And with that we completed our Part 1 of this Symfony tutorial series. In upcoming parts of the series we will learn how to manage databases and build a bit more complex application and modules. Post your doubts and comments if any.

Note: I am myself learning many parts in Symfony and I myself gather knowledge by experimentation and through various web sources. Hence if a Symfony expert is reading this and find anything wrong, kindly correct me.

  • symfony, a lack of documentation? I’m not sure where you’ve been looking, but symfony is one of the best documented frameworks ever.

    But the fact that you say you dislike frameworks because you know how to do PHP, HTML, CSS and JS says something about you as well. Using a framework is not because you don’t know those things, it’s because you *know* those things and want to build on a stable platform and don’t repeat the same tasks all over again every time.

  • Henrik

    Ehm lack of documentation?? What planet are you from?? http://www.symfony-project.com

  • Hi Stefan,

    Yup I do agree Symfony is well documented as far as documentation on their site is concerned. But to start with I didn’t find enough help from outside. i.e. from people’s personal blog or forums. This was what I meant when I wrote not much help.

    Further I again agree with your next point that we use frameworks not to repeat same code over and over again. And I am realizing that fast now after stepping myself into Symfony.

    But for someone who starts without any background on using such frameworks, it can get really tough to get started. Or probably it was just for me 😉

  • Hi Henrik,

    I guess you all got me wrong on this. I meant lack of enough help outside their own “The Book”.

    Ofcourse their own site is the only bible out there.

  • Haraki

    Excellent getting started tutorial. Nice explaination to start with. Worked out just fine for me.

    Looking forward to some big project sample code examples in near future.

    Regards from Japan,
    Haraki

  • Santosh

    I will agree with top two commentors over availability of documents on Symfony site. But your tutorial is not a bad start too.

    You probably went down a step further in explaining the stuff.

    Santosh

  • Very good. Nice and informative (blog and the comments abt documentation as well) for a beginner like me!

  • abel

    Looking forward to the next parts…

  • Rob

    Re your comment about the Symfony community, see http://www.symfony-project.org/blog/2008/10/20/three-years-of-symfony

    Another tutorial is always welcome though, particularly if it’s from someone solving those first-time problems.

  • Absolutely right.

    The problem which I faced while getting started with symfony was that I could find too many examples and very very basic tutorials.

    For instance, searching for some very basic howto took a lot of time for me. The tutorials which I came across over net, don’t seems to focus and explain the inner details and hence this series of tutorial.

    Hope to save time for many like me out thr. 🙂

  • Pingback: How to build a login-registration system using Symfony - A PHP Framework - Part 2 | Abhi's Weblog()

  • Pingback: rpsblog.com » A week of symfony #94 (13->19 october 2008)()

  • Pingback: Symfony model layer tips and tricks - A PHP Framework - Part 3 | Abhi's Weblog()

  • Arul

    Hi,

    I had follow this rules but when i execute this command
    “pear channel-discover pear.symfony-project.com”

    getting the following error
    ‘pear’ is not recognized as an internal or external command,
    operable program or batch file.

    please advise me

    Thanks.

  • Simply include the php folder where you can find pear.bat file in your PATH.

    On windows:
    My Computer -> Properties -> Advanced -> Environmental Variable -> Create a PATH variable if doesn’t exist already -> Add C:PHP in the PATH variable list.

    Restart the command line and if required your PC too. This will solve the issue and help you getting started.

  • Arul

    Thanks,

    Problem solved.

  • Great tutorial.
    I’m starting with Symfony and this helps me very much.

  • wintervssummer

    I very much love summer 🙂
    Someone very much loves winter 🙁
    I Wish to know whom more 🙂
    For what you love winter?
    For what you love summer? Let’s argue 🙂

  • arul

    Hi,

    Iam doing my project in symfony and executed successfully.

    I have problem with routing, actually now my project running like the below url

    http://www.myserver.com/myproject/web/index.php/mymodule

    When i typing the above url then only my indexSuccess.php page are displaying.

    but i need to display my indexSuccess.php page when i giving the below url

    http://www.myserver.com/myproject/

    please advice me.

    Thanks in advance

  • karthik

    Its a nice tutorial for the beginners of Symfony. I Expect more…

  • Vytautas

    Hi,
    I’m new at symfony. I started use it on a local server. Adn now I want to move my aplication to server. I read some tutorial how to do what, but i’m failed what one. So maybe you could explain me, how to do this job.
    Best regards, Vytautas

  • Hi Vytautas,

    I am not getting you, whats the difference between running on localhost and on live servers. Both require the same procedures and steps. Can you atleast tell something from your error logs. What error are you getting when you are trying to move to live servers?
    Regards, Abhi
  • Really nice tutorial..
    Helpd a lot…
    Hope to see more coming.
    Thnx

  • maithili

    Very nice tutorial.Its very good tutorial for beginners.Its helped me very much to learn about symfony.Even i am very new to symfony.This step by step with explanation helped me a lot.Thanks admin…I need more tutorial related to database.Actually when i run the application http://localhost/sfdemo/web/mymodule its redirecting the page to http://localhost/sfdemo/web/mymodule/projects.php.I dont want to redirect the page by showing projects.php.How to do with symfony?help me please…

  • neha

    hi.. i am a beginner in symfony . after successfully installed xampp including(apache, php, mysql etc) and symfony, when i started creating the first project using the command :

    F:xampp/php symfony init-project helloworld

    it says : “a project names “hellowolrd” already exists in directory. it says this for every name i tested. i also tried to give the complete path of the new project folder, but still the same problem.

    please help me..
    thanks alot..

  • Hi, which PHP IDE are you using?
    I am proficient with c#, .NET on VS2005. And I am moving to PHP web dev now. So, which are the best possible IDEs out there with “intelligence”?
    To start with, I got a list here: http://www.ibm.com/developerworks/opensource/library/os-php-ide/index.html
    I just need to know, which is the PHP IDE which is professionally used (Paid and Open Sourced, both 😉 ).
     
    Thanks

  • Hi Maverick,

    You might not believe but I do all my coding using VIM editor, thats it. At times when on windows, I use SciTe editor.

    However  I know you will get a lot of efficient IDE’s in the market, but I love this way. I m not the right guy to ask this 😀

    Thanks.

  • shiva prasad

    this tutorial was very useful.
    thank u so much..

  • sharmistha

    quite impressive…

  • Quite helpful. Takes it a step further…

  • Hi ,

    This is what i was looking for .The beginners.

    Regards,
    Gopal

  • Uday

    The best solution for my problem.

    Thanks.

  • bhumika

    Hi

    I want to install Symfony on my PC. At first I set the path to C:PATH

    but as I proceed its says
    “pear is not recognized as internal or external command.”

    Also I have xampp installed on my machine.

    Can u please help me out

  • clod

    For begginners I suggest the following PHP IDe with special Symfony plug-in: http://codelobster.com/symfony.html