Creating Rich, Interactive Web Projects With Symfony Framework

Sometimes you need even more flexibility than a WCMS like WordPress can provide. A framework offers all the flexibility of custom development and can be used to design an application that perfectly meets the expressed needs. It, however, requires development, integration and maintenance related technical expertise.

Providing a rich, interactive experience will increase visitors returning to your website. Symfony, known as a stable and powerful development environment, can be used to create a wide range of Web projects.

Here we provide an introduction to Symfony and a guide to getting started.

Go to:
Project creationCode organizationControllers, Templates, FormsInternationalizationSecurityAssets

Symfony Basics Overview

When creating a web project with Symfony, 1&1 provides the performance you need with the ability to expand as you grow.

Project creation

To make a project, you need to download the symfony.phar file. For Linux users it’s:

$ curl -LsS > symfony.phar
$ sudo mv symfony.phar /usr/local/bin/symfony
$ chmod a+x /usr/local/bin/symfony

For Windows users:

c:> php -r "readfile('');" > symfony.phar

Then copy the symfony.phar file into the folder where your project is stored.

To create a new application, just type the command including your project name. In this example, we call our project “blog.”

# Linux, Mac OS X
$ cd projects/
$ symfony new blog
# Windows
c:> cd projects/
c:projects> php symfony.phar new blog

The default configuration of the application and bundle are created quickly and easily. Now you can start developing.

Configuration of the project

All the configuration files are in app/config and they are composed of four types of files:

  1. Config: installation-specific application settings are stored here.
  2. Parameters: settings concerning the infrastructure (DB, mail).
  3. Security: security settings including all authorization and authentication requirements.
  4. Routing: route settings that allow flexibility for customized URL mapping and easy changes.

It’s always a good idea to make your project configurable using a parameters.yml file. Beginning with version 2.3, Symfony includes the file parameters.yml.dist which can be used as a template for this purpose. Add all of the parameters to this template and the main parameter file (as well as new parameters) so that their settings are maintained when porting the code to the production server.

Symfony supports file configuration formats such as: yml, xml, php array, and annotation. Many configuration examples can be found by doing a simple Google search. In order to convert the necessary service config to a new format, you can use a service like

Code organization

AppBundle is a great resource for developing all of your applications. It is especially convenient if your application is small. If you have a lot of different logics, just cut them into several bundles to make the code easier to understand.

To create a new bundle, use:

php app/console generate:bundle

More information about code organization


To make your code easy and clear to read, it is best to use the “fat-free controller” principle while developing controllers. Ideally, a controller must do four things:

  1. get a request
  2. process the form (if there is any)
  3. call the method of service where there are business logics of your application
  4. give the response

More information about controllers


By having a few entry points, you can use route settings in annotations – otherwise, it is better to use an individual routing.yml file in your bundle settings. Remember to add it to app/cofig/routing.yml

More information about routing


It is recommended to write Symfony templates with a language called Twig. It is a flexible, quick, and powerful means of work with templates.

It’s very convenient to place the layout template in the folder app/views/…, and place the bundle templates in src/YourBundle/Resources/views/ControllerName/templateName.html.twig

In Twig there are 3 types of special syntax (as defined by

{{ ... }}

“Says something”: prints a variable or the result of an expression to the template.

{% ... %}

“Do something”: a tag that controls the logic of the template; it is used to execute statements such as for-loops for example.

{# ... #}

“Comment something”: it’s the equivalent of the PHP /* comment */ syntax. It’s used to add single or multi-line comments. The content of the comments aren’t included in the rendered pages.

Twig streamlines the process of developing templates because it allows you to work with conditions, cycles, filters, and more. In detail: and


Forms are one of the largest components which are used in different ways than their developer intended as they are difficult to work with. Fortunately, Symfony has a form component that simplifies this process.

Always try to create forms in a separate class. An example of class form:

namespace AppBundleForm;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;

class PostType extends AbstractType
     public function buildForm(FormBuilderInterface $builder, array $options)
		->add('summary', 'textarea')
		->add('content', 'textarea')
		->add('authorEmail', 'email')
		->add('publishedAt', 'datetime');
    public function setDefaultOptions(OptionsResolverInterface $resolver)
		'data_class' => 'AppBundleEntityPost'

    public function getName()
          return 'post';

Moreover, try to bind form and entity — it will allow pulling validation and the types of fields from entity configuration automatically.

It’s best to add the form submit button in the template. Usually ‘form submit’ is achieved as follows:


namespace AppBundleForm;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;

class PostType extends AbstractType
     public function buildForm(FormBuilderInterface $builder, array $options)
		->add('summary', 'textarea')
		->add('content', 'textarea')
		->add('authorEmail', 'email')
		->add('publishedAt', 'datetime');
    public function setDefaultOptions(OptionsResolverInterface $resolver)
		'data_class' => 'AppBundleEntityPost'

    public function getName()
          return 'post';

More information about forms



Internationalization and localization adapt the applications and their contents to the specific region or language of the users. With Symfony, this is an opt-in feature that needs to be enabled before using it. To do this, uncomment the following translator configuration option and set your application locale:

# app/config/config.yml
	# ...
	translator: { fallback: "%locale%" }

# app/config/parameters.yml
	# ...
	locale: en

Try to use translation keys, not the lines where it’s necessary to make the translation. The most convenient way to achieve this is to use the yaml file for the translation. It’s often advised to use the xliff format for translation files, but sometimes that format can make things unnecessarily complicated.

Store your translation files in the corresponding bundle in src/YourBundle/Resources/translations/someTranslation.yml


The security settings are often considered to be one of Symfony’s most complex aspects. Here we will try to simplify some of the best practices.

Security settings are stored in app/config/security.yml, most of them are in firewalls. As a reminder: the Security component prevents access to resources that are forbidden for the current user. The security settings include those for authentication (verifying identity) and authorization (providing permission).

For the most purposes, only one firewall is necessary. Sometimes (for example, when you have a Web part and API) you will have to configure two firewalls.

Here is an example of security.yml which provides a login form to get a user from the database:

        AppBundleEntityUser: bcrypt

            entity: { class: AppBundle:User, property: username }

            pattern: ^/
            anonymous: true
                check_path: security_login_check
                login_path: security_login_form

                path: security_logout
                target: homepage

# ... access_control exists, but is not shown here

Symfony provides several ways to authorize users:

  1. In the key access_control in the file security.yml — for security in the URL template
  2. @Security annotation is a very convenient method (preferable in most cases)
  3. Service security.authorization_checker usage – in rare cases

An example of annotation @Security usage.

use SensioBundleFrameworkExtraBundleConfigurationSecurity;
// ...
* @Security("has_role('ROLE_ADMIN')")
public function newAction()
	// ...

Only the user with ROLE_ADMIN will have access to the given action.

More information about Security settings


For convenient work with js/css/images use the Assetic component. You must store assets in src/YourBundle/Resources/public.

It is not enough to just create css and js files and include them into the template file. You will have to compress and minify them, then use the smaller version to accelerate loading time on the client side. Assetic is a great tool to accomplish this. Some simple commands will help to collect and minify files. This command will find and carry all assets in the folder of your Web project:

php app/console assets:install

And the following command will collect all the combinations js and css included in templates into separate files for fast loading on the client side.

php app/console assetic:dump --no-debug

Remember to mention your environment through the parameter –env

You can include files in the template like this:

{% stylesheets
	filter='cssrewrite' output='css/compiled/all.css' %}
	<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
{# ... #}
{% javascripts
	output='js/compiled/all.js' %}
	<script src="{{ asset_url }}"></script>
{% endjavascripts %}

More information about this component

The bundles you will definitely need

Symfony is backed by a large development community that is constantly working toward improvements and enhancements. Over 2,400 bundles are already developed to meet a wide range of needs. Among the many options, you might consider these quality bundles:


FOSUserBundle – allows flexible management of the users in your database.

SonataAdminBundle – assists in creating an admin panel.

SonataUserBundle – integrates FOSUserBundle into SonataAdminBundle.

KnpMenuBundle  – helps to work with menus.

SensioFrameworkExtraBundle – a set of goodies that adds elegance and simplicity to your code by allowing you to configure your controllers with annotations. The component adds the annotations: @Route, @Cache, @Template, @ParamConverter, @Method, and @Security.


Symfony can be used to create Web projects of any size. This article provided an introduction to the Symfony framework and tips for getting started with your first project. Symfony provides a great eBook of best practices which provides much more in-depth information.

Delivering a positive user experience is essential for achieving success online. It is important to ensure that your Web hosting package can accommodate the performance demands of your Web project. Choosing a solution that exceeds your day-to-day requirements can ensure the availability and performance of your website. 1&1’s Web Hosting provides a convenient and powerful environment for even the most resource-intensive Web projects.

For more tips and advice on how to achieve online success, for both beginners and advanced users, visit the 1&1 Blog.

About Symfony

Symfony was first released in January 2007. Since then, the Symfony code has undergone a number of changes. It has a wide field of use ranging from the smallest sites to enterprise-level applications. Symfony components are even used as the basis for a number of other frameworks (for example: Drupal, phpBB, Laravel, and more). This framework has become the world standard of a stable development environment and is sponsored by SensioLabs, which has 13 years of experience in software development.


(This article was initially published on CODEPROJECT)

Please rate this post :

Leave a Reply

Your email address will not be published. Required fields are marked *