34,79 €
Orchestrate the designing, development, testing, and deployment of web applications with Symfony
If you are a PHP developer with some experience in Symfony and are looking to master the framework and use it to its full potential, then this book is for you. Though experience with PHP, object-oriented techniques, and Symfony basics is assumed, this book will give you a crash course on the basics and then proceed to more advanced topics.
In this book, you will learn some lesser known aspects of development with Symfony, and you will see how to use Symfony as a framework to create reliable and effective applications. You might have developed some impressive PHP libraries in other projects, but what is the point when your library is tied to one particular project? With Symfony, you can turn your code into a service and reuse it in other projects.
This book starts with Symfony concepts such as bundles, routing, twig, doctrine, and more, taking you through the request/response life cycle. You will then proceed to set up development, test, and deployment environments in AWS. Then you will create reliable projects using Behat and Mink, and design business logic, cover authentication, and authorization steps in a security checking process. You will be walked through concepts such as DependencyInjection, service containers, and services, and go through steps to create customized commands for Symfony's console. Finally, the book covers performance optimization and the use of Varnish and Memcached in our project, and you are treated with the creation of database agnostic bundles and best practices.
A step-by-step guide to mastering Symfony while developing a task management application. Each chapter comes with detailed examples.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 283
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2016
Production reference: 1210416
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-031-0
www.packtpub.com
Author
Sohail Salehi
Reviewers
Mickaël Andrieu
Vincent COMPOSIEUX
Tito Miguel Costa
Commissioning Editor
Usha Iyer
Acquisition Editors
Tushar Gupta
Richard Harvey
Content Development Editor
Aishwarya Pandere
Technical Editors
Pranil Pathare
Danish Shaikh
Copy Editor
Tasneem Fatehi
Project Coordinator
Nidhi Joshi
Proofreader
Safis Editing
Indexer
Mariammal Chettiyar
Production Coordinator
Nilesh Mohite
Cover Work
Nilesh Mohite
Sohail Salehi is a full stack web developer who is constantly seeking creative solutions for complex problems. He believes that what has been taught as universalities should be considered as a basic stepping stone to real-life challenges. They cannot be used as practical solutions. He learned that a one-size-fits-all solution does not work in the IT world. Every business, every coding challenge, and every environment setup has its own signature and requires some tweaking on basic principals to make sure that it receives a reliable cost-effective solution.
When he is not staring at his computer screen, he is watching sunsets and sunrises, swimming and surfing in the ocean, and putting his subconscious mind at work by asking creative questions while facing life's ups and downs on a daily basis.
I would like to thank the Packt Publishing team for being supportive at all times and also being patient with me at the times I've gone wild and updated the book contents over and over again.
Mickaël Andrieu is a passionate open source engineer, contributor, and maintainer of projects such as Symfony, CasperJS, and Certificationy. He is currently a core developer and technical evangelist of the open source e-commerce solution, PrestaShop, built around the Symfony framework in its latest version. An ex-developer at SensioLabs, he has accumulated good expertise in PHP and the Symfony framework.
When he is not working on his own project, he teaches best development practices to engineering students or advices big companies on their open source strategies.
He has worked at SensioLabs and Lp digital system.
He will probably be working on another book, as Llewellyn F. Rozario just contacted him for another review.
Vincent COMPOSIEUX is a French web engineer who loves technologies such as PHP, Python, NodeJS, and Go. He is based in Paris and working at Ekino, a French web agency that focuses on quality.
Previously, he has worked for e-commerce companies and web agencies on multiple web projects with high traffic.
He loves web technologies and frameworks and has experience using the Zend framework, Magento, and Symfony.
He has great experience of Symfony because he has been using it since the very first version and is actively involved in the Symfony community.
Indeed, he has developed some bundles such as FeedBundle to manage RSS and Atom feeds, GoogleTranslateBundle to use the Google Translate API to translate content, and some others. He is also a contributor to the Sonata bundles suite.
You can contact him and see more on his personal website, http://vincent.composieux.fr.
Tito Miguel Costa is a full stack web application developer with over 10 years of experience in PHP. He started using Symfony back in 2007, when version 1.0 was released and it remains his favorite framework until now. Back in Portugal, where he is originally from, he organized several courses and oriented a dissertation on how to optimize and scale projects built with Symfony. Currently, he maintains several open source bundles and works as a senior Symfony developer at Lendable, one of the most promising start-ups in London.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Welcome to your journey in Mastering Symfony. It is my duty and absolute pleasure to show you a different side of Symfony's world and take your development knowledge to a whole new level. In this book, I will not only sharpen your Symfony skills, but will also show you how to look at a project from different angles.
As a backend developer, you can always stick to your skill set and deliver a good job. However, it would be excellent if we could experience the way a business requirement is born, how a project manager sees the problem, what kind of technologies a system administrator uses to host the project, and how it affects developers, before finally knowing how to establish a more efficient work flow with frontend developers.
Having already published a few books, I am proud to say that this one—Mastering Symfony—is unique. After warming you up with some introductory materials, I will take you to the heart of the devil and show you how to find your way around a seriously robust project with mountains of real-life challenges. To run this show properly, I needed a decent-size stage. That's why I've decided to build a project management web application over the tutorials of this book. This web application gives me enough space to explore and expand many of Symfony's features required for my goal.
After the two introductory chapters, I will talk about how to set up a project properly. In other words, I will discuss the importance of concepts such as version control, continuous integration, deployment process, behavior-driven development, and so on. I will use Amazon Web Services to host our development, test, and deployment servers and show you how to integrate AWS tools and technologies into your Symfony project.
Then, I will talk about why the development culture has changed recently and why, before writing a single line of code, we have to be clear about scenarios and behaviors. I will discuss Behat and Mink and, more importantly, show you how to utilize them in your projects.
Finally, after I feel confident about everything being in the right place, we will start the real coding. In our Model layer, we will create business logic via Doctrine and feed it with data fixtures. In our Controller layer, we will develop and use a dozen of amazing functionalities coming from various bundles, and in our View layer, we will explore the Twig template engine thoroughly and implement slick frontend features and mobile functionality with the Bootstrap 3.x framework.
A good web app should be able to provide decent security, a user-friendly dashboard, and reasonable speed. That's where I will expand the security concept in Symfony and discuss the Sonata project, followed by the idea of CMF. For those who concern themselves with performance, I will show you how to create blazing fast Symfony applications with the help of reverse proxy caching systems such as Varnish.
Chapter 1, Installing and Configuring Symfony, helps you understand the idea of packages and package management along with the installation of Symfony.
Chapter 2, The Request and Response Life Cycle, introduces you to basic Symfony concepts such as bundles, routing, twig, doctrine, and so on over the course of a request/response life cycle.
Chapter 3, Setting Up the Environment, shows you how to set up development, test, and deployment environments in AWS and set up Behat and Git for BDD and version control respectively.
Chapter 4, Using Behavior-Driven Development in Symfony, covers Behat and Mink and how to use them to create reliable projects.
Chapter 5, Business Logic, discusses the model layer and Doctrine thoroughly.
Chapter 6, Dashboard and Security, shows you authentication and authorization steps in a security checking process and how to create a control panel for our project using the Sonata project and its bundles. The FOSUserBundle will be explained as well.
Chapter 7, The Presentation Layer, discusses the Twig template engine and Bootstrap 3.x framework. We will see how to use a bundle to integrate Bootstrap into our templates.
Chapter 8, Project Review, reviews what we have created so far and optimizes the code further.
Chapter 9, Services and Service Containers, explains concepts such as Dependency Injection, Service Containers, and Services.
Chapter 10, Custom User Commands, walks you through the steps to create customized commands for Symfony's console.
Chapter 11, More about Dev, Test, and Prod Environments, is a short chapter about Symfony environments. We will see how different they are from each other, how we can customize them based on project requirements, and how to create our own environments with their own front controller.
Chapter 12, Caching in Symfony, talks about performance optimization and the usage of Varnish and Memcached in our project.
Although examples of this book can be adapted and executed on any machine, my headspace is mainly around Linux and OSX platforms. For a deeper focus on the subject itself, I would suggest a Windows user to install Linux via a virtual machine such as Oracle's VirtualBox and follow the samples in a Linux environment. In Chapter 3, Setting Up the Environment, we will need an AWS account. Thanks to Amazon, there is a 1-year free tier account, which gives us enough resources to follow examples in this book. Before installing Symfony, make sure that you have the latest stable version of PHP and MySQL installed already. Having a database management application such as MySQL Workbench, HeidiSQL, or NaviCat is optional but it is nice to have them.
This book is for PHP developers who have already used Symfony and are looking to master the framework to its fullest potential. In other words, I presume that you have been using PHP and object-oriented techniques for a while and are familiar with Symfony basics already. To make sure that we are on the same page, I will give you a crash course at the beginning of this book; then we will explore more advanced topics as we proceed.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringSymfony_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
This chapter is merely a refresher for those who are pretty confident in using Symfony and an introduction for those who are quick learners! You can expect to read about how to install the Symfony Standard Edition package and manage its dependencies via Composer. After installation, we will check to make sure that everything is configured properly. The following are the main topics that we will talk about in this chapter:
I don't like to talk about features, numbers, and statistics. I don't do detailed comparisons between frameworks as well. Instead, I'd like to share an experience with you. As a PHP developer, I worked for the New Zealand Herald newspaper for a while. Sure, they are not the oldest newspaper in the world, but in 2013, they celebrated their 150th anniversary, which makes it very clear that over the years, they have created layers and layers of code on top of each other and used or tried almost every framework and technology in their website and internal newspaper systems. Their repositories contain tons of legacy codes written in different languages. You won't believe it if I say different parts of their system were implemented in Perl, Java, C#, ColdFusion, and PHP, and there was (perhaps, still is?) an API layer that acts as a communicating bridge between all of them.
Due to many factors such as maintenance costs, in the past few years, people at the NZ Herald decided to migrate their entire applications and services into one integrated system; something that is reliable, efficient, and easy to expand and maintain. Having experienced many frameworks already, the solution architects at NZ Herald chose Symfony as their framework.
They realized that those colorful graphs and pretty pictures that compare benchmarking results for various frameworks are worth nothing when it comes to real-life problems. They experienced the efficiency of various frameworks in the day-to-day challenges and understood that no matter how fast the development speed might look at the beginning, the most important thing is how reliable it actually is and how much it costs when it comes to maintaining the project. They simply put a price tag on many factors including performance, abstraction, decouplement, portability, integration, and above all, how well organized the code base will be after spending several years and using several men for the development. Guess what? Symfony beat every PHP framework out there.
What I'm trying to say is that Symfony is not just another tool for web app or website development. It is a new culture for web development, a solid reliable foundation that you can build your project on top of with peace of mind. I call it a new culture because for the first time, I see that it has made various PHP communities talk to each other and work together. I believe this is the most important PHP achievement ever. In the years to come, we will see more about this movement.
I believe one of the main reasons why Symfony stands out of the crowd is the way it defines the Model-View-Controller (MVC) design pattern. This is the key: Symfony defines MVC while many other frameworks try to simply follow MVC rules. Can you see the difference? This means that Symfony contains MVC but does not constrain it. Have a look at the MVC definition and keep it in mind that as we continue the journey through the chapters of this book, you will see what I mean by this. Maybe, this is reason that other PHP frameworks and Content Management Systems (CMS) adapted the Symfony components and started to follow in its footsteps.
If you look at the following link, you will see the other great players such as Drupal, phpBB, Laravel, Composer, Doctrine, Behat, and many others who use and benefit from Symfony components:
http://symfony.com/projects
For those who concern themselves with performance and their judgment is blinded by Hello World benchmarking results, I can talk about large companies such as BBC, CBS, and many others who chose Symfony.
Please don't tell me that these big boys didn't do due diligence before making a big decision like choosing a framework. They know the amount of pressure their website receives on a hourly basis and they do care about the quality of their service. There must be a good reason that they chose Symfony over other frameworks. In a nutshell, Symfony helps have a better organized code that reduces the maintenance costs tremendously and, at the same time, it can benefit from modern caching systems such as Varnish, which help with a better performance. Chapter 12, Caching in Symfony is all about performance improvement and caching systems.
In December 2013, when Fabien Potencier—the creator of Symfony—announced that he raised seven million dollars to boost Symfony and its ecosystem, I literally dropped other frameworks and decided to invest and focus even more on Symfony.
It is clear to me if he was capable of making his mark without raising money, then from 2014 onwards, he will be able to make a huge impact on the PHP world.
Don't get me wrong; I've been using other frameworks and respect other teams who made an effort to create a web development tool with PHP. I have used famous frameworks such as Zend to domestic packages such as MySource Matrix and SilverStripe. As a hobbyist, I also try new libraries and ideas in the open source world. However, every PHP developer needs to choose a right direction and set of tools as his main weapon. For me, it is Symfony, and I can see that Symfony developers will be in even higher demand soon.
Assuming that you are an experienced PHP developer and familiar with open source development, the tutorials in this book are provided for Linux and Mac platforms. I politely invite Windows users to install a VM application such as Oracle VirtualBox and any Linux distribution to follow the provided examples. You can download it from https://www.virtualbox.org/.
There are four ways to install the Symfony framework:
The easiest way is to download the Symfony installer and make it publicly accessible via the following commands:
Now create a new project simply by running the following command:
As this command shows, it will ask the Symfony installer to create a new folder in the current path called mava, and when you hit enter, you will see that the Symfony source code will be downloaded to that folder:
If you don't mention a version number or branch name in the installer command, it downloads and installs the latest stable version of Symfony.
In the list of things that we can do after installation is running the application immediately, without installing a virtual host. Thanks to the PHP built-in web server, we can run it via Symfony's console and browse the mava app at port 8000 on localhost:
The following screenshot shows how http://localhost:8000 looks like in your favourite browser:
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
Composer is a dependency manager application that can be used to install PHP packages.
Some developers prefers Composer, not just because it is easy to use, but it is far more efficient when it comes to keeping track of the project dependencies. In fact, the main reason for creating Composer was to provide a reliable and consistent environment to develop PHP projects.
Imagine a team of PHP developers who work on the same project using various libraries and resources. Sometimes, it can be a nightmare if updating an existing library or installing a new one crashes the code of another developer in the team. Someone should be in charge of tracking all dependencies and controlling the updates and installs to make sure that the project development runs smoothly. In the past, that person used to be the lead developer, but thanks to Composer, the dependency management during development, staging, and production phases is handled automatically by Composer.
Let's get started by downloading Composer if you don't have it already:
I presume that you have already installed the latest stable version of PHP and required extensions and libraries including curl. In case you don't have curl, you can install Composer via the following command:
Move it to your /usr/local/bin folder so that it is accessible from everywhere in your machine:
Depending on the distribution of your Linux, this path might be /usr/bin instead. Use the echo $PATH command to find out about the location.
Composer is just a manager. It does not store any libraries or packages in itself. However, it works very closely with a package repository called Packagist to make sure that it gets the right packages with the correct dependencies. To do so, Packagist talks to Composer via a configuration file called composer.json, which contains many settings including dependency information.
Symfony Standard Edition is a package saved in https://packagist.org/. Go to the website and search symfony and you will see the Symfony framework along with a list of Symfony components as the search result:
In this book, we will deal mainly with three Composer commands:
Let's see how to install the Symfony Standard Edition package via Composer.
Did you know that with the self-update option, you can upgrade the Composer to the latest stable version?
Fire a terminal and go to /var/www. I chose to install Symfony there to keep it simple and avoid different usernames and folders. Create a new folder called mava and set the ownership to yourself:
Now type the following command: