Wednesday, February 25, 2015

Creating Bundles in Symfony

Creating Bundles in Symfony

Bundle allows to group us several features to a single unit. It works like a module or plugin. Your Symfony site is composed of many bundles to make up your final application. Everything comes in bundles in Symfony from third party components and the one you develop. Even Symfony library code comes in a bundle. Our bundle can be used by multiple application or even distribute it to other developers. Individual entities related to specific functions are packaged in a bundle (thats where it gets its name from). It is somewhat similar to package in Java language but somewhat different. Each bundle has its own configuration, routes, controllers, templates and other as needed. Bundles are generally stored in src/ folder. It can however be stored anywhere as long as you can address it.

Creating Bundle

We can create bundle by making necessary directory structure, files and other structures, but it can be easily generated in command line with a single command. First change your directory to the directory you installed the framework. For an example if you installed at SchoolManagement.

$ cd Schoolmanagement

Run Following command

$ php app/console generate:bundle --namespace=Stm/SchoolManagementBundle --format=yml

The above command generates bundle with vendor name = Stm and bundle name = SchoolManagement with configuration format in yml format. yml format is easy to use with cleaner body compared to xml or php configurations. The command asks for some options for creating bundles

Bundle name [StmSchoolManagementBundle]:
Target directory [/Users/user1/htdocs/SchoolManagement/src]:
Do you want to generate the whole directory structure [no]?
Do you confirm generation [yes]?
Confirm automatic update of your Kernel [yes]?
Confirm automatic update of the Routing [yes]?

Just hit enter to select default options or chose option as you wish. If you select yes at third question, Symfony will automatically generate additional code snippets so that you can start faster. But if we like our custom program design, we can write from now on. Inside SchoolManagement/src, new folder with our vendor name is generated, containing, folders like Controller, resources etc. The generator also automatically registers our bundle in registerBundles() method of app/AppKernel.php with

new Stm\SchoolManagementBundle\StmSchoolManagementBundle()

To remove bundle, unregister the bundle by just deleting this line. It also includes SchoolManagemntBundle routing file in src/Stm/SchoolManagement/Resources/config/routing.yml to main routing file in app/config/routing.yml as

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

    path: /hello/{name}
    defaults: { _controller: StmSchoolManagementBundle:default:index }

How to install Symfony framework step by step for the first time

To a new user, installing Symfony framework seems somewhat different than other frameworks like CodeIgniter or other CMS like Wordpress and Drupal. While you can directly copy and paste the Symfony folder from Github, but the recommended way is to install through composer.


Symfony requires up-to date php version installed at your computer. It works with php5.4+ but recommended version is php5.5+ to support many new functionalities. You can check php version by using php -v at command line or call phpinfo() method in web server. Also, your web server and command line php versions might be different, if they are, you can add path to your php binaries to .bash_profile in Linux, Unix, or Mac computers and environment variables in windows machine. You will also need database server like mysql and preferably web server.


You can simply copy the symfony folder from github and run, like other simple frameworks and CMS. But the recommended method is installing through composer. It comes as a command line tool and we write different commands at command line to do required task. At first, command line tool might seem alian to new user, but actually, it is easier to use command line tool than other method. If you copy and paste github repository to your htdocs, you have set up the db and other credentials manually at app/config/parameters.yml file. If you can't find this file, rename parameters.yml.dist. With this, Acme demo is automatically installed and you have to unregister it and remove routes before you write production software.


Composer is installer and package manager of PHP. It is used by many frameworks and applications like Yii, Laravel, Symfony and others. It is very easy to efficiently install and manage dependencies through composer. Composer can be simply downloaded and installed in command line. More information about installing and running Composer can be found at Install composer beforehand proceed with next steps.

Installation with Composer

Navigate to wherever you like to install Symfony. Preferably in htdocs folder of your AMP stack. If you want to install Symfory in SchoolManagement/ folder then run following composer command

$ composer create-project symfony/framework-standard-edition SchoolManagement/

The above command tells composer to create project with code from vendor = symfony and product = framework-standard-edition into the local folder SchoolManagement. You can also install older or developmental version of symphony by specifying version number in single quotes, with ~ sign. For an example we install our standard edition of symfony framework with version = 2.6.

$ composer create-project symfony/framework-standard-edition SchoolManagement/ '~2.6'

Select Options for your application

Now it will ask you to select various options for your application. You have to answer these by typing in options or hitting enter if the default values is okay for you.

Would you like to install Acme demo bundle? [y/N] n

If this is your first time with symfony, you can chose to install Acme demo bundle. It is only demo files and not actually required. Chose N for not to install Acme demo bundle.

database_driver (pdo_mysql):
database_host (
database_port (null):
database_name (symfony):
database_user (root):
database_password (null):
mailer_transport (smtp):
mailer_host (
mailer_user (null):
mailer_password (null):
locale (en):
secret (ThisTokenIsNotSoSecretChangeIt):
debug_toolbar (true):
debug_redirects (false):
user_assetic_controller (true):

The options are self explanatory. You can just press enter to select the default option (in bracket). Pay special attention to database_name, database_user and database_password, write your db credentials to these variables. If you are using mamp, you might consider using
database_port (null): 8888
For secret, you should type any random string which is very hard to guess eg:
secret (ThisTokenIsNotSoSecretChangeIt): K3msp02M_kdl2mxldjza1qmCvD7xcvpoi43uXe
After this step, Symfony is installed.

Check if the installation is working

Change directory to the installation folder. For our case, write

$ cd SchoolManagement
Then check whether this installation is working properly.

$ php app/check.php
If there are any errors, it will show the message. If everything is right and you are ready to go, then it displays following message all in green

Your system is ready to run Symfony2 projects

Run your project

You can now run the Symfony2 project. You can test run it from your AMP stack or built in PHP web server.

Run from AMP stack

If you have AMP stack then point to following addres localhost in the browser. If you are hosting elsewhere, go to your webserver and following address in the web browser to access the Symfony project

One important thing that you should consider is you have to include web/app_dev.php after your host to run it properly. If you want to remove this, follow another manual How to remove web/app_dev.php or web/app.php in symfony project. or

Running from built-in php server

If you don't have webserver or like to access directly to this site, you can run following command

$ php app/console server:run
Server running on http:

You can access it in web browser by going to site


You will see symfony logo and debug bar, which signifies it is working properly. Symfony actually gives no route found exception if you haven't installed Acme Demo Bundle. But if you see symfony logo and debug bar, you are ready to go. You can start coding and defining routes. Now you have successfully installed Symfony2, ready to deploy. If you have installed Acme Demo Bundle, and want to remove this after initial testing, you can follow How to remove Acme Demo Bundle in Symfony project

Monday, February 23, 2015

How to remove web_dev.php in Symfony site

When we first install Symfony, we can access the site at http://symfony.webroot/web/web_dev.php. we cannot access web folder directly. This is due to the debug mode. When we install Symfony, it comes with built in debug mode enabled. Also, we have to access site through web/app.php in production mode This might be annoying.

Symfony comes with two modes: Production mode and debug mode. Debug mode behave differently than production mode. It caches much less but shows more verbose information. We can remove this web_dev.php by clearing production mode and setting debug mode off. This can be done by running following console command at command line at the root of Symfony project

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

This command clears the production cache. It also allows to access Symfony urls without app_dev.php.

Now we can access the site at http://symfony.webroot/web/action
But if we want to  access the action through http://symfony.webroot/action, without web/ then we have to rewrite the url with .htaccess or point to web folder in apache virtual host httpd.conf

The web/ in the url can be removed through .htaccess or apache virtual hosts. While setting webroot of apache virtual host is better, .htaccess works just fine in case we don't have access to the httpd.conf file in the server.

With .htaccess

To do this with .htaccess, create .htaccess at your web root folder and write following code To only remove the web/ subfolder in url do follwoing:

  <ifmodule mod_rewrite.c>
     RewriteEngine On 
     RewriteRule ^$ web/ 
     RewriteCond %{REQUEST_FILENAME} !-f 
     RewriteCond %{REQUEST_FILENAME} !-d 
     RewriteRule ^(.*)$ web/$1
It says: if there is web subfolder and if the request is not file or other directory, replace this web and access other contents inside it.

Entirely remove web/app

If we want to entirely remove web/app.php, we must explicitly name that in RewriteRule. Use following code for Symfony site and it will work.

  <ifmodule mod_rewrite.c>
     Options +FollowSymlinks
     RewriteEngine On

     # disable rewriting for front controllers
     RewriteRule ^/web/app_dev.php - [L]
     RewriteRule ^/web/app.php - [L]

     # Fix the bundles folder
     RewriteRule ^bundles/(.*)$ /web/bundles/$1  [QSA,L]

     RewriteCond %{REQUEST_FILENAME} !-f
     # Change below before deploying to production
     #RewriteRule ^(.*)$ /web/app.php [QSA,L]
     RewriteRule ^(.*)$ /web/app_dev.php [QSA,L]

To do with virtual host, just point the /web/ directory as your document root in your httpd config file

  <VirtualHost *:80>
     DocumentRoot /www/symfony.webroot/web
     # Other directives here

Sunday, February 22, 2015

Clearing Symfony Cache after system config change

It is easy to clear cache after changing system config

First method: Run console command from command line

$ php app/console cache:clear --env=prod

or equivalently

$ php app/console cache:clear -e prod

This command will clear the cache of production environment

Saturday, February 21, 2015

Removing AcmeDemoBundle from Symfony Project

The bundles in Symfony cannot be deleted simply. The bundles are called from various places. We need to unregister the bundle before deleting it. AcmeDemoBundle is a demo bundle and is not integrated with other bundles, so we can delete it easily. The process in doing it is described below

1) Unregistering the bundle from AppKernel::registerBundles() method in app/AppKernel.php. For that, delete following line in registerBundles() method.
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();

2) Removing Bundle Configuration from app/config/ folder. AcmeDemoBundle is a demo file and doesn't have configurations. It has only routing information. Remove routing information about AcmeDemoBundle from routing config file: app/config/routing_dev.yml. Delete following lines from routing config file.
    resource: "@AcmeDemoBundle/Resources/config/routing.yml"
3) Remove files from the system. Delete following folders and files
Now you are done in these simple steps.