Top Banner
symfony from scratch @ sfPHP A look at the PHP5 symfony platform and how to make symfony the foundation for your next web project
67

Symfony From Scratch

Nov 11, 2014

Download

Technology

Dustin Whittle

Presentation from April, 03, 2008 San Francisco PHP meetup presented by Dustin Whittle
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Symfony From Scratch

symfonyfromscratch@sfPHP

AlookatthePHP5symfonyplatformandhowtomakesymfonythe

foundationforyournextwebproject

Page 2: Symfony From Scratch

Whyyouwilllearn

• Whatisthesymfonyproject?• Whatdoessymfonyprojectprovide?

•  Howisitdifferentfrom(zend,cake,django,rails)?

•  Howtogetaprojectstarted?•  HowtointegratesymfonywithZend

•  Howtousesymfony+Y!UItocreateacompletewebplatform(php,css,js,patterns)

Page 3: Symfony From Scratch

Whatisthesymfonyproject?

•  Fullstackwebapplicationframeworkbuiltforrapidapplicationdevelopment

• WritteninPHP5basedonMVCpattern

•  Opensourceandfree•  LicensedundertheMITlicense

•  AgrowingcommunitysinceOctober2005

•  FoundedbyFabienPotencier,sponsoredbySensioLabs

Page 4: Symfony From Scratch

Whysymfony?

•  AgileDevelopment– Builtonbestpracticesusingprovendesignpatterns– Builttofactoroutcommonpatternsandallowdeveloperstofocusonapplicationlogic

– Automatesthetedioustasksmostdevelopersfacedaily•  Performance/Stability

– Proventoscaleonveryactivewebsites‐Y!/Sensio– Testedcodebase(8000+unitandfunctionaltest)

•  Maintainability– Providesreusablestructures(DRY)– Enforcesconsistencyamongstdevelopers

•  Support– Greatdocumentationandveryactivecommunity

Page 5: Symfony From Scratch

Howissymfonydifferent?

•  symfonyisnotacomponentlibrarylikeeZComponentsorZendFramework

•  Adoptbestideasfromanywhere,usingexistingcodeifavailable(prado,rails,django)

•  Itisafull‐stackframeworkforbuildingcomplexwebapplications– Whenyoucreateasymfonyproject,youhaveallofthetoolsyouneedtogetstarted.

– Itisnottargetedforbuildingsimpleapplications– Noassemblyrequired

•  Aflexibleandpluggablearchitecture

Page 6: Symfony From Scratch

CleanDesign

•  Builtusingprovendesignpatterns– Model‐View‐Controller• Separationofdataaccess,presentationlogic,andbusinesslogic

– Factoriesforcustomization

•  Builttoembraceagiledevelopmentprinciples– Allowsdeveloperstoeasilyfollow• ExtremeProgramming/TestDrivenDevelopment• DRY(Don’tRepeatYourself)

Page 7: Symfony From Scratch

MVC(stolenfromtheweb)

Page 8: Symfony From Scratch

MinimalRequirements

•  AwebserverthatiscapableofservingPHP5•  DatabaseserversupportedbyCreole/PDO– MySQL,PostgreSQL,SQLite,Oracle,MSSQL

•  RecommendedConfiguration– Apache

• mod_rewrite

– PHP5.1.x•  APC(xCacheoreAccelleratorarealsosupported)•  Syck•  xDebug

Page 9: Symfony From Scratch

symfony1.0‐>1.1

•  Evolvingintoaplatformtobuildyourownframework

•  Cleanseparationandcommunicationbetweencomponents(request,response,forms,validations,i18n,user,etc..)

•  Decouplingofdependencies‐introductionofEventDispatcher

•  Newfeatures:CacheFactories,NewFormSystem

Page 10: Symfony From Scratch

symfonycli

•  symfonycli– Providesprojectmanagementtasksfor• Creationofprojects,applications,andmodules• Configuringdatabase+projectsettings•  InstallingandRemovingplugins• Managingmodel(regeneratingom+loadingfixtures)• ExecutingUnit+FunctionalTests• Deployingprojecttoproduction• Rotatingandpurginglogs

– Foundationforcliapplicationsandcustomtasks

Page 11: Symfony From Scratch

ConfigurationSystem

•  Conventionoverconfiguration•  BasedonYAML– YAMLisreadable,concise,andhierarchysupport

•  Usesconfigurationfactoriestohandledifferentyamlfiles(customparsing)

•  CascadingConfiguration– Framework‐>Project‐>Application‐>Module

•  Configurationiscachedtophp

Page 12: Symfony From Scratch

Environments

•  Environmentdeterminedbyfrontcontroller•  Threedefaultenvironments– Production

•  Cachingenabled,loggingdisabled,cleanURLs– Development

•  Cachingdisabled,loggingenabled,debugtoolbarenabled– Testing

•  Similartoproductionwithoutcaching

•  Addasmanyenvironmentsasyourequire– Staging,QA,alpha…

Page 13: Symfony From Scratch

DebugEnvironment

•  WebDebugToolbar–  Browseraccesstorelevantinformation

•  RequestParameters/Sessions/Cookies•  Configuration(symfony/php)

–  Logs&DebugMessages•  xDebugIntegration(ExecutionTraces)

–  SQLQueryMonitor•  RawSQL+QueryTime

–  PerformanceMonitor•  MemoryConsumption•  Timers

–  CacheMonitor–  Logging

Page 14: Symfony From Scratch

RoutingSystem

•  FrontWebControllerdispatchesrequesttoappropriatecontrollerbasedonroute

•  Routingbasedonpathinfoorpatterns– Patternroutingsupportsregexrequirements

•  Amaintainablemod_rewritewithhelpers

blog_permalink:url:/blog/:permalinkparam:{module:blog,action:show}requirements:{permalink:.*}

Page 15: Symfony From Scratch

TheControllerLayer

•  Containsallbusinesslogic•  Basedonmodulesandactions•  Actionsarecontrollers•  Modulesareacollectionofrelatedactions– User=login/logout/register/profile

•  Modulesarerepresentedbyadirectorystructure(config,lib,templates)andaclass(actions.class.php/components.class.php)

•  Actionscansharesettings(view,cache,security)•  Actionsreturnviews(Success,Error,Custom)

Page 16: Symfony From Scratch

TheBasics=HelloWorld

Controller–(project/apps/frontend/modules/simple/actions/actions.class.php)

classsimpleActionsextendssfActions{publicfunctionexecuteIndex($request){$this‐>text='helloworld';}}

View‐(project/apps/frontend/modules/simple/templates/indexSuccess.php)

<?phpecho$text;?>

Page 17: Symfony From Scratch

TheModelLayer

– ORM:PropelorDoctrine– DefaultisPropel(sothatiswhatwewilldiscuss)

• NotexactlyActiveRecord=RowDataGateway+TableDataGatewayImplementation– Cleanseparationoftableoperationobjectsandrowinstances– “Object”classesforrows(RDG)– “Peer”classesfortableoperations(TDG)

•  DatabaseabstractionviaCreolelibrary•  Code+DDLBuilder+tasksbuiltonPhing

– CustomizableBuilders•  Reusablebehaviors:(ActAs,ParanoidDelete,updated_at,created_by)

Page 18: Symfony From Scratch

TheModelLayer

•  Builtintoolsforpagination,sorting,andfilters•  Supportforbehaviors•  Objectmodelbuiltviaschema.yml– Canbereverseengineeredfromexistingdb– Supportforindexes,references,constraints,anddbspecificproperties(autoincrement,sequences)

•  schema‐>modelgeneration‐>sql‐>insert

Page 19: Symfony From Scratch

Model‐Schemapropel:

posts:_attributes:{phpName:Post}id:{type:integer,required:true,primaryKey:true,autoIncrement:true}title:varchar(255)excerpt:longvarcharbody:longvarcharcreated_at:~

comments:_attributes:{phpName:Comment}id:{type:integer,required:true,primaryKey:true,autoIncrement:true}post_id:{type:integer,primaryKey:true,foreignTable:posts,foreignReference:id,ondelete:

cascade}author:varchar(255)email:varchar(255)body:longvarcharcreated_at:~

Page 20: Symfony From Scratch

TheModelFlow

Page 21: Symfony From Scratch

TheViewLayer

•  PHPasatemplatelanguage–  Nosmartylayer,insteadwehavehelpers–  Helpersaretemplatefunctions(think:rails)–  I18N,Date,Text,Cache,Routing

•  Viewconfigurationmanagedviaview.yml–  Metatags,title,javascript,css,layout,componentslots

•  Layout•  Partials+Slots

–  Templatefragmentwithoutbusinesslogic•  Components

–  Templatefragmentwithbusinesslogic•  ComponentSlots

–  Slotinlayoutforcontextualcontent

Page 22: Symfony From Scratch

Viewsareorganizedandreusable

•  Layoutsarethefullpageandpopupviews•  Slotsareplaceholdersinapage•  Apartialisastatictemplatefragment(think:copyrightnotice)

•  Acomponentisatemplatefragmentwithbusinesslogic(think:popularlist)

•  Acomponentslotisacontextualplaceholderfordifferentcomponents(basedoncontext)

Page 23: Symfony From Scratch

TheviewlayerinpicturesPartials

Slots

Layouts

Component

Page 24: Symfony From Scratch

AJAXToolkitIntegration

•  Prototype/script.aculo.usbuilt‐in•  Pluginsavailable:– sfUJSPlugin‐>helpersforUJSviajQuery– sfYUIPlugin‐>helpersforYUI– sfDojoPlugin‐>helpersforDojo

•  Buildyourownhelpers

Page 25: Symfony From Scratch

EasyrichinteractionsinPHP

•  TemplateHelpersinspiredfromRails– Basedonprototype/script.aculo.us

•  Easyimplementationsinonelineofphp– AJAXInteractions‐>link_to_remote– VisualEffects‐>visual_effect– AutoComplete‐>input_autocomplete_tag– InlineEditing‐>input_inline_editor_tag– DragandDrop‐>draggable_element– RichTextEditing‐>textarea_tagw/rich=tinymce|fck– RichCalendar‐>input_date_tag

Page 26: Symfony From Scratch

TheCachingSystem

•  Powerfulviewcachelayerwithmanyadapters:filebased,sqlite,memcache,apc,xcache,eaccelerator

•  Canbindcachetoanything(user/culture/id)•  Components/Partialscanbecachedindividually•  Actionscanbecachedwithorwithoutlayout•  Viewcachemanagerprovidesgreatinterfacetoselectivelyinvalidatebasedonurlpattern

•  sfSuperCachecanprovidefullpagecaching(skippingphpprocess)

•  HTTP1.1CacheHeaderManagement

Page 27: Symfony From Scratch

TheFormSystem(1.1)classSigninFormextendssfForm{publicfunctionconfigure(){$this‐>setWidgets(array('username'=>newsfWidgetFormInput(),'password'=>newsfWidgetFormInput(array('type'=>'password')),));

$this‐>setValidators(array('username'=>newsfValidatorString(),'password'=>newsfValidatorString(),));

$this‐>validatorSchema‐>setPostValidator(newsfGuardValidatorUser());

$this‐>widgetSchema‐>setNameFormat('signin[%s]');}}

<?phpecho$form;?>

Page 28: Symfony From Scratch

Generatinginterfaces(crud+admin)

•  CRUD(Create,Read,Update,Delete)– Basicadminforallfields

– Builttocustomize/extend• Boththeskeleton+generatedcode

•  AdministrationInterfaces– Pagination,Filters,Sorting,Actions– Viewslist/tabular– Extremelycustomizableviagenerator.yml

Page 29: Symfony From Scratch

I18n&L10n

•  InspiredbyPRADO•  FlexibleConfiguration– DictionariescanbeXLIFF,gettext,ordatabase

•  Caching•  TemplateHelpers– Dealingwithtext=__()

• Workswithcomplexstrings,enforcesseparation– Easydate,time,currencyformatting

•  InterfaceandDataLocalization– Supportforinternationalizationindatabasetables

Page 30: Symfony From Scratch

ThePluginSystem

•  Pluginsarepackages– Configuration,ObjectModel,Libraries,Helpers,Modules,Tasks,Tests,Assets

•  EasytoinstallviaPEAR– symfonyplugin‐installorpearinstall

•  Pluginscanbeoverridden/extended– Configuration,ObjectModel,Actions,Templates

Page 31: Symfony From Scratch

symfonyApplications

•  Askeet‐trac.askeet.com–  QuestionandAnswersite/tutorial

•  Demo‐Askeet.com•  Tutorial‐symfony‐project.com/askeet

•  Snipeet‐trac.snipeet.com–  Snippetrepository

•  Demo‐symfony‐project.com/snippets

•  Motilee‐trac.motilee.com–  ForumSystem

•  Demo–motilee.com

•  SteerCMS‐steercms‐project.org–  ContentManagementSystem

•  Symfonians‐symfonians.net–  SocialNetwork+CommunityShowcase

•  Bartertown–sourceforge.net/projects/bartertown–  AuctionSystem

Page 32: Symfony From Scratch

symfonyPlugins

•  ORM–  sfPropelPlugin,sfDoctrinePlugin

•  JavascriptFrameworkIntegration–  sfUJSPlugin,sfJqueryPlugin,sfYUIPlugin,sfExtPlugin,sfDojoPlugin

•  ThirdPartyLibraryIntegration–  sfZendPlugin,sfSwiftMailer,sfJpgraphPlugin,sfChartdirectorPlugin

•  ApplicationFunctionality–  sfSimpleCMSPlugin,sfSimpleBlogPlugin,sfSimpleForumPlugin,

sfSimpleNewsPlugin,sfMediaLibraryPlugin•  UserAuthentication

–  sfGuardPlugin,sfOpenIDPlugin•  Ecommerce

–  sfShoppingCartPlugin,sfAuthorizeNetPlugin,sfQuickbooksExportPlugin

Page 33: Symfony From Scratch

LIME‐UnitandFunctionalTesting

•  BasedonTest::MorePerllibrary

•  Supports– UnitTesting

•  Givenspecificinputvalidatespecificoutput– FunctionalTesting

•  Doesthisworkincontext,acompletefeature

•  TAPcompliantoutput

•  ZeroDependencies•  GreenisGood,RedisBad

Page 34: Symfony From Scratch

Aquickexampleapplication

•  Buildingafeedaggregator– Frontend• Login/Logout/Register/Profile• Displayfeedsindividuallybyname

• AggregatefeedsandcreateaggregateRSSfeed– Administration• Managefeedcategories+feeds• Manageusers,groups,andpermissions

Page 35: Symfony From Scratch

Installation

•  PEAR– pearchannel‐discoverpear.symfony‐project.com

– pearinstallsymfony/symfony

•  Subversion(svn:externals)–  svnexporthttp://svn.symfony‐project.com/branches/1.1

symfony

Page 36: Symfony From Scratch

Createyourfirstsymfonyapplicaiton

1.  symfonygenerate:projectsfproject2.  symfonygenerate:appfrontend

3.  symfonygenerate:modulefrontendcommon

Page 37: Symfony From Scratch

Configureyourproject

•  Configureyourdatabase– databases.yml,propel.ini

•  Configureyoursymfonysettings– settings.yml

•  Configureyourdefaultview– view.yml

•  Configureyourapplicationsettings– app.yml

Page 38: Symfony From Scratch

Configureyourdatabases

all:propel:class:sfPropelDatabaseparam:phptype:mysqlhostspec:localhostusername:sfshowcasepassword:passworddatabase:sfshowcasepersistent:trueencoding:utf8compat_assoc_lower:true

Page 39: Symfony From Scratch

Configureyousymfonysettings

use_database:onuse_security:on

use_flash:oni18n:on

suffix: .no_script_name:on

Page 40: Symfony From Scratch

Installpluginsforproject

symfonyplugin:installsfGuardPluginsymfonyplugin:installsfFeed2Plugin

Page 41: Symfony From Scratch

IntegrateyourownPHPlibraries

•  Autoloadinghooksforeasyintegrationof– ZendFramework

– EZComponents– SwiftMailer– PEAR– Yourownlibraries

Page 42: Symfony From Scratch

IntegratetheZendframework•  DownloadZendandinstallinlib/vendor/zf•  ChainZendAutoloading

classfrontendConfigurationextendssfApplicationConfiguration{/***Initializesthecurrentconfiguration.*/publicfunctioninitialize(){parent::initialize();set_include_path($sf_zend_lib_dir.PATH_SEPARATOR.get_include_path());require_once($sf_zend_lib_dir.’/Zend/Loader.php');spl_autoload_register(array('Zend_Loader','loadClass'));}}

Page 43: Symfony From Scratch

Creatingaschema/objectmodel

Page 44: Symfony From Scratch

InstallsfGuardPlugin

Enablemodulesinfrontendsettings.yml

.settings:enabled_modules:[sfGuardAuth,sfGuardGroup,sfGuardUser,sfGuardPermission]

Page 45: Symfony From Scratch

InstallsfGuardPlugin

Addremembermefilter(filters.yml)security_filter:class:sfGuardBasicSecurityFilter

Customizedefaultsecurityactionslogin_module:sfGuardAuthlogin_action:signinsecure_module:sfGuardAuthsecure_action:secure

Page 46: Symfony From Scratch

Rebuildobjectmodel(fornewplugins)

symfonypropel:build‐all‐loadfrontend

Page 47: Symfony From Scratch

Creatinganadministrationarea

symfonypropel:init‐adminfrontendfeedsFeedsymfonypropel:init‐adminfrontend

feed_categoriesFeedCategory

Page 48: Symfony From Scratch

Protectingouradminstrationarea

•  Createlocalmodules(sfGuardGroup…)•  Addaconfig/security.ymlandsetcredentials

all:

is_secure:true

credentials:[admin]

Page 49: Symfony From Scratch

Addingatasktoaggregatefeeds

•  FetchfeedsusingsfFeedPlugin•  Cachefeedsfordisplayonfrontend

Page 50: Symfony From Scratch

Addingroutes

#feeds

feeds_index:

url:/feedsparam:{module:feeds,action:index}

feeds_show:

url:/feeds/:name

param:{module:feeds,action:show}

feeds_admin:

url:/administration/feeds/:action/*

param:{module:feeds_admin,action:list}

users_admin:

url:/administration/users/:action/*param:{module:sfGuardUser,action:list}

Page 51: Symfony From Scratch

Addingcachingtoourapplication

•  Editcache.yml

Page 52: Symfony From Scratch

Testingourapplication

//createanewtestbrowser$browser=newsfTestBrowser();

$browser‐>get('/feeds/index')‐>isStatusCode(200)‐>isRequestParameter('module','feeds')‐>isRequestParameter('action','index')‐>checkResponseElement('body','/techcrunch/');

Page 53: Symfony From Scratch

Deployingourapplication

symfonyproject:freezesymfonyproject:deploy

Page 54: Symfony From Scratch

Createadel.icio.uscomponent

Createactions/components.class.phppublicfunctionexecuteDelicious(){$delicious=newZend_Service_Delicious(sfConfig::get('app_delicious_username'),sfConfig::get('app_delicious_password'));

$this‐>posts=$delicious‐>getRecentPosts(sfConfig::get('app_delicious_tag'),sfConfig::get('app_delicious_max',10));

}

Page 55: Symfony From Scratch

Createadel.icio.uspartial

templates/_delicious.php

<ul><?phpforeach($postsas$post):?><li><?phpecholink_to($post‐>getTitle(),$post‐>getUrl());?></li>

<?phpendforeach;?></ul>

Page 56: Symfony From Scratch

Wheretogofromhere?

•  ReadDocumentation• WorkthroughtheAskeetadvent

•  Stepbysteptutorials•  Findingexamplecode

•  Findinghelp

Page 57: Symfony From Scratch

Documentation

•  TheDefinitiveGuidetosymfony– http://symfony‐project.com/book/trunk– Releasedopensource1/29/2007– LicensedunderGFDL

•  APIDocumentation– Goodcoverage

•  Wiki– Manyusefulguidesandhowto

– Manyusercontributedtips

Page 58: Symfony From Scratch

AskeetAdvent

•  Askeet.com– http://symfony‐project.com/askeet

•  24DayTutorialon•  Howtobuildarealweb2.0application•  In‐depthcoverageofallaspectsofsymfony

Page 59: Symfony From Scratch

Tutorials

•  Askeet• Myfirstproject

•  Buildinganajaxifieddraganddropshoppingcart

•  Sortablelistsusingajax•  Degradableajaxpagination

Page 60: Symfony From Scratch

ExampleCode

•  Askeet– http://trac.askeet.com

•  Snippets– http://symfony‐project.com/snippets/

•  Snipeet– http://trac.snipeet.com

Page 61: Symfony From Scratch

FindingHelp

•  Forums– http://www.symfony‐project.com/forum

•  IRC– irc.freenode.net/#symfony

• MailingList(GoogleGroups)– symfony‐[email protected]

– archived&searchable

Page 62: Symfony From Scratch

RealWorldPerformance

•  HelloWorldin10‐15ms– APC/Syck

•  symfonycanprovidemanyfeatures– disabletheonesyouwillnotuse

•  Buildintelligently,cacheeffectively•  sfOptimizerPlugin/sfSuperCache•  Yahoo!Bookmarks/Y!Answers•  symfony‐project.com– digg,slashdot,techcrunch,ajaxian

Page 63: Symfony From Scratch

WhatdoesY!changetoscale

•  DropthefrontendORMandpushdownthestack(SOA)

•  Precompiledi18n

•  Y!YslowRules(frontendperformance)

Page 64: Symfony From Scratch

Yahoo!ishiringfrontendandbackendengineerstalktoMarcusChanfor

moreinfo.

(soisEducation.comandCurrentMedia)

Page 65: Symfony From Scratch

Questions?

Page 66: Symfony From Scratch

Thanksforlistening

Page 67: Symfony From Scratch

TheWebWorkflow

TheUserasksforaResourceinaBrowser

TheBrowsersendsaRequesttotheServer

TheServersendsbackaResponse

TheBrowserdisplaystheResourcetotheUser