TYPO3 Flow 2.0 Workshop T3BOARD13

15,859
-1

Published on

Slides of the TYPO3 Flow 2.0 fundamentals workshop which took place at Schmittenhöhe, Austria during T3BOARD13

Published in: Technology
1 Comment
5 Likes
Statistics
Notes
  • Please dear can you contact me on my email id jessicaduale@yahoo.com, i have something private to discuss with you. Thank, i will be happy to meet you in my email. Jessica
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
15,859
On Slideshare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
40
Comments
1
Likes
5
Embeds 0
No embeds

No notes for slide

TYPO3 Flow 2.0 Workshop T3BOARD13

  1. 1. Robert Lemke_TYPO3 Flow 2.0
  2. 2. project founder of TYPO3 Flow and TYPO3 Neosco-founder of the TYPO3 Associationcoach, coder, consultant36 years old TEXT HERElives in Lübeck, Germany1 wife, 2 daughters, 1 espresso machinelikes drumming
  3. 3. TYPO3 Flow Website and Download
  4. 4. Installation via Composer$ curl -s https://getcomposer.org/installer | php$ sudo mv composer.phar /usr/local/bin/composer$ composer create-project --stability="beta" --dev typo3/flow-base-distribution MyProject
  5. 5. Set File Permissions $ sudo ./flow core:setfilepermissions robert _www _www TYPO3 Flow 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
  6. 6. Set Up Database ConnectionConfiguration/Settings.yamlTYPO3: Flow: persistence: backendOptions: host: 127.0.0.1 # adjust to your database host dbname: training # adjust to your database name user: root # adjust to your database user password: password # adjust to your database password # if you want to log executed SQL queries, enable the next 2 lines # doctrine: # sqlLogger: TYPO3FlowPersistenceDoctrineLoggingSqlLogger # You might need to uncomment the following lines and specify # the location of the PHP binary manually. # core: # phpBinaryPathAndFilename: C:/path/to/php.exe
  7. 7. Set Up Virtual HostApache Virtual Host <VirtualHost *:80> DocumentRoot ~/Sites/Flow/Web/ ServerName flow.dev SetEnv FLOW_CONTEXT Development </VirtualHost> <VirtualHost *:80> DocumentRoot ~/Sites/Flow/Web/ ServerName flow.prod SetEnv FLOW_CONTEXT Production </VirtualHost>
  8. 8. Final Check
  9. 9. Command Line Use$ ./flow help kickstart:packageKickstart a new packageCOMMAND: typo3.kickstart:kickstart:packageUSAGE: ./flow 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.flow:package:create (Create a new package)
  10. 10. Command Line Use$ ./flow help kickstart:actioncontrollerKickstart a new action controllerCOMMAND: typo3.kickstart:kickstart:actioncontrollerUSAGE: ./flow kickstart:actioncontroller [<options>] <package key> <controller name>ARGUMENTS: --package-key The package key of the package for the new controller with an optional subpackage, (e.g. "MyCompany.MyPackage/Admin"). --controller-name The name for the new controller. This may also be a comma separated list of controller names.OPTIONS: --generate-actions Also generate index, new, create, edit, update and delete actions. --generate-templates Also generate the templates for each action. --generate-related Also create the mentioned package, related model and repository if neccessary. --force Overwrite any existing controller or template code. Regardless of this flag, the package, model and repository will never be overwritten.DESCRIPTION:
  11. 11. Biggest Book Store: Amazon
  12. 12. Biggest River: Amazon River © Google
  13. 13. Smallest River: Roe River © Google
  14. 14. Smallest River: Roe River © Google
  15. 15. Smallest River: Roe River © Google
  16. 16. Smallest River: Roe River
  17. 17. Smallest Book Store: Roebooks
  18. 18. Sketchy Model
  19. 19. H e ll o Wo r ld … 5 2 1 1 Ro bert Lem ke D.P. F l u x t r time ();
  20. 20. Object 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
  21. 21. class SomeService { protected static $instance; public function getInstance() { if (self::$instance === NULL) { self::$instance = new self; } return self::$instance; }}class SomeOtherController { public function action() { $service = SomeService::getInstance(); … }}
  22. 22. class ServiceLocator { protected static $services = array(); public function getInstance($name) { return self::$service[$name]; }}class SomeOtherController { public function action() { $service = ServiceLocator::getInstance("SomeService"); … }}
  23. 23. class BookController extends ActionController { /** * @var BookRepository */ protected $bookRepository; /** * @param BookRepository $bookRepository */ public function __construct(BookRepository $bookRepository) { $this->bookRepository = $bookRepository; }}
  24. 24. class BookController extends ActionController { /** * @var BookRepository */ protected $bookRepository; /** * @param BookRepository $bookRepository */ public function injectBookRepository(BookRepository$bookRepository) { $this->bookRepository = $bookRepository; }}
  25. 25. class BookController extends ActionController { /** * @FlowInject * @var BookRepository */ protected $bookRepository;}
  26. 26. TYPO3FlowSecurityCryptographyRsaWalletServiceInterface: className: TYPO3FlowSecurityCryptographyRsaWalletServicePhp scope: singleton properties: keystoreCache: object: factoryObjectName: TYPO3FLOW3CacheCacheManager factoryMethodName: getCache arguments: 1: value: FLOW3_Security_Cryptography_RSAWallet
  27. 27. Object ManagementFlows 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)
  28. 28. class Customer { /** * @FlowInject * @var AcmeCustomerNumberGenerator */ protected $customerNumberGenerator; ...}$customer = new Customer();$customer->getCustomerNumber();
  29. 29. Object Management <?php declare(ENCODING = u tf-8); namespace TYPO3ConfFlow creates proxy use TYPO3FlowAnnot erenceDomainModel ations as Flow; Conference;classes /** * Autogenerated Proxfor realizing DI and AOP * @FlowScope(“proto * @FlowEntity y Class type”)magic */ class Paper extends Paper_Original implem TYPO3FlowPersiste ents TYPO3FlowObje nceAspectPersisten c ceMagicInterface { _ new operator is /** * @var string supported * @ORMId * @ORMColumn(length ="40") * introduced by TYPO 3FlowPersistenceA spectPersistenceMag _ proxy classes are */ protected $Flow_Pers istence_Identifier = i NULL; created on the fly private $Flow_AOP_Pr oxy_targetMethodsAnd GroupedAdvices = arra y private $Flow_AOP_Pr oxy_groupedAdviceCha _ in production context private $Flow_AOP_Pr oxy_methodIsInAdvice ins = array(); all code is static Mode = array(); /** * Autogenerated Prox y Method */ public function __co nstruct() {
  30. 30. Object Scope /** * @FlowScope("prototype") */ class BookController extends ActionController { _ prototype: multiple instances for one request _ singleton: one unique instance for one request _ session: one unique instance for one session _ default scope: prototype.
  31. 31. Lifecycle Methods/** * Called after the object has been constructed and all * dependencies have been injected * * @param integer $initializationCause * @return void */public function initializeObject($initializationCause) { switch ($initializationCause) { case ObjectManagerInterface::INITIALIZATIONCAUSE_CREATED : … case ObjectManagerInterface::INITIALIZATIONCAUSE_RECREATED : … }}
  32. 32. Lifecycle Methods/** * Called shortly before the framework shuts down */public function shutdownObject() {}
  33. 33. Aspect-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
  34. 34. AOP /** * @AspectFLOW3 uses AOP for ... * @Introduce TYPO3FlowPe */ rsistenceAsp ectPer class Persist enceMagicAspe _ persistence magic ct { /** * @Pointcut c _ logging */ lassTaggedWit h(entity) || classT public functi on isEntityOr V a l u e O b j e c t( ) _ debugging /** {} * After retur ning advice, * making sure w _ security * @param TYP e have O3FlowAOPJ * @return voi oinPointInter d face $j * @Before cla ssTaggedWith( */ entity) && me thod(.* public functi on generateUU $proxy = $joi I D( J o i n P o i n t I n P o i n t- >g e t P r nterface O b j e c t A c c e s s: oxy(); :setProperty( } $proxy, Flow _Persis
  35. 35. Aspect_ part of the application where cross-cutting concerns are implemented_ in Flow aspects are classes annotated with @FlowAspect
  36. 36. Join PointA single point in the call graph _ method execution _ exception
  37. 37. Join PointA single point in the call graph _ method execution _ exceptionRepresents an event, not a location
  38. 38. PointcutA set of join points where advices could be executed _ can be composed _ can be named
  39. 39. AdviceAction to take at a join points defined by the point cut
  40. 40. Kinds of AdviceAdvice types supported by Flow:@FlowBefore@FlowAfterReturning@FlowAfterThrowing@FlowAfter@FlowAround
  41. 41. Pointcut Designatorsmethod(AcmeDemoMyClass->myMethod())class(AcmeDemoMyClass)within(AcmeDemoMyInterface)classAnnotatedWith(someTag)methodAnnotatedWith(anotherTag)setting(Acme.Demo.SomeSetting = "yeah, do it")filter(AcmeDemoMyCustomFilterImplementation)evaluate(coffe.kind = "Arabica")
  42. 42. /** * An aspect which centralizes the logging of important session actions. * * @FlowAspect * @FlowScope("singleton") */class LoggingAspect { /** * @var TYPO3FlowLogSystemLoggerInterface * @FlowInject */ protected $systemLogger; /** * Logs calls of start() * * @FlowAfter("within(TYPO3FlowSessionSessionInterface) && method(.*->start())" * @param TYPO3FlowAopJoinPointInterface $joinPoint The current joinpoint */ public function logStart(TYPO3FlowAopJoinPointInterface $joinPoint) { $session = $joinPoint->getProxy(); if ($session->isStarted()) { $this->systemLogger->log(sprintf(Started session with id %s, $session->getId(
  43. 43. PersistenceObject Persistence in the Flow _ based on Doctrine 2 _ seamless integration into Flow _ 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
  44. 44. // 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);
  45. 45. AnnotationsIn order to use less code, the following examples assumethat annotations have been imported directly: use TYPO3FlowAnnotationsEntity; /** * @Entity */ class Foo {}
  46. 46. Validation and Doctrine Annotations/** * @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"}) */
  47. 47. Persistence-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.@OneToMany Unlike with vanilla Doctrine@ManyToMany targetEntity does not have to be given@OneToOne but will be reused from the @var annotation. cascade can be used to cascade operation to related objects.
  48. 48. Persistence-related Annotations@var Defines the type of a property, collections can be typed using angle brackets Collection<TYPO3ConferenceDomainModelComment>@transient The property will be ignored, it will neither be persisted nor reconstituted@identity Marks the property as part of an objects identity
  49. 49. Custom Queries using the Query Object Modelclass PostRepository extends Repository { /** * Finds posts by the specified tag and blog * * @param TYPO3BlogDomainModelTag $tag * @param TYPO3BlogDomainModelBlog $blog The blog the post must refe * @return TYPO3FlowPersistenceQueryResultInterface 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) )
  50. 50. Schema 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 Flow
  51. 51. Schema ManagementExecuting migration scriptsNeeded after installation or upgrade:$ ./flow doctrine:migrate
  52. 52. Schema ManagementManual database updatesAd-hoc table and column creation, while you’re developing:$ ./flow doctrine:create$ ./flow doctrine:update
  53. 53. Schema ManagementGenerating migration scriptsCreates a basis for a migration script which sometimesneeds to be adjusted but in any case needs to be checked:$ ./flow doctrine:migrationgenerate
  54. 54. Security _ centrally managed (through AOP) _ as secure as possible by default _ modeled after TYPO3 CMS and Spring Security _ authentication, authorization, validation, filtering ... _ can intercept arbitrary method calls _ transparently filters content through query-rewriting _ extensible for new authentication or authorization mechanisms
  55. 55. Accounts, Users, AuthenticationFlow distinguishes between accounts and persons: _ account: TYPO3FlowSecurityAccount _ person: TYPO3PartyDomainModelPersonA person (or machine) can have any number of accounts.
  56. 56. Creating Accounts _ always use the AccountFactory _ create a party (eg. a Person) separately _ assign the account to the party _ add account and party to their respective repositories
  57. 57. $account = $this->accountFactory->createAccountWithPassword( $accountIdentifier, $password, array($role));$this->accountRepository->add($account);$person = new Person();$person->addAccount($account);$name = new PersonName(, Robert, , Lemke);$person->setName($name);$this->partyRepository->add($person);
  58. 58. Authentication Configuration _ Authentication Provider is responsible for authentication in a specific "area" _ Entry Point kicks in if a restricted resource is accessed and no account is authenticated yet
  59. 59. TYPO3: Flow: security: authentication: providers: DefaultProvider: provider: PersistedUsernamePasswordProvider entryPoint: WebRedirect entryPointOptions: routeValues: @package: RobertLemke.Example.Bookshop @controller: Login @action: login @format: html
  60. 60. Security Policy (policy.yaml) _ resources defines what can potentially be protected _ roles defines who can potentially be granted or denied access _ acls defines who may or may not access which resource
  61. 61. resources: methods: BookManagementMethods: method(.*Controller->(new|edit|create|delete|update)Action()) BookManagementDelete: method(.*BookController->deleteAction())roles: Administrator: []acls: methods: Administrator: BookManagementMethods: GRANT
  62. 62. Login / Logout _ simply extend AbstractAuthenticationController _ create a Fluid template with a login form
  63. 63. /** * @FlowScope("singleton") */class LoginController extends AbstractAuthenticationController { /** * @param TYPO3FlowMvcActionRequest $originalRequest The request * @return string */ protected function onAuthenticationSuccess(ActionRequest $originalRe $this->redirect(index, Book); } /** * @return void */ public function logoutAction() { parent::logoutAction(); $this->redirect(index, Book); }}
  64. 64. <f:base/><f:flashMessages /><f:form action="authenticate"> <f:form.textfield name="__authentication[TYPO3][Flow][Security][Authentication][Token][UsernamePassword][username]" /> <f:form.password name="__authentication[TYPO3][Flow][Security][Authentication][Token][UsernamePassword][password]" /> <f:form.submit value="login" /></f:form>
  65. 65. SecurityCross-Site Request Forgery _ enables an attacker to execute privileged operations without being authenticated _ the risk lies in using malicious links or forms while still being authenticated _ imagine a link coming in through an URL shortener...
  66. 66. SecurityAvoiding Cross-Site Request Forgery _ add a (truly!) random string token to each link or form _ make sure this token is correct before executing anything _ change the token as often as possible to make it impossible to send you a working malicious link while you’re logged in _ in most cases, we can assume that it should be enough to generate one token when you log in – that’s the default
  67. 67. SecurityCSRF Protection in Flow _ you must not forget to add that token to any link _ Flow automatically adds the CSRF token to each _ link you generate _ each form you create with Fluid _ and checks it for every call to a protected action _ the protection can be disabled using @skipCsrfProtection on an action
  68. 68. Robert Lemke_robertlemke.com@robertlemke
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×