9

Symfony Enterprise Applications Sample

Embed Size (px)

DESCRIPTION

Symfony Enterprise Applications Sample

Citation preview

  • Symfony Enterprise ApplicationsYour guide on building enterprise level web applicationswith Symfony

    Daniel RibeiroThis book is for sale at http://leanpub.com/symfony-enterprise-applications

    This version was published on 2014-03-12

    This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

    2014 Daniel Ribeiro

  • Tweet This Book!Please help Daniel Ribeiro by spreading the word about this book on Twitter!The suggested hashtag for this book is #symfonyenterpriseapplications.Find out what other people are saying about the book by clicking on this link to search for thishashtag on Twitter:https://twitter.com/search?q=#symfonyenterpriseapplications

  • Contents

    Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iWhy I wrote this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iWho am I, really? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

    1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1 Installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Virtual Host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

    2 Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.1 Why use them? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.2 Creating Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.3 Organizing things . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

  • IntroductionWhy I wrote this bookMy name is Daniel Ribeiro, and I am a seasoned developer who happens to be passioned withSymfony. That passion was the trigger for me to write this book. But of course one reason does notmake up for all the effort of writing a whole book. There were a few other more reasons to havewritten the book you are reading now, and Id like to share that with you briefly. So if you can pleasefollow along:

    1. I love to work for and with the community yes, the for comes before the with. I believeif you contribute, you will eventually get something back. I dont know the form it will getback to you, but it for sure will.

    2. I love to build enterprise level applications with PHP, and that became a solid reality, inmy opinion, when Symfony 2.x was released especially concerning the PHP part of thatstatement.

    3. I love to share knowledge. Its my nature. That helps me focus on always being up-to-date interms of what is out there on the open-source world.

    Those reasons and some other small ones that are not that relevant made me write and publish thisbook. I hope you enjoy reading it and that it pays off for you. I honestly hope so.

    Who am I, really?I am a seasoned developer from Brazil, with almost 10 years as of the writing if this book ofexperience with web applications in general. Ive went through a lot of different companies in Braziland worked with a major variety of application domains, including e-commerce, content manage-ment, payment processing, text analysis, social networks, resource planning, voice communicationsand multimedia, etc.I am currently working for a company called KnpLabs, which specializes in web applicationdevelopment with the Symfony framework mostly focusing start-up businesses. That positionallows me to constantly evolve in technical and social terms and always be active inside the open-source community contributing to projects often related to Symfony.If you would like to know a little bit more about me, you can check my personal website, whereI maintain a blog where I talk about PHP, Symfony and other nice stuff. You can also find someprojects I work on and more info about myself.

    http://knplabs.comhttp://danielribeiro.org

  • 1 Getting Started1.1 InstallingThe best way to get started with Symfony and install it on your local development machine is byusing Composer. With Composer, you can start a Symfony project with just one simple command here Ill just assume you have an alias for calling the composer binary globally:

    1 composer create-project symfony/framework-standard-edition /path/of/app 2.4.*

    Here is a critical part of the installation: the decision of Symfonys version. And that leads us toSymfonys release process. You can read about it on the website to understand it better, but hereare some thoughts from me:

    1. Always look for stable versions. It really doesnt matter if you go for 2.3 or 2.4 which arethe most recent ones. What matters is if you want your application to be the most stable itcan be, the reasonable choice is to go for a stable version of the its base framework.

    2. Be aware of the difference between a Standard Release and a Long Term Support Release.Using the latest versions as examples, the 2.3 is a LTS Release, while 2.4 is a Standard Release.The main difference is that the LTS version will receive maintenance for a considerable longerperiod of time.

    The next steps would be to setup permissions on the app/logs and app/cache directories and, ofcourse, setup a virtual host on your web server so that you can access your new application.

    1.2 Virtual HostWhether you chose to use Nginx, Apache or anything else as your web server, you will need to setupa virtual host following some conventions in order to access your new application. With that said,here goes some generic tips for your web server and virtual host configurations:

    1. Try to always expose the front controller file for Symfonys different environments beingapp_dev.php for the development environment and the app.php for the production environ-ment. That way you can navigate through environment and their unique configurations tosimulate the application running in different conditions easily.

    http://getcomposer.orghttp://symfony.com/doc/current/contributing/community/releases.html

  • 2 BundlesThe Symfony Official Documentation describes Bundles as:

    A bundle is simply a structured set of files within a directory that implement asingle feature. You might create a BlogBundle, a ForumBundle or a bundle for usermanagement (many of these exist already as open source bundles). Each directorycontains everything related to that feature, including PHP files, templates, stylesheets,JavaScripts, tests and anything else. Every aspect of a feature exists in a bundle andevery feature lives in a bundle.

    The thing is the concept of bundle is actually really misunderstood by some people who use Symfonyas a full-stack framework. Without really understanding that concept, people tend to create bundleswith lots of dependency between them and tight coupling code beucase of the structure they comeup with.

    2.1 Why use them?It makes a lot of sense to create bundles to integrate third-party libraries or solve specific andcommon problems into a Symfony application. Bundles like FOSRestBundle, KnpSnappyBundleor RespectValidationBundle are great because they serve this purpose.But when you are developing a web application, the heart of that application you can call it thedomain, the model or whatever else is almost always independent from the framework you areusing. You need your business specific code to be portable to any framework you want to at anytimeduring the development of that application.

    Does it make sense to have domain, businessspecific code inside generic bundles?It really depends, but generally no. Business specific code is, basically, spread throughout aservice layer, a domain model and some other important architectural concepts. However,if you know some business code should be reused in two different applications of the samedomain, maybe thats the perfect time to wrap them in bundles.

    http://symfony.com/doc/current/book/page_creation.html#page-creation-bundleshttps://github.com/FriendsOfSymfony/FOSRestBundlehttps://github.com/KnpLabs/KnpSnappyBundlehttps://github.com/Respect/ValidationBundle

  • 2 Bundles 3

    Lets take a look at a quick example: a simple web application, something like a website that holdsboth a blog and a forum for their users. Lets consider, for the sake of the example, that the forumand the blog are accessed by the same users. Those users use the same login and password for bothapplications. The User entity would be shared by the ForumBundle and the BlogBundle, right?

    1 src/2 Vendor/3 Product/4 BlogBundle/5 ForumBundle/6 SiteBundle/

    Now comes a simple and recurring question: where should you place the User entity? Inside theForumBundle? Or the BlogBundle? Shold you create a separate bundle to hold all features related tothe user entity, like a UserBundle? For that problem, people come up with all kinds of solutions.Ive seen bundles created just with the purpose of holding entities, such as EntityBundle. Ive alsoseen bundles that are considered to exist on a different layer in comparison to the other ones, sothey come up with a CommonBundle or a AppBundle. Still, the problem persists. What is the problemagain? Having to follow a bundle structure for a non-compliant case. Should the User entity reallybe inside a bundle? Dont worry, well discuss that later on this book.

    2.2 Creating BundlesThe best way to create Bundles inside Symfony is to use the built-in console command:

    1 app/console generate:bundle

    2.2.1 NamespaceThat command will prompt you for some things, one of them being the Bundle namespace. Now,Symfony has a few different options of namespaces for Bundles, but my experience tells me that youshould always place Bundles inside a Bundle namespace kind of obvious, huh? That way, yourBundle namespace would look like something near to Vendor\Bundle\SomeBundle and the classname, something like VendorSomeBundle.

    WarningThe command mentioned above is going to ask for you to use "/" instead of "\".

  • 2 Bundles 4

    2.2.2 ConfigurationYou will also need to choose a configuration format for your Bundle YAML, XML, PHP orAnnotation. Again, my experience tells me that here you should avoid Annotations. They are agreat resource that allows you to have more flexibility and readability on your configurations.But everything has disadvantages. The collateral effect annotations can cause in your code is tightcoupling with the library responsible for parsing them. Not using them makes your code cleanerand easy to interact with different frameworks later on.So what format should you go for? Id say XML. Its advantage over the others are plain and simple:

    1. Is faster than YAML PHP wins here2. Can be auto-completed in most recent IDEs3. Has no external dependency while YAML depends on a parser component

    You can read more about those differences on Fabiens blog where I took some of the items abovefrom.

    2.2.3 Directory Structure and Kernel updateI dont know why the default option for generating the Bundle directory structure is no. Of courseyou want to generate the directory structure! Give it a yes and go on. The same thing goes for theautomatic update of the Kernel class. But that option is already set to yes as default, so no worrieshere.

    2.3 Organizing things

    http://fabien.potencier.org/article/15/symfony-service-container-using-xml-or-yaml-to-describe-services

    Table of ContentsIntroductionWhy I wrote this bookWho am I, really?

    1 Getting Started1.1 Installing1.2 Virtual Host

    2 Bundles2.1 Why use them?2.2 Creating Bundles2.3 Organizing things