Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Symfony2 Essentials
Symfony2 Essentials

Symfony2 Essentials:

eBook
R$80 R$147.99
Paperback
R$183.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Symfony2 Essentials

Chapter 2. Your First Pages

Most modern PHP frameworks follow a classic MVC concept. Symfony2 is also an MVC framework, so we do have controllers, models, and views. In this chapter, we will learn about these building blocks to see how Symfony2 organizes things:

  • Review of the default bundle structure and recommendations
  • Setting up the first routings and controllers for the home screen
  • Working with templates
  • Creating the initial database schema and models
  • Loading sample fixtures
  • Looking into migration throughout the chapter

Everything is a bundle

In the previous chapter, we dug in to the basic Symfony2 directory structure. Within the src directory, we already had two bundles: one called DemoBundle within the Acme subdirectory and the other one within AppBundle.

DemoBundle is a showcase of an example bundle that has existed since the beginning of Symfony2. It has been created to demonstrate how Symfony2 organizes things. AppBundle is a relatively new thing, introduced in Symfony 2.6 with a new concept of work.

Until the 2.6 version, it was recommended to contain a bundle within the vendor namespace. With Symfony 2.6 and its new best practices rules, it is now recommended to keep the custom application code within the handy AppBundle and create other bundles only if you want to create reusable code to be shared among your other projects.

Bundles don't have a fixed directory structure. In fact, you can have a bundle without most of the directories. If you create a utility bundle, it will probably have only...

The configuration format

Symfony2 can handle configuration in different formats: YAML, XML, and annotations. The main configuration files within app/config are provided with the YAML format. XML is usually harder to read, and is used only with third-party bundles.

While both YAML and XML configuration are pretty straightforward and need no explanations, we should stop by annotations for a while. As an example, see the AppBundle/Controller/DefaultController class:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath(
                $this-&gt...

Cleanups

Before we start writing our own app, we need to do some cleanups. We need to configure AppBundle to use the YAML configuration. While this is possible to switch the configuration format manually, we will remove the bundle (it doesn't contain much code yet), and we will generate a new bundle to demonstrate new bundle creation.

Recreating AppBundle

To recreate AppBundle, remove it first as follows:

$ rm -rf src/AppBundle

Remove it from app/AppKernel.php by removing the following line:

new AppBundle\AppBundle(),

Remove it's routing (app/config/routing.yml), which is as follows:

app:
    resource: @AppBundle/Controller/
    type:     annotation

Now we will need to generate it again. Issue the following command:

$ php app/console generate:bundle --namespace=AppBundle

Now provide the following answers to the generator:

Bundle name [AppBundle]: [Enter]
Target directory [.../todoapp/src]: [Enter]
Configuration format (yml, xml, php, or annotation): yml
Do you want to generate the whole...

Routing

Like with many other frameworks based on the concept of MVC, before any controller is actually executed, Symfony2 needs to know how to handle it. The Symfony routing configuration starts within the app/config/routing_*.yml file. Depending on which environment you fire up, this version of routing is fired up. Usually, this environment file loads the main app/config/routing.yml file, which loads other files from vendors, bundles, and so on. You can, of course, directly define your own single routings here, but it's usually recommended to keep the bundle-specific routings within the bundle itself, while using the main routing only to import resources.

As per the example provided earlier in this chapter, we know our app tries to import another resource file defined as @AppBundle/Resources/config/routing.yml. The @BundleName syntax is a shortcut to the bundle namespace (in our case AppBundle) but namespace can be longer if you include the vendor in your name. Let's take a look...

Templates – the View layer

Each MVC framework offers the View layer, and Symfony2 is no different. In Symfony1, we were using plain PHP code. Symfony has introduced a new templating engine named Twig. The Symfony syntax is more elegant — it's shorter and designed to be cleaner than regular PHP code in templates.

Note

We can still use it now. However, it's not the recommended approach, as in most cases, you will not find examples of a working bundle code in pure PHP.

Let's take a look at the template code within our bundle, src/AppBundle/Resources/views/Default/index.html.twig:

Hello {{ name }}!

Yes, this is it. As you can figure out, {{ name }} outputs the variable name. It is an equivalent of <?php echo $name; ?>. The code actually doesn't do much, and it is not a valid HTML code (it just outputs some text). Let's modify it a little:

{% extends '::base.html.twig' %}

{% block body %}
Hello {{ name }}!
{% endblock body %}

Now try to fire http...

Everything is a bundle


In the previous chapter, we dug in to the basic Symfony2 directory structure. Within the src directory, we already had two bundles: one called DemoBundle within the Acme subdirectory and the other one within AppBundle.

DemoBundle is a showcase of an example bundle that has existed since the beginning of Symfony2. It has been created to demonstrate how Symfony2 organizes things. AppBundle is a relatively new thing, introduced in Symfony 2.6 with a new concept of work.

Until the 2.6 version, it was recommended to contain a bundle within the vendor namespace. With Symfony 2.6 and its new best practices rules, it is now recommended to keep the custom application code within the handy AppBundle and create other bundles only if you want to create reusable code to be shared among your other projects.

Bundles don't have a fixed directory structure. In fact, you can have a bundle without most of the directories. If you create a utility bundle, it will probably have only some...

The configuration format


Symfony2 can handle configuration in different formats: YAML, XML, and annotations. The main configuration files within app/config are provided with the YAML format. XML is usually harder to read, and is used only with third-party bundles.

While both YAML and XML configuration are pretty straightforward and need no explanations, we should stop by annotations for a while. As an example, see the AppBundle/Controller/DefaultController class:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath(
                $this->container
                     ->getParameter...

Cleanups


Before we start writing our own app, we need to do some cleanups. We need to configure AppBundle to use the YAML configuration. While this is possible to switch the configuration format manually, we will remove the bundle (it doesn't contain much code yet), and we will generate a new bundle to demonstrate new bundle creation.

Recreating AppBundle

To recreate AppBundle, remove it first as follows:

$ rm -rf src/AppBundle

Remove it from app/AppKernel.php by removing the following line:

new AppBundle\AppBundle(),

Remove it's routing (app/config/routing.yml), which is as follows:

app:
    resource: @AppBundle/Controller/
    type:     annotation

Now we will need to generate it again. Issue the following command:

$ php app/console generate:bundle --namespace=AppBundle

Now provide the following answers to the generator:

Bundle name [AppBundle]: [Enter]
Target directory [.../todoapp/src]: [Enter]
Configuration format (yml, xml, php, or annotation): yml
Do you want to generate the whole directory...

Routing


Like with many other frameworks based on the concept of MVC, before any controller is actually executed, Symfony2 needs to know how to handle it. The Symfony routing configuration starts within the app/config/routing_*.yml file. Depending on which environment you fire up, this version of routing is fired up. Usually, this environment file loads the main app/config/routing.yml file, which loads other files from vendors, bundles, and so on. You can, of course, directly define your own single routings here, but it's usually recommended to keep the bundle-specific routings within the bundle itself, while using the main routing only to import resources.

As per the example provided earlier in this chapter, we know our app tries to import another resource file defined as @AppBundle/Resources/config/routing.yml. The @BundleName syntax is a shortcut to the bundle namespace (in our case AppBundle) but namespace can be longer if you include the vendor in your name. Let's take a look at the bundle...

Left arrow icon Right arrow icon

Description

Symfony is a free and open source PHP MVC web application development framework, which helps you create and maintain web applications and replace recurrent coding tasks. It integrates with an independent library, PHPUnit, to give you a rich testing framework. It is one of the best and most popular frameworks available on the market. Popular projects such as Drupal, Laravel, and phpBB also use Symfony. Its well-organized structure, clean code, and good programming practices make web development a breeze. Symfony2 Essentials will guide you through the process of creating a sample web application with Symfony2. You will create a To-Do application, using a few of the most commonly used Symfony2 components, and discover how to perform these development tasks efficiently. This book introduces you to the Symfony framework with a quick installation guide and a brief explanation of its key features including the MVC architecture, twig templating, dependency injection, and more. You will learn to manage dependencies, create controllers, views, and API calls, and secure your application. Next, you will go through the steps that are common for most web applications, which include writing CRUD and AJAX, handling forms, validation, translations, and the command-line interface, and e-mail sending features. The book ends with best practices, debugging, profiling, and deployment procedures. By the end of this book, you will have learned how to combine a Symfony2 framework with other open source code to speed up the development process.

Who is this book for?

This book is aimed at experienced programmers, especially those familiar with a closely related technology such as Yii or Laravel, but who now want to learn Symfony quickly.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 08, 2015
Length: 158 pages
Edition : 1st
Language : English
ISBN-13 : 9781784395933
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 08, 2015
Length: 158 pages
Edition : 1st
Language : English
ISBN-13 : 9781784395933
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 647.97
Symfony2 Essentials
R$183.99
Mastering Symfony
R$245.99
Extending Symfony2 Web Application Framework
R$217.99
Total R$ 647.97 Stars icon

Table of Contents

11 Chapters
1. The Symfony Framework – Installation and Configuration Chevron down icon Chevron up icon
2. Your First Pages Chevron down icon Chevron up icon
3. Twig Templating and Assets Handling Chevron down icon Chevron up icon
4. Forms Chevron down icon Chevron up icon
5. Security and Handling Users Chevron down icon Chevron up icon
6. Translation Chevron down icon Chevron up icon
7. AJAX Chevron down icon Chevron up icon
8. Command-line Operations Chevron down icon Chevron up icon
9. Symfony2 Profiler and Debugger Chevron down icon Chevron up icon
10. Preparing an Application for Production Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7
(7 Ratings)
5 star 0%
4 star 28.6%
3 star 28.6%
2 star 28.6%
1 star 14.3%
Filter icon Filter
Top Reviews

Filter reviews by




Madchu Oct 08, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
It took me two attempts to get through this, but that was mainly because I've been trying to learn everything and Symfony, at first glance, was a little daunting. The author covers things well, though, so I'm glad I gave this a second go. it complements well with an online course on Symfony from KNP University which is the best I've found so far on the subject.
Amazon Verified review Amazon
AlberT Nov 08, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Un libro che scorre facilmente, affronta più o meno tutti gli aspetti del ciclo di vita di una applicazione symfony ..Nulla di particolarmente illuminante, ma sicuramente una buona infarinatura generale.
Amazon Verified review Amazon
D. Cullen Feb 21, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Mistakes in the examples make it tricky for someone completely new to symfony, but otherwise ok.
Amazon Verified review Amazon
Spurgeon Jun 07, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Good book for experienced PHP developers to acquaint themselves with Symfony. Considering that Symfony 3 is out some time back, this might be slightly outdated. Nevertheless, the foundations / fundamentals hold good.
Amazon Verified review Amazon
Amazon Customer Feb 15, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
very basic book, you could find better guides on the web.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.