[Developer says] A quick start with Symfony2

Symfony is a powerful PHP framework. That is, a set of tools which you can use and create almost any web application and it’s way much faster than writing everything from scratch. codebender and most of its components, such as the cloud-based compiler, are built using Symfony. Symfony offers several mechanisms which can get you started, literally in, minutes. In the next sections we are going to demonstrate how you can create a simple book store application with Symfony without actually writing any code. Our application will consist of a database for storing data about the books on the store, as well as the web interface for adding and editing books on the database.

Prerequisites

Before moving on, please make sure you’ve downloaded and installed PHP (min version 5.4) and MySQL to your development machine. It would also be ideal to use some Unix operating system such as Ubuntu. If you’re not familiar with any of these you could create an Ubuntu Linux virtual machine which should come with both PHP and MySQL pre-installed and requires no set up.

A bit about Symfony’s structure

A Symfony application is divided in bundles. Each bundle is a bunch of PHP classes that are related to a specific aspect of the application. For example, all the code that handles the creation and deletion of users as well as the login and logout mechanism, should be placed in a single bundle. This is really helpful when your application codebase starts getting bigger and bigger. Every bundle interacts with the rest of the app components through Controllers. Controllers are nothing more than PHP classes but they are flavored with several cool features. They can render web pages and interact with the database and controllers from other bundles.

Symfony application setup

Move to your home folder and let’s try the commands below

$ mkdir project
$ cd project
$ sudo curl -LsS http://symfony.com/installer -o symfony-installer
$ sudo chmod a+x symfony-installer 
$ ./symfony-installer new bookstore 2.3

Downloading Symfony...

    4.60 MB/4.60 MB ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓  100%

 Preparing project...

 ✔  Symfony 2.3.34 was successfully installed. Now you can:

    * Change your current directory to ~/Desktop/project/bookstore


    * Configure your application in app/config/parameters.yml file.

    * Run your application:
        1. Execute the php app/console server:run command.
        2. Browse to the http://localhost:8000 URL.

    * Read the documentation at http://symfony.com/doc

We’ve just downloaded the Symfony framework core and created a new project. The project is calledbookstore and uses version 2.3 of Symfony which is an LTS version and will be supported until mid 2016. The application also contains a sample bundle. And we did all this running a single command! Now, as the installer output says, we can even run the application from within the project root directory. Navigate to the project root directory (bookstore) and run php app/console server:run. Then open http://localhost:8000 from your browser and you will see the welcome page of the app.

By default, the installer will create a bundle called AppBundle, along with its DefaultController and some functional tests for this controller. We will not need this bundle at all, so you can remove it by doing the following:

  • remove the AppBundle directory
  • remove the new AppBundle\AppBundle(), from the bookstore/app/AppKernel.php file
  • remove all the contents of the bookstore/app/config/routing.yml file, without deleting the file

That should completely remove the sample bundle and its configuration from your project.

Creating the BookstoreBundle

Now let’s move on to creating a new bundle in our project. This bundle will host the code of the bookstore web application. From within the project root directory execute the command

$ php app/console generate:bundle

This will start the Symfony bundle generator, an interactive wizard which helps you create a bundle and ‘attach’ it to the application kernel. The generator takes care of the directory structure and creates all the necessary files. You just have to specify some properties of the new bundle as follows:

  • Bundle namespace: Bookstore/DefaultBundle
  • Bundle name [BookstoreDefaultBundle]: (use default value)
  • Target directory [path/to/project/bookstore/src]: (use default value)
  • Configuration format (yml, xml, php, or annotation): annotation
  • Do you want to generate the whole directory structure [no]? (use default value)
  • Confirm generation
  • Confirm automatic update of the Kernel and Routing

There you go! You will find the bundle in the bookstore/src directory. Within the Controllerdirectory of the bundle you will find a PHP class called DefaultController. The class contains a single method that can be accessed through the http://localhost:8000/hello/{name} url.{name} is a placeholder and can be replaced with any value. All the method does is render an empty HTML page reading ‘Hello name!’. We won’t use this auto-generated Controller in this example, but there is no real need to delete it.

Creating databases and tables

Now that we have created the structure of the Bookstore main bundle, we need to create a database. The database will contain a single table called Book. This table will contain metadata for the books available in our book store. None of the above will be done with MySQL statements. Instead, we will use Doctrine, again through Symfony’s console.

We must first configure the database-related parameters of the application in thebookstore/app/config/parameters.yml file. After that, the parameters.yml file should look like this:

parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306 
    database_name: bookstore # you should only need to change the database name
    database_user: root
    database_password: null
    ....

Then run the command below from the project root directory

$ php app/console doctrine:database:create
Created database `bookstore` for connection named default

You have successfully created the database that will be used by the application. Next, we have to create the Doctrine Book entity. An entity is a PHP class, which is mapped to a MySQL table by Symfony using Doctrine’s object relation mapper (ORM). In practice, this means Symfony handles each row of a MySQL table as a PHP object. You just use entity methods to modify an object and each operation is internally ‘translated’ to a MySQL statement. You can read more about how Doctrine works with Symfony here.

Using the command below, you can use the Doctrine entity generator which will guide you through creating an entity.

$ php app/console generate:doctrine:entity

Fill in the entity properties as follows:

  • The Entity shortcut name: BookstoreDefaultBundle:Book
  • Configuration format (yml, xml, php, or annotation) : annotation
  • Now we can add the fields of the Book table. First, add the field name and then the wizard will ask you to specify the field type and length (if applicable).
    • title [string][255] (book title)
    • author [string][255] (author name)
    • isbn [string][255] (the unique ISBN code of the book)
    • year [integer] (year the book was published)
    • shelf [integer] (the shelf where the book is placed)
    • available [boolean] (indicates whether the book is available at the book store right now)
  • Do you want to generate an empty repository class [no]? (use default value)
  • Confirm generation

This should create an Entity directory in the Bookstore bundle. The directory contains a BookPHP class with all the properties specified above. Below the properties, the wizard has automatically generated getter/setter methods for each property. The class also contains ORM annotations which specify the exact structure of the Book MySQL table.

In order to create the Book table in your MySQL database, run the following command:

$ php app/console doctrine:schema:create
Database schema created successfully!

An empty Book table should have been created in the bookstore database.

Creating a CRUD Controller

At this point we have set up the Symfony application and configured our book store database. Now we need to add the code that interacts with the database and performs basic operations, such as adding books to the Book table.

These operations (methods) will be hosted in a CRUD controller, where CRUD stands for create,read, udpate, delete. Once again, using the Symfony console, we can easily generate such a controller for every table of our database schema in a single command. The coolest thing about this is that Symfony will also generate the html pages where you can actually add or edit a book from the database.

Let’s run the command below:

$ php app/console generate:doctrine:crud

This starts the CRUD generator which will help you specify the details of your new Controller.

  • First, we need to define the Doctrine Entity based on which the controller should be created. In our case, that’s the Book entity, which should be referenced by the shortcut notationBookstoreDefaultBundle:Book.
  • Next, the wizard will ask if it should implement the write actions, like new, update anddelete. Type ‘yes’ and let’s move to the next section.
  • We have to specify the configuration format of the controller. That is the mapping of the actions of a controller to actual Urls of the application. For example, the createNewBookAction should be placed under http://localhost:8000/book/create Url. We are going to use theannotation format for now, which is more compact and specifies the route of each action adding a comment above the action method.
  • Last, we have to add a prefix to all the actions related to Book entities. The wizard will suggest using ‘/book’, which should be just fine.

After confirming the generation of the controller, you will find a new Controller PHP class undersrc/Bookstore/DefaultBundle/Controller directory in your project. Go ahead and have a look at the code, it’s pretty straightforward.

The book store application should be ready! Run the Symfony server with php app/console server:run and head over to http://localhost:8000/book Url on your browser and start using it. The whole process should take less than 10 minutes and we barely used a text editor. Happy days!

Leave a Comment

Stay tuned:

* we promise that we won´t spam you, never.