symfony from scratch
Post on 11-Nov-2014
8.306 Views
Preview:
DESCRIPTION
TRANSCRIPT
symfonyfromscratch@sfPHP
AlookatthePHP5symfonyplatformandhowtomakesymfonythe
foundationforyournextwebproject
Whyyouwilllearn
• Whatisthesymfonyproject?• Whatdoessymfonyprojectprovide?
• Howisitdifferentfrom(zend,cake,django,rails)?
• Howtogetaprojectstarted?• HowtointegratesymfonywithZend
• Howtousesymfony+Y!UItocreateacompletewebplatform(php,css,js,patterns)
Whatisthesymfonyproject?
• Fullstackwebapplicationframeworkbuiltforrapidapplicationdevelopment
• WritteninPHP5basedonMVCpattern
• Opensourceandfree• LicensedundertheMITlicense
• AgrowingcommunitysinceOctober2005
• FoundedbyFabienPotencier,sponsoredbySensioLabs
Whysymfony?
• AgileDevelopment– Builtonbestpracticesusingprovendesignpatterns– Builttofactoroutcommonpatternsandallowdeveloperstofocusonapplicationlogic
– Automatesthetedioustasksmostdevelopersfacedaily• Performance/Stability
– Proventoscaleonveryactivewebsites‐Y!/Sensio– Testedcodebase(8000+unitandfunctionaltest)
• Maintainability– Providesreusablestructures(DRY)– Enforcesconsistencyamongstdevelopers
• Support– Greatdocumentationandveryactivecommunity
Howissymfonydifferent?
• symfonyisnotacomponentlibrarylikeeZComponentsorZendFramework
• Adoptbestideasfromanywhere,usingexistingcodeifavailable(prado,rails,django)
• Itisafull‐stackframeworkforbuildingcomplexwebapplications– Whenyoucreateasymfonyproject,youhaveallofthetoolsyouneedtogetstarted.
– Itisnottargetedforbuildingsimpleapplications– Noassemblyrequired
• Aflexibleandpluggablearchitecture
CleanDesign
• Builtusingprovendesignpatterns– Model‐View‐Controller• Separationofdataaccess,presentationlogic,andbusinesslogic
– Factoriesforcustomization
• Builttoembraceagiledevelopmentprinciples– Allowsdeveloperstoeasilyfollow• ExtremeProgramming/TestDrivenDevelopment• DRY(Don’tRepeatYourself)
MVC(stolenfromtheweb)
MinimalRequirements
• AwebserverthatiscapableofservingPHP5• DatabaseserversupportedbyCreole/PDO– MySQL,PostgreSQL,SQLite,Oracle,MSSQL
• RecommendedConfiguration– Apache
• mod_rewrite
– PHP5.1.x• APC(xCacheoreAccelleratorarealsosupported)• Syck• xDebug
symfony1.0‐>1.1
• Evolvingintoaplatformtobuildyourownframework
• Cleanseparationandcommunicationbetweencomponents(request,response,forms,validations,i18n,user,etc..)
• Decouplingofdependencies‐introductionofEventDispatcher
• Newfeatures:CacheFactories,NewFormSystem
symfonycli
• symfonycli– Providesprojectmanagementtasksfor• Creationofprojects,applications,andmodules• Configuringdatabase+projectsettings• InstallingandRemovingplugins• Managingmodel(regeneratingom+loadingfixtures)• ExecutingUnit+FunctionalTests• Deployingprojecttoproduction• Rotatingandpurginglogs
– Foundationforcliapplicationsandcustomtasks
ConfigurationSystem
• Conventionoverconfiguration• BasedonYAML– YAMLisreadable,concise,andhierarchysupport
• Usesconfigurationfactoriestohandledifferentyamlfiles(customparsing)
• CascadingConfiguration– Framework‐>Project‐>Application‐>Module
• Configurationiscachedtophp
Environments
• Environmentdeterminedbyfrontcontroller• Threedefaultenvironments– Production
• Cachingenabled,loggingdisabled,cleanURLs– Development
• Cachingdisabled,loggingenabled,debugtoolbarenabled– Testing
• Similartoproductionwithoutcaching
• Addasmanyenvironmentsasyourequire– Staging,QA,alpha…
DebugEnvironment
• WebDebugToolbar– Browseraccesstorelevantinformation
• RequestParameters/Sessions/Cookies• Configuration(symfony/php)
– Logs&DebugMessages• xDebugIntegration(ExecutionTraces)
– SQLQueryMonitor• RawSQL+QueryTime
– PerformanceMonitor• MemoryConsumption• Timers
– CacheMonitor– Logging
RoutingSystem
• FrontWebControllerdispatchesrequesttoappropriatecontrollerbasedonroute
• Routingbasedonpathinfoorpatterns– Patternroutingsupportsregexrequirements
• Amaintainablemod_rewritewithhelpers
blog_permalink:url:/blog/:permalinkparam:{module:blog,action:show}requirements:{permalink:.*}
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)
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;?>
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)
TheModelLayer
• Builtintoolsforpagination,sorting,andfilters• Supportforbehaviors• Objectmodelbuiltviaschema.yml– Canbereverseengineeredfromexistingdb– Supportforindexes,references,constraints,anddbspecificproperties(autoincrement,sequences)
• schema‐>modelgeneration‐>sql‐>insert
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:~
TheModelFlow
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
Viewsareorganizedandreusable
• Layoutsarethefullpageandpopupviews• Slotsareplaceholdersinapage• Apartialisastatictemplatefragment(think:copyrightnotice)
• Acomponentisatemplatefragmentwithbusinesslogic(think:popularlist)
• Acomponentslotisacontextualplaceholderfordifferentcomponents(basedoncontext)
TheviewlayerinpicturesPartials
Slots
Layouts
Component
AJAXToolkitIntegration
• Prototype/script.aculo.usbuilt‐in• Pluginsavailable:– sfUJSPlugin‐>helpersforUJSviajQuery– sfYUIPlugin‐>helpersforYUI– sfDojoPlugin‐>helpersforDojo
• Buildyourownhelpers
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
TheCachingSystem
• Powerfulviewcachelayerwithmanyadapters:filebased,sqlite,memcache,apc,xcache,eaccelerator
• Canbindcachetoanything(user/culture/id)• Components/Partialscanbecachedindividually• Actionscanbecachedwithorwithoutlayout• Viewcachemanagerprovidesgreatinterfacetoselectivelyinvalidatebasedonurlpattern
• sfSuperCachecanprovidefullpagecaching(skippingphpprocess)
• HTTP1.1CacheHeaderManagement
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;?>
Generatinginterfaces(crud+admin)
• CRUD(Create,Read,Update,Delete)– Basicadminforallfields
– Builttocustomize/extend• Boththeskeleton+generatedcode
• AdministrationInterfaces– Pagination,Filters,Sorting,Actions– Viewslist/tabular– Extremelycustomizableviagenerator.yml
I18n&L10n
• InspiredbyPRADO• FlexibleConfiguration– DictionariescanbeXLIFF,gettext,ordatabase
• Caching• TemplateHelpers– Dealingwithtext=__()
• Workswithcomplexstrings,enforcesseparation– Easydate,time,currencyformatting
• InterfaceandDataLocalization– Supportforinternationalizationindatabasetables
ThePluginSystem
• Pluginsarepackages– Configuration,ObjectModel,Libraries,Helpers,Modules,Tasks,Tests,Assets
• EasytoinstallviaPEAR– symfonyplugin‐installorpearinstall
• Pluginscanbeoverridden/extended– Configuration,ObjectModel,Actions,Templates
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
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
LIME‐UnitandFunctionalTesting
• BasedonTest::MorePerllibrary
• Supports– UnitTesting
• Givenspecificinputvalidatespecificoutput– FunctionalTesting
• Doesthisworkincontext,acompletefeature
• TAPcompliantoutput
• ZeroDependencies• GreenisGood,RedisBad
Aquickexampleapplication
• Buildingafeedaggregator– Frontend• Login/Logout/Register/Profile• Displayfeedsindividuallybyname
• AggregatefeedsandcreateaggregateRSSfeed– Administration• Managefeedcategories+feeds• Manageusers,groups,andpermissions
Installation
• PEAR– pearchannel‐discoverpear.symfony‐project.com
– pearinstallsymfony/symfony
• Subversion(svn:externals)– svnexporthttp://svn.symfony‐project.com/branches/1.1
symfony
Createyourfirstsymfonyapplicaiton
1. symfonygenerate:projectsfproject2. symfonygenerate:appfrontend
3. symfonygenerate:modulefrontendcommon
Configureyourproject
• Configureyourdatabase– databases.yml,propel.ini
• Configureyoursymfonysettings– settings.yml
• Configureyourdefaultview– view.yml
• Configureyourapplicationsettings– app.yml
Configureyourdatabases
all:propel:class:sfPropelDatabaseparam:phptype:mysqlhostspec:localhostusername:sfshowcasepassword:passworddatabase:sfshowcasepersistent:trueencoding:utf8compat_assoc_lower:true
Configureyousymfonysettings
use_database:onuse_security:on
use_flash:oni18n:on
suffix: .no_script_name:on
Installpluginsforproject
symfonyplugin:installsfGuardPluginsymfonyplugin:installsfFeed2Plugin
IntegrateyourownPHPlibraries
• Autoloadinghooksforeasyintegrationof– ZendFramework
– EZComponents– SwiftMailer– PEAR– Yourownlibraries
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'));}}
Creatingaschema/objectmodel
InstallsfGuardPlugin
Enablemodulesinfrontendsettings.yml
.settings:enabled_modules:[sfGuardAuth,sfGuardGroup,sfGuardUser,sfGuardPermission]
InstallsfGuardPlugin
Addremembermefilter(filters.yml)security_filter:class:sfGuardBasicSecurityFilter
Customizedefaultsecurityactionslogin_module:sfGuardAuthlogin_action:signinsecure_module:sfGuardAuthsecure_action:secure
Rebuildobjectmodel(fornewplugins)
symfonypropel:build‐all‐loadfrontend
Creatinganadministrationarea
symfonypropel:init‐adminfrontendfeedsFeedsymfonypropel:init‐adminfrontend
feed_categoriesFeedCategory
Protectingouradminstrationarea
• Createlocalmodules(sfGuardGroup…)• Addaconfig/security.ymlandsetcredentials
all:
is_secure:true
credentials:[admin]
Addingatasktoaggregatefeeds
• FetchfeedsusingsfFeedPlugin• Cachefeedsfordisplayonfrontend
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}
Addingcachingtoourapplication
• Editcache.yml
Testingourapplication
//createanewtestbrowser$browser=newsfTestBrowser();
$browser‐>get('/feeds/index')‐>isStatusCode(200)‐>isRequestParameter('module','feeds')‐>isRequestParameter('action','index')‐>checkResponseElement('body','/techcrunch/');
Deployingourapplication
symfonyproject:freezesymfonyproject:deploy
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));
}
Createadel.icio.uspartial
templates/_delicious.php
<ul><?phpforeach($postsas$post):?><li><?phpecholink_to($post‐>getTitle(),$post‐>getUrl());?></li>
<?phpendforeach;?></ul>
Wheretogofromhere?
• ReadDocumentation• WorkthroughtheAskeetadvent
• Stepbysteptutorials• Findingexamplecode
• Findinghelp
Documentation
• TheDefinitiveGuidetosymfony– http://symfony‐project.com/book/trunk– Releasedopensource1/29/2007– LicensedunderGFDL
• APIDocumentation– Goodcoverage
• Wiki– Manyusefulguidesandhowto
– Manyusercontributedtips
AskeetAdvent
• Askeet.com– http://symfony‐project.com/askeet
• 24DayTutorialon• Howtobuildarealweb2.0application• In‐depthcoverageofallaspectsofsymfony
Tutorials
• Askeet• Myfirstproject
• Buildinganajaxifieddraganddropshoppingcart
• Sortablelistsusingajax• Degradableajaxpagination
ExampleCode
• Askeet– http://trac.askeet.com
• Snippets– http://symfony‐project.com/snippets/
• Snipeet– http://trac.snipeet.com
FindingHelp
• Forums– http://www.symfony‐project.com/forum
• IRC– irc.freenode.net/#symfony
• MailingList(GoogleGroups)– symfony‐users@googlegroups.com
– archived&searchable
RealWorldPerformance
• HelloWorldin10‐15ms– APC/Syck
• symfonycanprovidemanyfeatures– disabletheonesyouwillnotuse
• Buildintelligently,cacheeffectively• sfOptimizerPlugin/sfSuperCache• Yahoo!Bookmarks/Y!Answers• symfony‐project.com– digg,slashdot,techcrunch,ajaxian
WhatdoesY!changetoscale
• DropthefrontendORMandpushdownthestack(SOA)
• Precompiledi18n
• Y!YslowRules(frontendperformance)
Yahoo!ishiringfrontendandbackendengineerstalktoMarcusChanfor
moreinfo.
(soisEducation.comandCurrentMedia)
Questions?
Thanksforlistening
TheWebWorkflow
TheUserasksforaResourceinaBrowser
TheBrowsersendsaRequesttotheServer
TheServersendsbackaResponse
TheBrowserdisplaystheResourcetotheUser
top related