SlideShare uma empresa Scribd logo
1 de 69
Baixar para ler offline
Robert Lemke_


TYPO3 Flow 2.0
project founder of TYPO3 Flow and TYPO3 Neos

co-founder of the TYPO3 Association

coach, coder, consultant

36 years old

                      TEXT HERE
lives in Lübeck, Germany

1 wife, 2 daughters, 1 espresso machine

likes drumming
TYPO3 Flow Website and Download
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
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 robert


Mac OS X:

  $ sudo dscl . -append /Groups/_www GroupMembership robert
Set Up Database Connection
Configuration/Settings.yaml
TYPO3:
  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'
Set Up Virtual Host
Apache 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>
Final Check
Command Line Use

$ ./flow help kickstart:package

Kickstart a new package

COMMAND:
  typo3.kickstart:kickstart:package

USAGE:
  ./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)
Command Line Use

$ ./flow help kickstart:actioncontroller

Kickstart a new action controller

COMMAND:
  typo3.kickstart:kickstart:actioncontroller

USAGE:
  ./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:
Biggest Book Store: Amazon
Biggest River: Amazon River




                              © Google
Smallest River: Roe River




                            © Google
Smallest River: Roe River




                            © Google
Smallest River: Roe River




                            © Google
Smallest River: Roe River
Smallest Book Store: Roebooks
Sketchy Model
H e ll o Wo r ld …

 5        2                1   1
        Ro bert Lem ke
        D.P. F l u x t r
       time ();
Object Management

Dependency Injection
 _ a class doesn't create or retrieve the
   instance of another class but get's it
   injected
 _ fosters loosely-coupling and high
   cohesion
 _ more stable, reusable code
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();
      …
    }

}
class ServiceLocator {

      protected static $services = array();

      public function getInstance($name) {
        return self::$service[$name];
      }

}



class SomeOtherController {

    public function action() {
      $service = ServiceLocator::getInstance("SomeService");
      …
    }

}
class BookController extends ActionController {

    /**
     * @var BookRepository
     */
    protected $bookRepository;

    /**
      * @param BookRepository $bookRepository
      */
    public function __construct(BookRepository $bookRepository) {
       $this->bookRepository = $bookRepository;
    }

}
class BookController extends ActionController {

    /**
     * @var BookRepository
     */
    protected $bookRepository;

  /**
    * @param BookRepository $bookRepository
    */
  public function injectBookRepository(BookRepository
$bookRepository) {
     $this->bookRepository = $bookRepository;
  }

}
class BookController extends ActionController {

    /**
     * @FlowInject
     * @var BookRepository
     */
    protected $bookRepository;

}
TYPO3FlowSecurityCryptographyRsaWalletServiceInterface:
  className: TYPO3FlowSecurityCryptography
RsaWalletServicePhp
  scope: singleton
  properties:
    keystoreCache:
      object:
        factoryObjectName: TYPO3FLOW3CacheCacheManager
        factoryMethodName: getCache
        arguments:
          1:
             value: FLOW3_Security_Cryptography_RSAWallet
Object Management

Flow's 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)
class Customer {

    /**
     * @FlowInject
     * @var AcmeCustomerNumberGenerator
     */
    protected $customerNumberGenerator;
     ...
}

$customer = new Customer();
$customer->getCustomerNumber();
Object Management
                           <?php
                           declare(ENCODING = 'u
                                                 tf-8');
                           namespace TYPO3Conf
Flow creates proxy         use TYPO3FlowAnnot
                                                erenceDomainModel
                                                ations as Flow;
                                                                     Conference;


classes                     /**
                             * Autogenerated Prox
for 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() {
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.
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 :
        …
    }
}
Lifecycle Methods

/**
  * Called shortly before the framework shuts down
  */
public function shutdownObject() {
}
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
AOP
                           /**
                            * @Aspect
FLOW3 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
Aspect

_ part of the application where cross-cutting concerns are
  implemented
_ in Flow aspects are classes annotated with
  @FlowAspect
Join Point

A single point in the call graph
 _ method execution
 _ exception
Join Point

A single point in the call graph
 _ method execution
 _ exception
Represents an event, not a location
Pointcut

A set of join points where advices could be executed
 _ can be composed
 _ can be named
Advice

Action to take at a join points defined by the point cut
Kinds of Advice

Advice types supported by Flow:
@FlowBefore
@FlowAfterReturning
@FlowAfterThrowing
@FlowAfter
@FlowAround
Pointcut Designators

method(AcmeDemoMyClass->myMethod())
class(AcmeDemoMyClass)
within(AcmeDemoMyInterface)
classAnnotatedWith(someTag)
methodAnnotatedWith(anotherTag)
setting(Acme.Demo.SomeSetting = "yeah, do it")
filter(AcmeDemoMyCustomFilterImplementation)

evaluate(coffe.kind = "Arabica")
/**
 * 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(
Persistence

Object 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
// 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);
Annotations

In order to use less code, the following examples assume
that annotations have been imported directly:


 use TYPO3FlowAnnotationsEntity;

 /**
  * @Entity
  */
 class Foo {}
Validation and Doctrine Annotations
/**
 * @Entity
 */
class Blog {

    /**
     * @var string
     * @Validate Text, StringLength(minimum = 1, maximum = 80)
     * @Column(length="80")
     */
    protected $title;

    /**
     * @var DoctrineCommonCollectionsCollection<TYPO3Blog
DomainModelPost>
     * @OneToMany(mappedBy="blog")
     * @OrderBy({"date" = "DESC"})
     */
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.
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
Custom Queries using the
   Query Object Model
class 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)
              )
Schema Management

Doctrine 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
Schema Management

Executing migration scripts
Needed after installation or upgrade:


$ ./flow doctrine:migrate
Schema Management

Manual database updates
Ad-hoc table and column creation, while you’re developing:


$ ./flow doctrine:create

$ ./flow doctrine:update
Schema Management

Generating migration scripts
Creates a basis for a migration script which sometimes
needs to be adjusted but in any case needs to be checked:

$ ./flow doctrine:migrationgenerate
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
Accounts, Users, Authentication

Flow distinguishes between accounts and persons:
 _ account: TYPO3FlowSecurityAccount
 _ person: TYPO3PartyDomainModelPerson


A person (or machine) can have any number of accounts.
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
$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);
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
TYPO3:
  Flow:
    security:
       authentication:
         providers:
           DefaultProvider:
             provider: 'PersistedUsernamePasswordProvider'
             entryPoint: 'WebRedirect'
             entryPointOptions:
               routeValues:
                 '@package': 'RobertLemke.Example.Bookshop'
                 '@controller': 'Login'
                 '@action': 'login'
                 '@format': 'html'
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
resources:
  methods:
    BookManagementMethods: 'method(.*Controller->(new|edit|create|
delete|update)Action())'
    BookManagementDelete: 'method(.*BookController->deleteAction())'

roles:
  Administrator: []



acls:
  methods:
    Administrator:
      BookManagementMethods: GRANT
Login / Logout

 _ simply extend AbstractAuthenticationController
 _ create a Fluid template with a login form
/**
 * @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');
    }
}
<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>
Security

Cross-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...
Security

Avoiding 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
Security

CSRF 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
Robert Lemke_
robertlemke.com
@robertlemke

Mais conteúdo relacionado

Mais procurados

ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
Kumar
 

Mais procurados (20)

08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Shark
Shark Shark
Shark
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Merb
MerbMerb
Merb
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
 
DataMapper
DataMapperDataMapper
DataMapper
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
ES6 metaprogramming unleashed
ES6 metaprogramming unleashedES6 metaprogramming unleashed
ES6 metaprogramming unleashed
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
 
Findbin libs
Findbin libsFindbin libs
Findbin libs
 

Destaque

TYPO3 Flow - PHP Framework for Developer Happiness
TYPO3 Flow - PHP Framework for Developer HappinessTYPO3 Flow - PHP Framework for Developer Happiness
TYPO3 Flow - PHP Framework for Developer Happiness
Christian Müller
 

Destaque (12)

TYPO3 Flow and the Joy of Development (FOSDEM 2013)
TYPO3 Flow and the Joy of Development (FOSDEM 2013)TYPO3 Flow and the Joy of Development (FOSDEM 2013)
TYPO3 Flow and the Joy of Development (FOSDEM 2013)
 
TYPO3 Flow 2.0 in the field - webtech Conference 2013
TYPO3 Flow 2.0 in the field - webtech Conference 2013TYPO3 Flow 2.0 in the field - webtech Conference 2013
TYPO3 Flow 2.0 in the field - webtech Conference 2013
 
TYPO3 Flow a solid foundation for medialib.tv
TYPO3 Flow a solid foundation for medialib.tvTYPO3 Flow a solid foundation for medialib.tv
TYPO3 Flow a solid foundation for medialib.tv
 
TYPO3 Flow 2.0 (International PHP Conference 2013)
TYPO3 Flow 2.0 (International PHP Conference 2013)TYPO3 Flow 2.0 (International PHP Conference 2013)
TYPO3 Flow 2.0 (International PHP Conference 2013)
 
T3CON14EU: Migrating from TYPO3 CMS to TYPO3 Flow
T3CON14EU: Migrating from TYPO3 CMS to TYPO3 FlowT3CON14EU: Migrating from TYPO3 CMS to TYPO3 Flow
T3CON14EU: Migrating from TYPO3 CMS to TYPO3 Flow
 
TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)
TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)
TYPO3 Flow: Beyond the Blog Example (Inspiring Flow 2013)
 
T3CON12 Flow and TYPO3 deployment with surf
T3CON12 Flow and TYPO3 deployment with surfT3CON12 Flow and TYPO3 deployment with surf
T3CON12 Flow and TYPO3 deployment with surf
 
TYPO3 5.0 Experience Concept
TYPO3 5.0 Experience ConceptTYPO3 5.0 Experience Concept
TYPO3 5.0 Experience Concept
 
TYPO3 Flow - PHP Framework for Developer Happiness
TYPO3 Flow - PHP Framework for Developer HappinessTYPO3 Flow - PHP Framework for Developer Happiness
TYPO3 Flow - PHP Framework for Developer Happiness
 
Testing TYPO3 Flow Applications with Behat
Testing TYPO3 Flow Applications with BehatTesting TYPO3 Flow Applications with Behat
Testing TYPO3 Flow Applications with Behat
 
TYPO3 Neos - past, present and future (T3CON14EU)
TYPO3 Neos - past, present and future (T3CON14EU)TYPO3 Neos - past, present and future (T3CON14EU)
TYPO3 Neos - past, present and future (T3CON14EU)
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 

Semelhante a TYPO3 Flow 2.0 Workshop T3BOARD13

2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php
Jochen Rau
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
nihiliad
 

Semelhante a TYPO3 Flow 2.0 Workshop T3BOARD13 (20)

Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3
 
Doctrine in FLOW3
Doctrine in FLOW3Doctrine in FLOW3
Doctrine in FLOW3
 
Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0
 
IPCSE12: Hands on FLOW3
IPCSE12: Hands on FLOW3IPCSE12: Hands on FLOW3
IPCSE12: Hands on FLOW3
 
Hands on FLOW3 (DPC12)
Hands on FLOW3 (DPC12)Hands on FLOW3 (DPC12)
Hands on FLOW3 (DPC12)
 
2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Symfony internals [english]
Symfony internals [english]Symfony internals [english]
Symfony internals [english]
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014Bioinformatics p5-bioperlv2014
Bioinformatics p5-bioperlv2014
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
TYPO3 Flow 2.0 (T3CON13 San Francisco)
TYPO3 Flow 2.0 (T3CON13 San Francisco)TYPO3 Flow 2.0 (T3CON13 San Francisco)
TYPO3 Flow 2.0 (T3CON13 San Francisco)
 

Mais de Robert Lemke

Mais de Robert Lemke (20)

Neos Content Repository – Git for content
Neos Content Repository – Git for contentNeos Content Repository – Git for content
Neos Content Repository – Git for content
 
A General Purpose Docker Image for PHP
A General Purpose Docker Image for PHPA General Purpose Docker Image for PHP
A General Purpose Docker Image for PHP
 
Scaleable PHP Applications in Kubernetes
Scaleable PHP Applications in KubernetesScaleable PHP Applications in Kubernetes
Scaleable PHP Applications in Kubernetes
 
Flownative Beach - Neos Meetup Hamburg 2022
Flownative Beach - Neos Meetup Hamburg 2022Flownative Beach - Neos Meetup Hamburg 2022
Flownative Beach - Neos Meetup Hamburg 2022
 
GitOps with Flux - IPC Munich 2022
GitOps with Flux - IPC Munich 2022GitOps with Flux - IPC Munich 2022
GitOps with Flux - IPC Munich 2022
 
OpenID Connect with Neos and Flow
OpenID Connect with Neos and FlowOpenID Connect with Neos and Flow
OpenID Connect with Neos and Flow
 
Neos Conference 2019 Keynote
Neos Conference 2019 KeynoteNeos Conference 2019 Keynote
Neos Conference 2019 Keynote
 
A practical introduction to Kubernetes (IPC 2018)
A practical introduction to Kubernetes (IPC 2018)A practical introduction to Kubernetes (IPC 2018)
A practical introduction to Kubernetes (IPC 2018)
 
Neos Conference 2018 Welcome Keynote
Neos Conference 2018 Welcome KeynoteNeos Conference 2018 Welcome Keynote
Neos Conference 2018 Welcome Keynote
 
A practical introduction to Event Sourcing and CQRS
A practical introduction to Event Sourcing and CQRSA practical introduction to Event Sourcing and CQRS
A practical introduction to Event Sourcing and CQRS
 
Neos Conference 2017 Welcome Keynote
Neos Conference 2017 Welcome KeynoteNeos Conference 2017 Welcome Keynote
Neos Conference 2017 Welcome Keynote
 
IPC16: A Practical Introduction to Kubernetes
IPC16: A Practical Introduction to Kubernetes IPC16: A Practical Introduction to Kubernetes
IPC16: A Practical Introduction to Kubernetes
 
IPC 2016: Content Strategy for Developers
IPC 2016: Content Strategy for DevelopersIPC 2016: Content Strategy for Developers
IPC 2016: Content Strategy for Developers
 
Docker in Production - IPC 2016
Docker in Production - IPC 2016Docker in Production - IPC 2016
Docker in Production - IPC 2016
 
Is this Open Source Thing Really Worth it? (IPC 2016 Berlin)
Is this Open Source Thing Really Worth it? (IPC 2016 Berlin)Is this Open Source Thing Really Worth it? (IPC 2016 Berlin)
Is this Open Source Thing Really Worth it? (IPC 2016 Berlin)
 
The Neos Brand (Inspiring Conference 2016)
The Neos Brand (Inspiring Conference 2016)The Neos Brand (Inspiring Conference 2016)
The Neos Brand (Inspiring Conference 2016)
 
Neos - past, present, future (Inspiring Conference 2016)
Neos - past, present, future (Inspiring Conference 2016)Neos - past, present, future (Inspiring Conference 2016)
Neos - past, present, future (Inspiring Conference 2016)
 
Meet Neos Nürnberg 2016: Ja ich will!
Meet Neos Nürnberg 2016: Ja ich will!Meet Neos Nürnberg 2016: Ja ich will!
Meet Neos Nürnberg 2016: Ja ich will!
 
Meet Neos Nürnberg 2016: Hallo Neos!
Meet Neos Nürnberg 2016: Hallo Neos!Meet Neos Nürnberg 2016: Hallo Neos!
Meet Neos Nürnberg 2016: Hallo Neos!
 
Turning Neos inside out / React.js HH
Turning Neos inside out / React.js HHTurning Neos inside out / React.js HH
Turning Neos inside out / React.js HH
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

TYPO3 Flow 2.0 Workshop T3BOARD13

  • 2. project founder of TYPO3 Flow and TYPO3 Neos co-founder of the TYPO3 Association coach, coder, consultant 36 years old TEXT HERE lives in Lübeck, Germany 1 wife, 2 daughters, 1 espresso machine likes drumming
  • 3. TYPO3 Flow Website and Download
  • 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. 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 robert Mac OS X: $ sudo dscl . -append /Groups/_www GroupMembership robert
  • 6. Set Up Database Connection Configuration/Settings.yaml TYPO3: 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. Set Up Virtual Host Apache 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>
  • 9. Command Line Use $ ./flow help kickstart:package Kickstart a new package COMMAND: typo3.kickstart:kickstart:package USAGE: ./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. Command Line Use $ ./flow help kickstart:actioncontroller Kickstart a new action controller COMMAND: typo3.kickstart:kickstart:actioncontroller USAGE: ./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:
  • 12. Biggest River: Amazon River © Google
  • 13. Smallest River: Roe River © Google
  • 14. Smallest River: Roe River © Google
  • 15. Smallest River: Roe River © Google
  • 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. Object Management Dependency Injection _ a class doesn't create or retrieve the instance of another class but get's it injected _ fosters loosely-coupling and high cohesion _ more stable, reusable code
  • 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. class ServiceLocator { protected static $services = array(); public function getInstance($name) { return self::$service[$name]; } } class SomeOtherController { public function action() { $service = ServiceLocator::getInstance("SomeService"); … } }
  • 23. class BookController extends ActionController { /** * @var BookRepository */ protected $bookRepository; /** * @param BookRepository $bookRepository */ public function __construct(BookRepository $bookRepository) { $this->bookRepository = $bookRepository; } }
  • 24. class BookController extends ActionController { /** * @var BookRepository */ protected $bookRepository; /** * @param BookRepository $bookRepository */ public function injectBookRepository(BookRepository $bookRepository) { $this->bookRepository = $bookRepository; } }
  • 25. class BookController extends ActionController { /** * @FlowInject * @var BookRepository */ protected $bookRepository; }
  • 26. TYPO3FlowSecurityCryptographyRsaWalletServiceInterface: className: TYPO3FlowSecurityCryptography RsaWalletServicePhp scope: singleton properties: keystoreCache: object: factoryObjectName: TYPO3FLOW3CacheCacheManager factoryMethodName: getCache arguments: 1: value: FLOW3_Security_Cryptography_RSAWallet
  • 27. Object Management Flow's 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. class Customer { /** * @FlowInject * @var AcmeCustomerNumberGenerator */ protected $customerNumberGenerator; ... } $customer = new Customer(); $customer->getCustomerNumber();
  • 29. Object Management <?php declare(ENCODING = 'u tf-8'); namespace TYPO3Conf Flow creates proxy use TYPO3FlowAnnot erenceDomainModel ations as Flow; Conference; classes /** * Autogenerated Prox for 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. 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. 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. Lifecycle Methods /** * Called shortly before the framework shuts down */ public function shutdownObject() { }
  • 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. AOP /** * @Aspect FLOW3 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.
  • 36. Aspect _ part of the application where cross-cutting concerns are implemented _ in Flow aspects are classes annotated with @FlowAspect
  • 37. Join Point A single point in the call graph _ method execution _ exception
  • 38. Join Point A single point in the call graph _ method execution _ exception Represents an event, not a location
  • 39. Pointcut A set of join points where advices could be executed _ can be composed _ can be named
  • 40. Advice Action to take at a join points defined by the point cut
  • 41. Kinds of Advice Advice types supported by Flow: @FlowBefore @FlowAfterReturning @FlowAfterThrowing @FlowAfter @FlowAround
  • 43. /** * 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(
  • 44. Persistence Object 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
  • 45. // 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);
  • 46. Annotations In order to use less code, the following examples assume that annotations have been imported directly: use TYPO3FlowAnnotationsEntity; /** * @Entity */ class Foo {}
  • 47. Validation and Doctrine Annotations /** * @Entity */ class Blog { /** * @var string * @Validate Text, StringLength(minimum = 1, maximum = 80) * @Column(length="80") */ protected $title; /** * @var DoctrineCommonCollectionsCollection<TYPO3Blog DomainModelPost> * @OneToMany(mappedBy="blog") * @OrderBy({"date" = "DESC"}) */
  • 48. 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.
  • 49. 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
  • 50. Custom Queries using the Query Object Model class 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) )
  • 51. Schema Management Doctrine 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
  • 52. Schema Management Executing migration scripts Needed after installation or upgrade: $ ./flow doctrine:migrate
  • 53. Schema Management Manual database updates Ad-hoc table and column creation, while you’re developing: $ ./flow doctrine:create $ ./flow doctrine:update
  • 54. Schema Management Generating migration scripts Creates a basis for a migration script which sometimes needs to be adjusted but in any case needs to be checked: $ ./flow doctrine:migrationgenerate
  • 55. 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
  • 56. Accounts, Users, Authentication Flow distinguishes between accounts and persons: _ account: TYPO3FlowSecurityAccount _ person: TYPO3PartyDomainModelPerson A person (or machine) can have any number of accounts.
  • 57. 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
  • 58. $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);
  • 59. 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
  • 60. TYPO3: Flow: security: authentication: providers: DefaultProvider: provider: 'PersistedUsernamePasswordProvider' entryPoint: 'WebRedirect' entryPointOptions: routeValues: '@package': 'RobertLemke.Example.Bookshop' '@controller': 'Login' '@action': 'login' '@format': 'html'
  • 61. 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
  • 62. resources: methods: BookManagementMethods: 'method(.*Controller->(new|edit|create| delete|update)Action())' BookManagementDelete: 'method(.*BookController->deleteAction())' roles: Administrator: [] acls: methods: Administrator: BookManagementMethods: GRANT
  • 63. Login / Logout _ simply extend AbstractAuthenticationController _ create a Fluid template with a login form
  • 64. /** * @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'); } }
  • 65. <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>
  • 66. Security Cross-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...
  • 67. Security Avoiding 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
  • 68. Security CSRF 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