MyPage is a personalized page based on your interests.The page is customized to help you to find content that matters you the most.


I'm not curious

Getting Started with Symfony 2

Published on 30 April 15
0
2
Getting Started with Symfony 2 - Image 1
Symfony 2 has seemingly gained the attention of developers in recent times. Owing to the growing hype surrounding this framework, it is something that you ought to know about. Let's try and decipher what the framework is all about, and how to get started with this platform.

Introduction
A web application framework formed of reusable PHP components has been termed as Symfony. Symfony 2 is an updated version of this framework, and it enables developers to create websites and web applications with ease and convenience. The individual PHP components that set out to form this framework can be selected as per your design and development requirements.

Let's understand why Symfony is gaining popularity and why it should be used by you. Frameworks in general offer ease and convenience to the developers, and help create websites in an efficient manner. It should be specifically used to create large apps, as it may add up to the complexity when you are using it to create small apps. While there are many frameworks available for you, Symfony 2 becomes an ideal choice. Symfony is known to be compatible with all databases and other integration elements. It offers convenience in developing small scale apps to large websites.

Installation and Configuration
Go to www.symfony.com. You will see a download button on this page, click on the button to initiate download. You will see two options for download

  • Use a composer to set-up the framework
  • Use the Quick test drive version

There are two versions of Symfony available for download- with long term support and with latest features. You can even download individual components within the framework, which is the third download option available

If you have chosen the quick test drive option, here's how you need to go ahead with the download and configuration process.

Extract the contents of the zip file that you have downloaded to the web directory. Before extracting, make sure you have created a new folder where you can extract the contents of the zip folder. You will need a web server support i.e. support from PHP or WAMP for this purpose. In case you are using WAMP, create the new folder "Symfony-test" in the WAMP web directory.

This is the directory structure

Example-PC /d/wamp/www/symfony-test

$ ls

LICENSE UPGRADE-2.2.md UPGRADE-2.4.md app composer.json src web README.md UPGRADE-2.3.md UPGRADE.md bin composer.lock vendor

Go to http://localhost/symfony-test/web/app_dev.php/

In case you have installed and configured the framework perfectly, then you will be directed to the Welcome page.

You have installed and configured the framework. Now, you need to understand the directory structure of the framework.

Directory Structure of Symfony 2
This PHP framework has a total of five directories- app, bin, src, vendor, and web. In most cases, when developing an app with this framework, you need to put the source code in src, static assets in web, or write the config files to the app directory. Even the directory structure in Symfony 2 can be customized to suit your design needs.

It is important to understand what individual directories stand for, and how they can be used.

app/
This directory is meant for the application configuration. If you need files related to configuration, you can look up for them in the app/configuration folder. In case you want to configure the database, you can modify the parameters/settings in here; you can even hold the cache in this directory. When working on Symfony 2, you are working with a range of files like xml, yml, php, twig, html etc. when Symfony begins requesting these files, it may deteriorate the performance. In order, to ensure smooth performance, in-built cache directory has been provided where the cache data is stored.

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

With this command, you can clear the cache within the production environment.

Command Line Interface
This tool is available with every /app directory. With this tool, you can use commands that will enhance the overall productivity of your web application. The reason being, you will automatic repetitive and tedious tasks.

Run the following command without any arguments to understand the capabilities of this tool
$ php app/console
You can understand the usage of this tool with the help command
$ php app/console debug:router --help
Along with these files, the app directory also holds logs and appkernel.php

The class appkernel.php must necessarily implement two methods

  • registerBundles() returns the array of all the bundles responsible for running an application
  • registerContainerConfiguration() this is responsible for loading the application configuration
bin/
This directory is known to store most of the security functions

src/
This is where the source code of your application is stored. All the controllers, views, routes etc. are created within this directory. Even the php template files are stored in this directory

vendor/
All the third party related things will be stored in this directory. To manage the common dependencies, you will need to depend on composer. With doctrine, you can perform database related tasks while with twig you can perform template/view related tasks.

web/
When you create a project with Symfony 2, your project would be stored in this directory. There are two important files located within this directory- app.php for the production environment and app_dev.php for the development environment. With this file, you can call the routes, twigs, controllers as well as all the other related elements necessary to initiate your project. You would also find the robots.txt files in this directory. The composer.json file is located in this directory which is responsible for composer configuration. The front controllers are also located in this directory.

Take a look at the production controller within the web/ directory

// web/app.php
require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
Bundle System
Bundles are similar to plug-ins in other software. The reason it has been coined bundle is because everything, right from the core framework to the code is a bundle. Bundle is basically a set of components like PHP files, stylesheets, JavaScripts etc. to execute a single feature. Bundles improve the functionality of the applications; you get to choose the elements that might help improve the functionality of your system. There is a default appbundle present in Symfony 2 that you can use to develop your own application.

How to Register a Bundle?
An application in Symfony 2 is made of bundles as it is defined in registerBundles(). Every bundle in this directory has an individual bundle class


// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle();
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
Along with the appBundle, the framework also releases other bundles like FrameworkBundle, DoctrineBundle, SwiftmailerBundle and AsseticBundle.

Configuring the Bundle
If you want to customize the bundles to suit your design need, you can do so using the configuration files like YAML, PHP, XML etc.
# app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }

framework:
#esi: ~
#translator: { fallbacks: ["%locale%"] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: "%kernel.debug%"
form: true
csrf_protection: true
validation: { enable_annotations: true }
templating: { engines: ['twig'] }
default_locale: "%locale%"
trusted_proxies: ~
session: ~

# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"

# Swift Mailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }

# ...
The first level entry classes like twig, framework and swiftmailer are responsible for the configuration of the specific bundle i.e. twigBundle, frameworkBundle and swiftmailerBundle respectively. With the specific configuration file, you can easily override the default configuration. The dev environment loads config_dev.yml which in turn loads the config.yml and modifies the same to add the necessary debugging files to it
# app/config/config_dev.yml
imports:
- { resource: config.yml }

framework:
router: { resource: "%kernel.root_dir%/config/routing_dev.yml" }
profiler: { only_exceptions: false }

web_profiler:
toolbar: true
intercept_redirects: false

# ...
Extend the Bundle
You can even extend the bundle to another bundle. With this, you can easily customize the controllers and other files within a particular bundle.

The notation used to reference a file from the bundle is @BUNDLE_NAME/path/to/file. The @Bundle_Name will be located to its real path by Symfony 2

Example @AppBundle/Controller/DefaultController.php would automatically be converted to src/AppBundle/Controller/DefaultController.php as Symfony knows the location of AppBundle.

Similarly in case of controllers with the following format, you can easily reference actions within the controllers BUNDLE_NAME:CONTROLLER_NAME:ACTION_NAME

With these conventions, you can easily override the controllers, files and templates within the bundle. Let's say you create a bundle by the name NewBundle which will override the AppBundle. When you load the AppBundle:Default:index controller to Symfony 2, you will see that it first looks within the NewBundle for the DefaultController and then within the AppBundle. Any bundle can override almost all portions of another bundle. This is what gives Symfony the flexibility.

Setting up the Database
You can import the database, stored in rsywx.sql using MySQL command line tool. While it is possible to create the database internally, it is suggested that you use third party tools to create the database. The reason being you will be able to create a more intuitive database.

Configure app/config/parameters.yml to link the database
parameters:
database_driver: pdo_mysql
database_host: 127.0.0.1
database_port: null
database_name: symfony
database_user: root
database_password: null
Once you have configured the parameters, you will need to change the user name and password for the database before importing the database structures into the config file.

Using the command below, you can import the database.

php app\console doctrine:mapping:import

Once imported, you will need to create entities corresponding to the database using the following code

php app\console doctrines:generate:entity tr



Note: As of now Symfony 2 supports two ORMs (Object Relational Mapping)- Doctrine and Propel.

Conclusion
With this, you have setup Symfony 2 framework. With the database in place, and all the bundles configured, you are ready to begin with developing your own application on this framework. This is an easy and straightforward setup. Always create a copy of the original zip file that you have downloaded, before you start with the setup
This blog is listed under Development & Implementations and IT Strategy & Management Community

Related Posts:
Post a Comment

Please notify me the replies via email.

Important:
  • We hope the conversations that take place on MyTechLogy.com will be constructive and thought-provoking.
  • To ensure the quality of the discussion, our moderators may review/edit the comments for clarity and relevance.
  • Comments that are promotional, mean-spirited, or off-topic may be deleted per the moderators' judgment.
You may also be interested in
 
Awards & Accolades for MyTechLogy
Winner of
REDHERRING
Top 100 Asia
Finalist at SiTF Awards 2014 under the category Best Social & Community Product
Finalist at HR Vendor of the Year 2015 Awards under the category Best Learning Management System
Finalist at HR Vendor of the Year 2015 Awards under the category Best Talent Management Software
Hidden Image Url

Back to Top