Sunday, January 6, 2013

Getting started with Symfony2 - Part 1

After installing Symfony 2.1 and going through the documentations, everything seems simple enough. To start developing an application from scratch, first create a project, next create a Bundle and start adding codes.

Several assumptions;
  1. Installation was done as in my previous posting, including creating the project called mysymfony.
  2. The Bundle is called HelloBundle in Sample. All Bundle names must end with the word Bundle.
  3. All Bundles will be under the vendor named "Sample".
Here are steps to create and delete a Bundle.

A. Create a Bundle
Step 1: Generate the Bundle

cd mysymfony
php app/console generate:bundle --namespace=Sample/HelloBundle --format=yml

Respond to the wizard's questions;
  1. [Enter]
  2. HelloBundle
  3. [Enter]
  4. [Enter]
  5. [Enter]
  6. [Enter]
  7. [Enter]
  8. [Enter]

Step 2: Create the routing.
Still in the symfony directory, edit the file src/Sample/HelloBundle/Resources/config/routing.yml

    pattern:  /hello/{name}
    defaults: { _controller: SampleHelloBundle:Hello:index }

Step 3: Create the controller file.

vi src/Sample/HelloBundle/Controller/HelloController.php

namespace Sample\HelloBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HelloController extends Controller
    public function indexAction($name)
        return $this->render('SampleHelloBundle:Hello:index.html.twig', array('name' => $name));

Step 4: Create a view template

vi src/Sample/HelloBundle/Resources/views/Hello/index.html.twig

{% extends '::base.html.twig' %}
{% block body %}
Hello {{ name }}!
{% endblock %}

Step 5: Access the final application

In a web browser, enter the location or URL as



B. Delete a Bundle
Step 1: Delete the Bundle directory
rm -rf src/Sample/HelloBundle/

Step 2: Remove Bundle routing in /app/config/routing.yml
Example, delete

    resource: "@SampleHelloBundle/Resources/config/routing.yml"
    prefix:   /

Step 3: Remove Bundle from app/AppKernel.php
Example, delete

new Sample\HelloBundle\SampleHelloBundle(),

Step 4: Clear Symfony cache
php app/console cache:clear 


php app/console cache:clear --env=prod --no-debug

Note to self: No promises when Part 2 will be published.

No comments:

Blog Archive