Successfully reported this slideshow.
Bastian Waidelich & Robert Lemke/** * Conference controller for the Acme.Demo package * * @scope singleton */class Confere...
Hanau, GermanyRobert Lemkechief "architect" of TYPO3 5.0 and FLOW3co-founder of the TYPO3 Association35 years oldlives in ...
Hanau, GermanyBastian WaidelichFLOW3 core team member since 2008co-creator of Fluid30 years oldlives in Cologne, Germany0 ...
Hanau, GermanyThis WorkshopMorning • Installation • Kickstart & Hello World! • Commands • Depencency Injection • Persisten...
Hanau, GermanyThis WorkshopAfternoon • Routing • Validation • Property Mapper • Migrations • Security / Login • A Glimpse ...
Hanau, GermanyAt a GlanceFLOW3 is a web application framework • brings PHP development to a new level • made for PHP 5.3, ...
Hanau, Germany Foundation for the Next Generation CMSTYPO3 5.0 is the all-newEnterprise CMS • content repository, workspac...
Hanau, GermanyGit Clone$ git clone --recursive git://git.typo3.org/FLOW3/Distributions/Base.git .Cloning into ....remote: ...
Hanau, Germany Set File Permissions  $ sudo ./flow3 core:setfilepermissions robert _www _www  FLOW3 File Permission Script...
Hanau, GermanySet Up Database ConnectionConfiguration/Settings.yaml #                                                      ...
Hanau, GermanySet Up Virtual HostApache Virtual Host  <VirtualHost *:80>       DocumentRoot /opt/local/apache2/htdocs/Talk...
Hanau, GermanyFinal Check
Hanau, GermanyUpdate from Git to Latest State$ git submodule foreach "git checkout master"-✂-----✂-----✂-----✂-----✂-----✂...
Hanau, GermanyCommand Line Use$ ./flow3 helpFLOW3 1.0.0 ("Development" context)usage: ./flow3 <command identifier>The foll...
Hanau, GermanyCommand Line Use$ ./flow3 help kickstart:packageKickstart a new packageCOMMAND:  typo3.kickstart:kickstart:p...
Hanau, GermanyHello World!               $ ./flow3 kickstart:package Acme.Demo
H e ll o Wo r ld ! 5         1                1   1         Ro bert Lem ke         D.P. F l u x t r        time ();
Hanau, GermanyHello World!StandardController.php   <?php   namespace AcmeDemoController;   use TYPO3FLOW3MVCControllerActi...
Hanau, GermanyTackling the Heart of Software Development                                         /**Domain-Driven Design  ...
Hanau, GermanyDomain-Driven DesignDomain activity or business of the userDomain-Driven Design is about • focussing on the ...
Hanau, GermanyDomain-Driven DesignUbiquitous Language • important prerequisite for successful   collaboration • use the sa...
Hanau, GermanyDomain-Driven Design
Hanau, GermanyDomain: Conference
Hanau, GermanyDomain: Conference
Hanau, GermanyDomain: Conference
Hanau, GermanyDomain: Conference
K ic k s t a rt ing "C o n f e re n c e" 5          1                1   1         Ro bert Lem ke          D.P. F l u x t ...
Hanau, GermanyDomain: Conference
Hanau, GermanyObject ManagementDependency Injection • a class doesnt create or retrieve the instance   of another class bu...
Hanau, GermanyObject ManagementFLOW3s take on Dependency Injection • one of the first PHP implementations   (started in 200...
Hanau, Germany                                                                             WarConstructor Injection: Symfo...
Hanau, Germany                                                                               War  Constructor Injection: S...
Hanau, GermanyConstructor Injection    <?phpnamespace F3DemoController;use F3FLOW3MVCControllerActionController;use F3Demo...
Hanau, GermanyConstructor Injection
Hanau, GermanySetter Injection<?phpnamespace F3DemoController;use F3FLOW3MVCControllerActionController;use F3DemoServiceGr...
Hanau, GermanyProperty Injection<?phpnamespace F3DemoController;use F3FLOW3MVCControllerActionController;use F3DemoService...
Hanau, GermanyObjects.yaml   F3FLOW3SecurityCryptographyRsaWalletServiceInterface:     className: F3FLOW3SecurityCryptogra...
Hanau, GermanyObject Management    class Customer {	   /**	    * @inject	    * @var CustomerNumberGenerator	    */	   prot...
Hanau, GermanyObject Management                                     <?php                                     declare(ENCO...
Hanau, GermanyYour Own Commands      $ ./flow3 kickstart:commandcontroller Acme.Demo Test
Hanau, GermanyValidationValidation is about different things• incoming data needs to be validated for security reasons • n...
Hanau, GermanyValidationValidation in FLOW3• you do not want to code checks into your controllers• FLOW3 separates validat...
Hanau, GermanyValidationValidation Models• BaseProperties  rules defining the minimum requirements on individual properties...
Hanau, GermanyValidationBase Properties• Validation rules defined directly at the properties  	   /**  	    * @var string  ...
Hanau, GermanyValidationValidators• validators provided by FLOW3 can be used through their short name • Count, Float, NotE...
Hanau, GermanyProperty MapperTransfer properties from A to B • Allows for complete or partial copying of objects and objec...
Hanau, Germany    Property Mapper	   $articleArray = array(	   	 headline => Hello World!,	   	 story => Just a demo ...	 ...
Hanau, Germany Resource Management Image Upload Resources are handled like other properties in a form:	 <f:form method="bl...
Hanau, Germany    Property Mapper    Allow nested object structures    For security reasons the creation of nested structu...
Hanau, GermanyPersistenceObject Persistence in the Flow • based on Doctrine 2 • seamless integration into FLOW3 • provides...
Hanau, Germany    Basic Object Persistence	   	 // Create a new customer and persist it:	   $customer = new Customer("Robe...
Hanau, Germany    Validation and Doctrine Annotationsnamespace TYPO3BlogDomainModel;/** * A Blog object * * @Entity */clas...
Hanau, GermanyPersistence-related Annotations@Entity        Declares a class as "entity"@Column        Controls the databa...
Hanau, GermanyPersistence-related Annotations@var           Defines the type of a property, collections can be             ...
Hanau, Germany    Custom Queries using the Query Object Model/** * A PostRepository */class PostRepository extends TYPO3FL...
Hanau, GermanySchema ManagementDoctrine 2 Migrations• Migrations allow schema versioning and  change deployment• Migration...
Hanau, GermanySchema ManagementRunning Migrations• needed after installation or upgrade:$ ./flow3 doctrine:migrate
Hanau, GermanySchema ManagementManual database updates• for simple situations this can be good enough:$ ./flow3 doctrine:c...
Hanau, GermanySchema ManagementGenerating migrations$ ./flow3 doctrine:migrationgenerateGenerated new migration class to "...
M ig rat io n s 5        8                1   1        Ro bert Lem ke        D.P. F l u x t r       time ();
Hanau, GermanyFluidExample for assigning a string to a Fluid variable:	   	 // in the action controller:	   $this->view->a...
Hanau, GermanyFluidVariables can also be objects:	   	 // in the action controller:	   $this->view->assign(conference, $co...
Hanau, GermanyFluidif-then-else:	   	 // in the action controller:	   $this->view->assign(post, $blogPost);	   <!-- in the...
Hanau, GermanyFluidfor-each:	   	 // in the action controller:	   $this->view->assign(ages, array("Karsten" => 34, "Robert...
Hanau, GermanyFluidfor-each:	   	 // in the action controller:	   $this->view->assign(post, $blogPost);	   <!-- in the Flu...
Hanau, GermanyFluidView helpers – in this case the link.action view helper:	   <!-- in the Fluid template: -->	   {namespa...
F lue n t F lu id 5         8                1   1         K. Damb ek aln s & R. Lem ke         D.P. F l u x t r        ti...
Hanau, GermanySecurityTouchless Security, Flow-Style • security is handled at a central place (through AOP) • third-party ...
Hanau, GermanySecurity Policy
Us e rs a n d L o g in 5         8                1   1        K. Damb ek aln s & R. Lem ke         D.P. F l u x t r      ...
Hanau, GermanyAOPAspect-Oriented Programming • programming paradigm • separates concerns to improve modularization • OOP m...
Hanau, GermanyAOP                                 /**                                  * @aspectFLOW3 uses AOP for ...    ...
Th e Wiz a rd o f AOP 5       8                1   1      K. Damb ek aln s & R. Lem ke       D.P. F l u x t r      time ();
Hanau, GermanySignal-Slot Event HandlingSignal  • can be fired on any event  • can be freely defined by the developerSlot  •...
Hanau, GermanySignal-Slot Event Handling   /**     * @param F3BlogDomainModelPost $post     * @param F3BlogDomainModelComm...
Hanau, GermanySignal-Slot Event HandlingSignals are wired to Slots in a package’s bootstrap: /**   * Invokes custom PHP co...
Hanau, GermanySignal-Slot Event HandlingAny method can be a slot:  /**   * @param F3BlogDomainModelComment $comment   * @p...
Hanau, GermanyRoadmaphttp://forge.typo3.org/projects/flow3-distribution-base/roadmap
Hanau, GermanyConference Appgit://git.typo3.org/TYPO3v5/Distributions/Conference.git
Hanau, GermanyBlog Appgit://git.typo3.org/FLOW3/Applications/Blog.git
Hanau, GermanyThank You & Have Fun! • FLOW3: http://flow3.typo3.org • Blog: http://robertlemke.de/blog • Twitter: @robertle...
Upcoming SlideShare
Loading in …5
×

FLOW3 Tutorial - T3CON11 Frankfurt

5,588 views

Published on

FLOW3 is an application framework which will change the way you code PHP. It aims to back up developers with security and infrastructure while they focus on the application logic.
FLOW3 is one of the first application frameworks to choose Domain-Driven Design as its major underlying concept. This approach makes FLOW3 easy to learn and at the same time clean and flexible for even complex projects. Built with PHP 5.3 in mind from the beginning, it features namespaces and has an emphasis on clean, object-oriented code.
Thanks to its Doctrine 2 integration, FLOW3 gives you access to a wide range of databases while letting you forget the fact that you’re using a database at all (think objects, not tables). FLOW3’s unique way of supporting Dependency Injection (no configuration necessary) lets you truly enjoy creating a stable and easy-to-test application architecture. Being the only Aspect-Oriented Programming capable PHP framework, FLOW3 allows you to cleanly separate cross cutting concerns like security from your main application logic.
In this tutorial we’ll walk you through an imaginary project from scratch. During the journey we’ll visit all important areas of the framework like templating, routing, security and persistence. For every core concept we’ll provide a short introduction, so that the process is comprehensible to all experienced PHP developers.

Published in: Technology, Education
  • Hello,

    In order to start as beginner (who has basic knowledge of php) i.e. wants to start with flow3 framework, there is proper organized documentation which make very unhappy, though flow3 is providing well set of features.

    Any book or tutorial, like I need following set of documentation:

    1. Setup an project
    2. Add few tables - From where to start ?
    3. How to make use of messages ?
    4. How to make rest call to my business class
    5. How we can maintain project level configurations ?
    6. How dependency injection configured?

    As I am new to any of frameworks and wants to start with flow3, but not getting confidence due to lack of resources.

    If any help, appriceted.
    Thanks
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

FLOW3 Tutorial - T3CON11 Frankfurt

  1. 1. Bastian Waidelich & Robert Lemke/** * Conference controller for the Acme.Demo package * * @scope singleton */class ConferenceController extends ActionController { /** * @inject * @var AcmeDemoDomainRepositoryConferenceRepository */ protected $conferenceRepository; /** * Shows a list of conferences * * @return void */ public function indexAction() { $this->view->assign(conferences, $this->conferenceRepository->findAll()); FLOW3 Tutorial } /** * Shows a single conference object *
  2. 2. Hanau, GermanyRobert Lemkechief "architect" of TYPO3 5.0 and FLOW3co-founder of the TYPO3 Association35 years oldlives in Lübeck, Germany1 wife, 2 daughters, 1 espresso machinelikes drumming
  3. 3. Hanau, GermanyBastian WaidelichFLOW3 core team member since 2008co-creator of Fluid30 years oldlives in Cologne, Germany0 wifes, ? daughters, 1 cafeteralikes climbing & guitar playing
  4. 4. Hanau, GermanyThis WorkshopMorning • Installation • Kickstart & Hello World! • Commands • Depencency Injection • Persistence, Doctrine and Domain-Driven Design • Modelling of an example App • Kickstarting the example App
  5. 5. Hanau, GermanyThis WorkshopAfternoon • Routing • Validation • Property Mapper • Migrations • Security / Login • A Glimpse on TYPO3 Phoenix
  6. 6. Hanau, GermanyAt a GlanceFLOW3 is a web application framework • brings PHP development to a new level • made for PHP 5.3, full namespaces support • modular, extensible, package based • free & Open Source (LGPL v3) • backed by one of the largest Open Source projects with 6000+ contributors
  7. 7. Hanau, Germany Foundation for the Next Generation CMSTYPO3 5.0 is the all-newEnterprise CMS • content repository, workspaces, versions, i18n, ExtJS based UI ... • powered by FLOW3 • compatible code base • use TYPO3 features in FLOW3 standalone apps as you like
  8. 8. Hanau, GermanyGit Clone$ git clone --recursive git://git.typo3.org/FLOW3/Distributions/Base.git .Cloning into ....remote: Counting objects: 3837, done.remote: Compressing objects: 100% (2023/2023), done.remote: Total 3837 (delta 2007), reused 2721 (delta 1465)Receiving objects: 100% (3837/3837), 3.49 MiB | 28 KiB/s, done.Resolving deltas: 100% (2007/2007), done.
  9. 9. Hanau, Germany Set File Permissions $ sudo ./flow3 core:setfilepermissions robert _www _www FLOW3 File Permission Script Checking permissions from here upwards. Making sure Data and Web/_Resources exist. Setting file permissions, trying to set ACLs via chmod ... Done.Linux: $ sudo usermod -a -G www-data robertMac OS X: $ sudo dscl . -append /Groups/_www GroupMembership robert
  10. 10. Hanau, GermanySet Up Database ConnectionConfiguration/Settings.yaml # # # Global Settings # # # TYPO3: FLOW3: persistence: backendOptions: dbname: demo user: demo password: password host: 127.0.0.1 # only on Windows: core: phpBinaryPathAndFilename: C:/path/to/php.exe
  11. 11. Hanau, GermanySet Up Virtual HostApache Virtual Host <VirtualHost *:80> DocumentRoot /opt/local/apache2/htdocs/Talks/FLOW3/Web/ ServerName dev.flow3.rob SetEnv FLOW3_CONTEXT Development </VirtualHost> <VirtualHost *:80> DocumentRoot /opt/local/apache2/htdocs/Talks/FLOW3/Web/ ServerName flow3.rob SetEnv FLOW3_CONTEXT Production </VirtualHost>
  12. 12. Hanau, GermanyFinal Check
  13. 13. Hanau, GermanyUpdate from Git to Latest State$ git submodule foreach "git checkout master"-✂-----✂-----✂-----✂-----✂-----✂-----✂-----✂-----✂-----✂-----✂-----✂-$ git submodule foreach "git pull --rebase"Entering Build/CommonFirst, rewinding head to replay your work on top of it...Fast-forwarded master to 6f27f1784240b414e966ce0e5a12e23cb2f7ab02.Entering Packages/Application/TYPO3First, rewinding head to replay your work on top of it...Fast-forwarded master to 5187430ee44d579ae2bac825e2a069c4cd3Acme8a4.Entering Packages/Application/TYPO3CRFirst, rewinding head to replay your work on top of it...Fast-forwarded master to b1f5331aa51d390fa3d973404Acme1b9fd773f7059.Entering Packages/Application/TwitterCurrent branch master is up to date.…
  14. 14. Hanau, GermanyCommand Line Use$ ./flow3 helpFLOW3 1.0.0 ("Development" context)usage: ./flow3 <command identifier>The following commands are currently available:PACKAGE "TYPO3.FLOW3":-------------------------------------------------------------------------------* flow3:cache:flush Flush all caches cache:warmup Warm up caches* flow3:core:setfilepermissions Adjust file permissions for CLI and web server access* flow3:core:shell Run the interactive Shell doctrine:validate Validate the class/table mappings doctrine:create Create the database schema doctrine:update Update the database schema doctrine:entitystatus Show the current status of entities and mappings doctrine:dql Run arbitrary DQL and display results doctrine:migrationstatus Show the current migration status doctrine:migrate Migrate the database schema doctrine:migrationexecute Execute a single migration doctrine:migrationversion Mark/unmark a migration as migrated doctrine:migrationgenerate Generate a new migration
  15. 15. Hanau, GermanyCommand Line Use$ ./flow3 help kickstart:packageKickstart a new packageCOMMAND: typo3.kickstart:kickstart:packageUSAGE: ./flow3 kickstart:package <package key>ARGUMENTS: --package-key The package key, for example "MyCompany.MyPackageName"DESCRIPTION: Creates a new package and creates a standard Action Controller and a sample template for its Index Action. For creating a new package without sample code use the package:create command.SEE ALSO: typo3.flow3:package:create (Create a new package)
  16. 16. Hanau, GermanyHello World! $ ./flow3 kickstart:package Acme.Demo
  17. 17. H e ll o Wo r ld ! 5 1 1 1 Ro bert Lem ke D.P. F l u x t r time ();
  18. 18. Hanau, GermanyHello World!StandardController.php <?php namespace AcmeDemoController; use TYPO3FLOW3MVCControllerActionController; class StandardController extends ActionController { /** * @param string $name * @return string */ public function indexAction($name) { return "Hello $name!"; } } ?>
  19. 19. Hanau, GermanyTackling the Heart of Software Development /**Domain-Driven Design * Paper submitted by * a speaker * @scope prototype * @entityA methodology which ... */ class Paper { • results in rich domain models /** * @var Participant */ • provides a common language protected $author; across the project team /** * @var string */ • simplify the design of complex protected $title; applications /** * @var string */ protected $shortAbstra ct;FLOW3 is the first PHP framework /**tailored to Domain-Driven Design * @var string */ protected $abstract;
  20. 20. Hanau, GermanyDomain-Driven DesignDomain activity or business of the userDomain-Driven Design is about • focussing on the domain and domain logic • accurately mapping the concepts to software • forming a ubiquitous language among the project members
  21. 21. Hanau, GermanyDomain-Driven DesignUbiquitous Language • important prerequisite for successful collaboration • use the same words for • discussion • modeling • development • documentation
  22. 22. Hanau, GermanyDomain-Driven Design
  23. 23. Hanau, GermanyDomain: Conference
  24. 24. Hanau, GermanyDomain: Conference
  25. 25. Hanau, GermanyDomain: Conference
  26. 26. Hanau, GermanyDomain: Conference
  27. 27. K ic k s t a rt ing "C o n f e re n c e" 5 1 1 1 Ro bert Lem ke D.P. F l u x t r time ();
  28. 28. Hanau, GermanyDomain: Conference
  29. 29. Hanau, GermanyObject ManagementDependency Injection • a class doesnt create or retrieve the instance of another class but gets it injected • fosters loosely-coupling and high cohesion ‣ more stable, reusable code
  30. 30. Hanau, GermanyObject ManagementFLOW3s take on Dependency Injection • one of the first PHP implementations (started in 2006, improved ever since) • object management for the whole lifecycle of all objects • no unnecessary configuration if information can be gatered automatically (autowiring) • intuitive use and no bad magical surprises • fast! (like hardcoded or faster)
  31. 31. Hanau, Germany WarConstructor Injection: Symfony 2 nin g (Im :m igh no t co Sym f nta ony exp in erro <?php ert .. .) rsnamespace AcmeDemoBundleController;use SymfonyBundleFrameworkBundleControllerController;use SymfonyComponentHttpFoundationRedirectResponse;use SensioBundleFrameworkExtraBundleConfigurationRoute;use SensioBundleFrameworkExtraBundleConfigurationTemplate;use AcmeDemoBundleGreeterService;class DemoController extends Controller { /** * @var AcmeDemoBundleGreeterService */ protected $greeterService; /** * @param AcmeDemoBundleGreeterService */ public function __construct($greeterService = NULL) { $this->greeterService = $greeterService; } /** * @Route("/hello/{name}", name="_demo_hello") */ public function helloAction($name) { return new Response(Hello . $this->greeterService->greet($name), 200, array(Content-Type => text/plain)); }
  32. 32. Hanau, Germany War Constructor Injection: Symfony 2 nin g (Im :m igh no t co Sym f nta ony exp in erro ert .. .) rs <?xml version="1.0" ?><container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <services> <service id="acme.demo.greeterservice" class="AcmeDemoBundleGreeterService" public="false" /> <service id="acme.demo.democontroller" class="AcmeDemoBundleControllerDemoController"> <argument type="service" id="acme.demo.greeterservice" /> </service> </services></container>
  33. 33. Hanau, GermanyConstructor Injection <?phpnamespace F3DemoController;use F3FLOW3MVCControllerActionController;use F3DemoServiceGreeterService;class DemoController extends ActionController { /** * @var F3DemoServiceGreeterService */ protected $greeterService; /** * @param F3DemoServiceGreeterService */ public function __construct(F3DemoServiceGreeterService $greeterService) { $this->greeterService = $greeterService; } /** * @param string $name */ public function helloAction($name) { return Hello . $name; }}
  34. 34. Hanau, GermanyConstructor Injection
  35. 35. Hanau, GermanySetter Injection<?phpnamespace F3DemoController;use F3FLOW3MVCControllerActionController;use F3DemoServiceGreeterService;class DemoController extends ActionController { /** * @var F3DemoServiceGreeterService */ protected $greeterService; /** * @param F3DemoServiceGreeterService */ public function injectGreeterService(F3DemoServiceGreeterService $greeterService) { $this->greeterService = $greeterService; } /** * @param string $name */ public function helloAction($name) { return Hello . $name; }}
  36. 36. Hanau, GermanyProperty Injection<?phpnamespace F3DemoController;use F3FLOW3MVCControllerActionController;use F3DemoServiceGreeterService;class DemoController extends ActionController { /** * @var F3DemoServiceGreeterService * @inject */ protected $greeterService; /** * @param string $name */ public function helloAction($name) { return Hello . $name; }}
  37. 37. Hanau, GermanyObjects.yaml F3FLOW3SecurityCryptographyRsaWalletServiceInterface: className: F3FLOW3SecurityCryptographyRsaWalletServicePhp scope: singleton properties: keystoreCache: object: factoryObjectName: F3FLOW3CacheCacheManager factoryMethodName: getCache arguments: 1: value: FLOW3_Security_Cryptography_RSAWallet
  38. 38. Hanau, GermanyObject Management class Customer { /** * @inject * @var CustomerNumberGenerator */ protected $customerNumberGenerator; ...}$customer = new Customer();$customer->getCustomerNumber();
  39. 39. Hanau, GermanyObject Management <?php declare(ENCODING = u tf-8); namespace F3Confere nceDomain ModelConference; /**FLOW3 creates proxy classes * Autogenerated Prox y Classfor realizing DI and AOP magic * @scope prototype * @entity */ class Paper extends • new operator is supported F3FLOW3Persistenc Paper_Original implem eAspectPersistence ents F3FLOW3Object MagicInterface { Pr /** • proxy classes are created * @var string * @Id on the fly * @Column(length="40 ") * introduced by F3F LOW3PersistenceAsp */ ectPersistenceMagic • in production context all protected $FLOW3_Per sistence_Identifier = NULL; code is static private $FLOW3_AOP_P roxy_targetMethodsAn dGroupedAdvices = ar ra private $FLOW3_AOP_P roxy_groupedAdviceCh ains = array(); private $FLOW3_AOP_P roxy_methodIsInAdvic eMode = array(); /** * Autogenerated Prox y Method */ public function __co nstruct() {
  40. 40. Hanau, GermanyYour Own Commands $ ./flow3 kickstart:commandcontroller Acme.Demo Test
  41. 41. Hanau, GermanyValidationValidation is about different things• incoming data needs to be validated for security reasons • no evil markup in submitted content• domain model integrity needs to be ensured • an email needs to be (syntactically) valid • credit card numbers should consist only of digits
  42. 42. Hanau, GermanyValidationValidation in FLOW3• you do not want to code checks into your controllers• FLOW3 separates validation from your controller’s concerns • no PHP code needed for validation • declared through annotations
  43. 43. Hanau, GermanyValidationValidation Models• BaseProperties rules defining the minimum requirements on individual properties of a model• BaseModel rules or custom validators enforcing the minimum requirements on the combination of properties of a model• Supplemental rules defining additional requirements on a model for a specific situation (e.g. a certain action method)
  44. 44. Hanau, GermanyValidationBase Properties• Validation rules defined directly at the properties /** * @var string * @validate StringLength(minimum = 10, maximum = 100) */ protected $title; /** * @var string * @validate StringLength(minimum = 1, maximum = 50) */ protected $author;
  45. 45. Hanau, GermanyValidationValidators• validators provided by FLOW3 can be used through their short name • Count, Float, NotEmpty, RegularExpression, Uuid, DateTime, NumberRange, StringLength, Alphanumeric, Integer, Number, String, EmailAddress, Label, Raw, Text• custom validators need to implement the ValidatorInterface• use them by specifying the fully qualified class name /** * @var DambekalnsStuffDomainModelStuff * @validate DambekalnsStuffDomainValidatorStuffValidator */ protected $stuff;
  46. 46. Hanau, GermanyProperty MapperTransfer properties from A to B • Allows for complete or partial copying of objects and object graphs • Is used by the MVC framework for the mapping of raw GET and POST data to Argument objects
  47. 47. Hanau, Germany Property Mapper $articleArray = array( headline => Hello World!, story => Just a demo ... ); $article = $mapper->convert($sourceArray, Acme.DemoDomainModelArticle);
  48. 48. Hanau, Germany Resource Management Image Upload Resources are handled like other properties in a form: <f:form method="blog" action="update" object="{blog}" name="blog"enctype="multipart/form-data"> <f:if condition="{blog.authorPicture}"> <img src="{f:uri.resource(resource: blog.authorPicture)}" /> </f:if> <label for="authorPicture">Author picture</label> <f:form.upload property="authorPicture" id="authorPicture" /> <f:form.submit value="Update"/> </f:form>
  49. 49. Hanau, Germany Property Mapper Allow nested object structures For security reasons the creation of nested structure through the property mapper is disabled by default /** * @return void */ public function initializeUpdateAction() { $this->arguments[article]->getPropertyMappingConfiguration() ->allowCreationForSubProperty(picture); $this->arguments[article]->getPropertyMappingConfiguration() ->allowModificationForSubProperty(picture); }
  50. 50. Hanau, GermanyPersistenceObject Persistence in the Flow • based on Doctrine 2 • seamless integration into FLOW3 • provides all the great Doctrine 2 features • uses UUIDs • low level persistence API • allows for own, custom persistence backends (instead of Doctrine 2) • e.g. CouchDB, Solr
  51. 51. Hanau, Germany Basic Object Persistence // Create a new customer and persist it: $customer = new Customer("Robert"); $this->customerRepository->add($customer); // Find an existing customer: $otherCustomer = $this->customerRepository->findByFirstName("Karsten"); // and delete it: $this->customerRepository->remove($otherCustomer);
  52. 52. Hanau, Germany Validation and Doctrine Annotationsnamespace TYPO3BlogDomainModel;/** * A Blog object * * @Entity */class Blog { /** * @var string * @validate Text, StringLength(minimum = 1, maximum = 80) * @Column(length="80") */ protected $title; /** * @var DoctrineCommonCollectionsCollection<TYPO3BlogDomainModelPost> * @OneToMany(mappedBy="blog") * @OrderBy({"date" = "DESC"}) */ protected $posts; ...}
  53. 53. Hanau, GermanyPersistence-related Annotations@Entity Declares a class as "entity"@Column Controls the database column related to the class property. Very useful for longer text content (type="text" !)@ManyToOne Defines relations to other entities. Unlike with@OneToMany vanilla Doctrine targetEntity does not have to be@ManyToMany given but will be reused from the @var@OneToOne annotation. cascade can be used to cascade operation to related objects.
  54. 54. Hanau, GermanyPersistence-related Annotations@var Defines the type of a property, collections can be typed using angle brackets: DoctrineCommonCollectionsCollection<TYPO3ConferenceDomainModelComment>@transient The property will be ignored, it will neither be persisted nor reconstituted@identity Marks the property as part of an objects identity
  55. 55. Hanau, Germany Custom Queries using the Query Object Model/** * A PostRepository */class PostRepository extends TYPO3FLOW3PersistenceRepository { /** * Finds posts by the specified tag and blog * * @param TYPO3BlogDomainModelTag $tag * @param TYPO3BlogDomainModelBlog $blog The blog the post must refer to * @return TYPO3FLOW3PersistenceQueryResultInterface The posts */ public function findByTagAndBlog(TYPO3BlogDomainModelTag $tag, TYPO3BlogDomainModelBlog $blog) { $query = $this->createQuery(); return $query->matching( $query->logicalAnd( $query->equals(blog, $blog), $query->contains(tags, $tag) ) ) ->setOrderings(array( date => TYPO3FLOW3PersistenceQueryInterface::ORDER_DESCENDING) ) ->execute(); }}
  56. 56. Hanau, GermanySchema ManagementDoctrine 2 Migrations• Migrations allow schema versioning and change deployment• Migrations are the recommended way for DB updates• Tools to create and deploy migrations are integrated with FLOW3
  57. 57. Hanau, GermanySchema ManagementRunning Migrations• needed after installation or upgrade:$ ./flow3 doctrine:migrate
  58. 58. Hanau, GermanySchema ManagementManual database updates• for simple situations this can be good enough:$ ./flow3 doctrine:create$ ./flow3 doctrine:update• useful when • you are just starting a project and have never released
  59. 59. Hanau, GermanySchema ManagementGenerating migrations$ ./flow3 doctrine:migrationgenerateGenerated new migration class to "…/Version20110608074324.php"from schema differences.$• Generated migrations can contain errors and should be checked and adjusted as needed• Migrations need to be moved to their “owning” package manually
  60. 60. M ig rat io n s 5 8 1 1 Ro bert Lem ke D.P. F l u x t r time ();
  61. 61. Hanau, GermanyFluidExample for assigning a string to a Fluid variable: // in the action controller: $this->view->assign(title, Welcome to Fluid); <!-- in the Fluid template: --> <head> <title>{title}</title> </head>
  62. 62. Hanau, GermanyFluidVariables can also be objects: // in the action controller: $this->view->assign(conference, $conference); <!-- in the Fluid template: --> <div class="venue"> <p>Venue Street: {conference.venue.street}</p> </div>
  63. 63. Hanau, GermanyFluidif-then-else: // in the action controller: $this->view->assign(post, $blogPost); <!-- in the Fluid template: --> <f:if condition="{post.comments}"> <f:then>There are some comments.</f:then> <f:else>There are no comments.</f:else> </f:if>
  64. 64. Hanau, GermanyFluidfor-each: // in the action controller: $this->view->assign(ages, array("Karsten" => 34, "Robert" => 35)); <!-- in the Fluid template: --> <ul> <f:for each="{ages}" as="age" key="name"> <li>{name} is {age} year old.</li> </f:for> </ul>
  65. 65. Hanau, GermanyFluidfor-each: // in the action controller: $this->view->assign(post, $blogPost); <!-- in the Fluid template: --> <f:if condition="{post.comments}"> <ul> <f:for each="{post.comments}" as="comment" > <li>{post.title}</li> </f:for> </ul> </f:if>
  66. 66. Hanau, GermanyFluidView helpers – in this case the link.action view helper: <!-- in the Fluid template: --> {namespace f=F3FluidViewHelpers} <f:link.action action="delete" arguments="{post: post, really: yes}"> Delete this post </f:link.action>
  67. 67. F lue n t F lu id 5 8 1 1 K. Damb ek aln s & R. Lem ke D.P. F l u x t r time ();
  68. 68. Hanau, GermanySecurityTouchless Security, Flow-Style • security is handled at a central place (through AOP) • third-party code is as secure as possible by default • modeled after our experiences in the TYPO3 project and Spring Security (Java framework) • provides authentication, authorization, validation, filtering ... • can intercept arbitrary method calls • transparently filters content through query-rewriting • extensible for new authentication or authorization mechanisms
  69. 69. Hanau, GermanySecurity Policy
  70. 70. Us e rs a n d L o g in 5 8 1 1 K. Damb ek aln s & R. Lem ke D.P. F l u x t r time ();
  71. 71. Hanau, GermanyAOPAspect-Oriented Programming • programming paradigm • separates concerns to improve modularization • OOP modularizes concerns into objects • AOP modularizes cross-cutting concerns into aspects • FLOW3 makes it easy (and possible at all) to use AOP in PHP
  72. 72. Hanau, GermanyAOP /** * @aspectFLOW3 uses AOP for ... * @introduce */ F3FLOW3Pers istenceAspec tPersistence class Persist MagicInterfac enceMagicAspe e, F3FLO ct { • persistence magic /** * @pointcut c lassTaggedWit */ h(entity) || classTaggedWi th(valueobjec • logging public functi on isEntityOr ValueObject() {} t) /** * @var string • debugging * @Id * @Column(len gth="40") * @introduce F3FLOW3Pers */ istenceAspec tPersistence • security protected $FL OW3_Persisten ce_Identifier ; MagicAspect-> isEnti /** * After retur ning advice, * making sure w e have an UUI * @param F3 D for each an FLOW3AOPJoi d every * @return voi nPointInterfa d ce $joinPoint * @before cla The current j ssTaggedWith( oin po */ entity) && me thod(.*->__co public functi nstruct()) on generateUU $proxy = $joi ID(F3FLOW3 nPoint->getPr AOPJoinPoint oxy(); Interface $jo F3FLOW3Ref inPoint) lectionObjec } tAccess::setP roperty($prox y , FLOW3_Per siste
  73. 73. Th e Wiz a rd o f AOP 5 8 1 1 K. Damb ek aln s & R. Lem ke D.P. F l u x t r time ();
  74. 74. Hanau, GermanySignal-Slot Event HandlingSignal • can be fired on any event • can be freely defined by the developerSlot • is invoked when a signal is emitted • any method can be used as a slotany signal can be wired to any slot
  75. 75. Hanau, GermanySignal-Slot Event Handling /** * @param F3BlogDomainModelPost $post * @param F3BlogDomainModelComment $newComment * @return void */ public function createAction(F3BlogDomainModelPost $post, F3BlogDomainModelComment $newComment) { $post->addComment($newComment); $this->emitCommentCreated($newComment, $post); … } /** * @param F3BlogDomainModelComment $comment * @param F3BlogDomainModelPost $post * @return void * @signal */ protected function emitCommentCreated(F3BlogDomainModelComment $comment, F3BlogDomainModelPost $post) {}
  76. 76. Hanau, GermanySignal-Slot Event HandlingSignals are wired to Slots in a package’s bootstrap: /** * Invokes custom PHP code directly after the package manager has been * initialized. * * @param F3FLOW3CoreBootstrap $bootstrap The current bootstrap * @return void */ public function boot(F3FLOW3CoreBootstrap $bootstrap) { $dispatcher = $bootstrap->getSignalSlotDispatcher(); $dispatcher->connect( F3BlogControllerCommentController, commentCreated, F3BlogServiceNotification, sendNewCommentNotification ); }
  77. 77. Hanau, GermanySignal-Slot Event HandlingAny method can be a slot: /** * @param F3BlogDomainModelComment $comment * @param F3BlogDomainModelPost $post * @return void */ public function sendNewCommentNotification(F3BlogDomainModelComment $comment, F3BlogDomainModelPost $post) { $mail = new F3SwiftMailerMessage(); $mail ->setFrom(array(john@doe.org => John Doe)) ->setTo(array(karsten@typo3.org => Karsten Dambekalns)) ->setSubject(New comment on blog post " . $post->getTitle() . ") ->setBody($comment->getContent()) ->send(); }
  78. 78. Hanau, GermanyRoadmaphttp://forge.typo3.org/projects/flow3-distribution-base/roadmap
  79. 79. Hanau, GermanyConference Appgit://git.typo3.org/TYPO3v5/Distributions/Conference.git
  80. 80. Hanau, GermanyBlog Appgit://git.typo3.org/FLOW3/Applications/Blog.git
  81. 81. Hanau, GermanyThank You & Have Fun! • FLOW3: http://flow3.typo3.org • Blog: http://robertlemke.de/blog • Twitter: @robertlemke / @mrbasti • Feedback: robert@typo3.org / bastian@typo3.org

×