Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Javascript
Article

Using Symfony Framework for Creating Web Projects

1 Feb 2015CPOL8 min read 18.9K   1  
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.

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

Introduction

The first release of Symfony took place 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.

Symfony is based on six principles:

  1. Minimization of development time and application support, as well as the minimization of duplicate actions during development.
  2. Unlimited flexibility of applications: Event Dispatcher and Dependency Injection allows you to do incredible things with the code.
  3. Scalability: all components of the application are presented in the form of easy-to-plug Bundles (reusable blocks that provide additional functionality).
  4. Stability: SensioLabs guarantees the support of major versions for three years.
  5. Satisfaction with development: the framework provides a very convenient structure (debug bar, profiler, etc) to make developers’ life easier.
  6. Huge amount of documentation helps beginners understand the code.

When creating a Web project with Symfony, it’s important to use a reliable and powerful Web hosting provider like 1&1 Internet.

Project creation

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

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

For Windows users:

c:\> php -r "readfile('http://symfony.com/installer');" > 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 http://converter.rosstuck.com/

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

Further details can be found at: http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_bundle.html

Controllers

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

In detail: http://symfony.com/doc/current/best_practices/controllers.html

Routing

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

For further information about routing: http://symfony.com/doc/current/book/routing.html

Templates

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 three types of special syntax (as defined by Symfony.com):

{{ ... }}

"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: http://symfony.com/doc/current/book/templating.html and http://twig.sensiolabs.org/

Forms

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 AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class PostType extends AbstractType
{
     public function buildForm(FormBuilderInterface $builder, array $options)
    {
           $builder
		->add('title')
		->add('summary', 'textarea')
		->add('content', 'textarea')
		->add('authorEmail', 'email')
		->add('publishedAt', 'datetime');
    }
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
   {
          $resolver->setDefaults(array(
		'data_class' => 'AppBundle\Entity\Post'
          ));
   }

    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:

public function newAction(Request $request)
{
	// build the form ...
	$form->handleRequest($request);
	if ($form->isValid()) {
		$em = $this->getDoctrine()->getManager();
		$em->persist($post);
		$em->flush();
		return $this->redirect($this->generateUrl(
			'admin_post_show',
			array('id' => $post->getId())
		));
	}
	// render the template
}

In the eBook "Symfony best practices"

if ($form->isValid()) { …. }

looks as

if ($form->isSubmitted() && $form->isValid()) {….}

but $form->isSubmitted() is not necessary, as the given check is also made in $form->isValid().

For further information about forms: http://symfony.com/doc/current/book/forms.html

Internationalization

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
   framework:
	# ...
	translator: { fallback: "%locale%" }

# app/config/parameters.yml
   parameters:
	# ...
	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

Security

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:

security:
    encoders:
        AppBundle\Entity\User: bcrypt

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

    firewalls:
        secured_area:
            pattern: ^/
            anonymous: true
            form_login:
                check_path: security_login_check
                login_path: security_login_form

            logout:
                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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
// ...
/**
* @Security("has_role('ROLE_ADMIN')")
*/
public function newAction()
{
	// ...
}

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

You will find more information about Security settings here: http://symfony.com/doc/current/book/security.html

Assets

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
	'css/bootstrap.min.css'
	'css/main.css'
	filter='cssrewrite' output='css/compiled/all.css' %}
	<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
{# ... #}
{% javascripts
	'js/jquery.min.js'
	'js/bootstrap.min.js'
	output='js/compiled/all.js' %}
	<script src="{{ asset_url }}"></script>
{% endjavascripts %}

You can find further information about this component here: http://symfony.com/doc/current/cookbook/assetic/asset_management.html

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.

Conclusion

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 Community or the 1&1 Blog.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
1&1 Internet
United States United States
1&1 is a subsidiary of United Internet, a profitable public company with a market cap of over $8 billion. Founded in 1988, 1&1’s global community is over 13 million customer contracts strong. The 1&1 Group manages more than 19 million domain names worldwide with more than 70,000 servers run in 1&1’s seven state-of-the-art, green data centers.

Known for its comprehensive and affordable Internet products, 1&1 is Europe’s leading Web host and one of the top 5 Web hosts in the United States. From domain registration to Web hosting, site creation, technical support and cutting edge technology, 1&1 offers users every available resource to easily and affordably create and maintain an optimal online presence.

Comments and Discussions