Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Traveling Symfony Circus

The Traveling Symfony Circus

Come with us on a journey around the USA with lessons learned from teaching and seeing Symfony projects of all sizes and shapes. We'll talk about tricks for performance, security ACL (voters), ESI debugging, form variables, and hugging Drupal developers.

weaverryan

May 24, 2013
Tweet

More Decks by weaverryan

Other Decks in Technology

Transcript

  1. Who is this Hipster? • That “Docs” guy • KnpLabs

    US - Symfony consulting, training, Kumbaya • Writer for KnpUniversity.com screencasts knplabs.com github.com/weaverryan @weaverryan Thursday, May 23, 13
  2. Who is this Hipster? • That “Docs” guy • KnpLabs

    US - Symfony consulting, training, Kumbaya • Writer for KnpUniversity.com screencasts • Husband of the much more talented @leannapelham knplabs.com github.com/weaverryan @weaverryan Thursday, May 23, 13
  3. Cooperation Composer Other Libraries Drupal Aura Packages Symfony Components Symfony

    Framework AWS SDK Some random library you wrote! Thursday, May 23, 13
  4. PSR: PHP Standards Repository @weaverryan • PSR0 - Thou shalt

    name your classes, namespaces and directories in a sane way • PSR1 - Thou shalt use these coding standards • PSR2 - Thou shalt probably use these other coding standards too • PSR3 - Thou shalt create loggers that implement this interface http://www.php-fig.org/ Thursday, May 23, 13
  5. Symfony Components @weaverryan • Drupal • phpBB • eZ publish

    • Magento (Twig) • Joomla (Yaml) • Flow3 • Laravel • Zikula • Propel • Behat • Foxycart Thursday, May 23, 13
  6. The Main Event Symfony: Why - despite my previous slides

    - we haven’t all retired to a beach yet (the bad news) Thursday, May 23, 13
  7. 10 Lessons from touring like a Symfony Country Music Star

    http://www.weavercountry.com/ Thursday, May 23, 13
  8. How we see Symfony @weaverryan 1) Front Controller 2) Container

    is built 3) Kernel handles the request, fires events 4) Routing returns attributes 5) Resolver finds the controller gets its args 6) Controller is executed, returns a Response 7) A few more events fire, Response is sent HttpKernel: http://bit.ly/httpkernel Thursday, May 23, 13
  9. How a newcomer sees Symfony @weaverryan 1) app_dev.php (wtf is

    this?) 2) ??? routing? _controller, which points to a file somewhere? 3) Some magic ->render() method from an indexAction function I found? 4) some other things, I have no idea. There are like 20 dirs and 50 YAML files 5) #%$!ing class not found error! 6) Profit! Thursday, May 23, 13
  10. #1) Symfony Frameworkisms @weaverryan • _controller: MainBundle:Default:index • MainBundle:Default:index.html.twig •

    @MainBundle/Resources/config/routing.yml • arguments: [@router, %foo_param%] Thursday, May 23, 13
  11. #2) Namespaces @weaverryan • Namespaces are long • People forget

    the “namespace” • People forget the “use” statement • The autoloader can’t give you useful debugging information Thursday, May 23, 13
  12. use Symfony\Component\HttpFoundation\Response; $loader = new \Twig_Loader_Filesystem( __DIR__.'/templates' ); $twig =

    new \Twig_Environment($loader); $html = $templating->render('index.twig'); return new Response($html); w/o the container Thursday, May 23, 13
  13. 1) A Routing-Controller, Request-Response Flow e.g. for /foo, execute the

    fooAction function, then I’ll put PHP code there to make a page *every* framework does this... in pretty much exactly the same way Thursday, May 23, 13
  14. 2) A bunch of optional objects to help you build

    that page Thursday, May 23, 13
  15. Teaching Symfony @weaverryan • Avoid Symfony Framework’isms initially • Do

    things the long way, *then* opt into shortcuts • Start small (Silex!) • Remind people that routing+controller is 50% and everything else is totally optional Thursday, May 23, 13
  16. The smaller we make Symfony, the faster a user will

    understand it Thursday, May 23, 13
  17. public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new

    Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\...\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\...\SensioFrameworkExtraBundle(), new SfLive\WootBundle\SfLiveWootBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\...\WebProfilerBundle(); $bundles[] = new Sensio\...\SensioDistributionBundle(); $bundles[] = new Sensio\...\SensioGeneratorBundle(); } return $bundles; } Thursday, May 23, 13
  18. public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new

    Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\...\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\...\SensioFrameworkExtraBundle(), new SfLive\WootBundle\SfLiveWootBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\...\WebProfilerBundle(); $bundles[] = new Sensio\...\SensioDistributionBundle(); $bundles[] = new Sensio\...\SensioGeneratorBundle(); } return $bundles; } Thursday, May 23, 13
  19. public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new

    Symfony\Bundle\TwigBundle\TwigBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new SfLive\WootBundle\SfLiveWootBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\...\WebProfilerBundle(); } return $bundles; } Thursday, May 23, 13
  20. What *is* the Symfony Framework @weaverryan 1) A simple Routing-Controller,

    Request- Response Flow (HttpKernel) 2) A DI container with (optional) pre-built services for your convenience 3) (Optional) Shortcuts and other Symfony-isms that speed-up development Thursday, May 23, 13
  21. Initialization time @weaverryan Symfony\Component\HttpKernel\Kernel::boot() • Initialize and boot the bundles

    (~several ms) • Building and instantiating the container (depends) Thursday, May 23, 13
  22. What? Time Affects prod? Boot the bundles ~1-5ms Yes Rebuild

    the container? ~1-300ms No! Ok! Build the container ~500ms-seconds No! Instantiate the container <1ms Yes Building and Instantiating the Container Thursday, May 23, 13
  23. kernel.request.loading @weaverryan • The amount of time it takes to

    instantiate your listeners • How lightweight are your event listeners to construct? Thursday, May 23, 13
  24. Heavy Service Debugging @weaverryan • If a service is heavy

    to instantiate, there’s no good way (yet) to see that • Heavy instantiation is hidden in event “loading” statements, the firewall, and the controller • Having 1000 services is ok, but do you really know how many are being instantiated on each request? Thursday, May 23, 13
  25. How do I enforce that a comment is only editable

    by its owner *or* an “admin” user? Thursday, May 23, 13
  26. @weaverryan http://symfony.com/doc/current/cookbook/security/acl.html • Creates a new, generic table setup to

    that stores a relationship between an object, a user, and what that user can do with the object • Written to be highly efficient • And you should (probably) never use it! Thursday, May 23, 13
  27. @weaverryan http://symfony.com/doc/current/cookbook/security/acl.html • Creates a new, generic table setup to

    that stores a relationship between an object, a user, and what that user can do with the object • Written to be highly efficient •Bah! Seriously, don’t use it! Thursday, May 23, 13
  28. The relationship between the object and the user that defines

    access probably already exists Thursday, May 23, 13
  29. User A Comment Scenario2: The user is a super admin

    Roles: ROLE_SUPER_ADMIN YES! Thursday, May 23, 13
  30. Voters @weaverryan public function editAction($slug) { $blog = // ...

    $sc = $this->container ->get('security.context'); if (!$sc->isGranted('EDIT', $blog)) { throw new AccessDeniedException(); } } Thursday, May 23, 13
  31. Voters @weaverryan $sc->isGranted('EDIT', $blog) 1) Symfony iterates over “voters” and

    asks each of they know how to decide access for a Blog object and the “attribute” EDIT 2) A voter can deny, granted, or “abstain” from voting 3) And you can actually pass an arbitrary object to the voters Thursday, May 23, 13
  32. Core Voters @weaverryan Voter Votes if... Access if... RoleVoter ROLE_*

    attributes Does the user have this role? RoleHierarchyVoter ROLE_* attributes Does the user have a role by looking at role hierarchies AuthenticatedVoter IS_AUTHENTICATED_* How *trusted* is the user’s authentication (e.g. remember me)? Thursday, May 23, 13
  33. Core Voters @weaverryan Voter Votes if... Access if... RoleVoter ROLE_*

    attributes Does the user have this role? RoleHierarchyVoter ROLE_* attributes Does the user have a role by looking at role hierarchies AuthenticatedVoter IS_AUTHENTICATED_* How *trusted* is the user’s authentication (e.g. remember me)? None of these make use of an object if you pass one Thursday, May 23, 13
  34. Add your own Voter use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class CommentVoter

    implements VoterInterface { public function supportsAttribute($attribute) { return $attribute == 'EDIT'; } public function supportsClass($class) { $commentClass = 'Sf\WootBundle\Entity\Comment'; return $commentClass === $class || is_subclass_of($class, $commentClass); } } Thursday, May 23, 13
  35. Add your own Voter use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class CommentVoter

    implements VoterInterface { public function supportsAttribute($attribute) { return $attribute == 'EDIT'; } public function supportsClass($class) { $commentClass = 'Sf\WootBundle\Entity\Comment'; return $commentClass === $class || is_subclass_of($class, $commentClass); } } Invent some attribute(s) that you will ask on Thursday, May 23, 13
  36. Add your own Voter use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class CommentVoter

    implements VoterInterface { public function supportsAttribute($attribute) { return $attribute == 'EDIT'; } public function supportsClass($class) { $commentClass = 'Sf\WootBundle\Entity\Comment'; return $commentClass === $class || is_subclass_of($class, $commentClass); } } Decide which object(s) we will use when asking permission Thursday, May 23, 13
  37. Add your own Voter use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Doctrine\ORM\EntityManager;

    class CommentVoter implements VoterInterface { // ... public function vote(TokenInterface $token, $object, array $attributes) { // ... awesome business logic here! } } Comment object array containing EDIT Thursday, May 23, 13
  38. Add your own Voter public function vote(TokenInterface $token, $object, array

    $attributes) { // ... details: checking if we support this attribute, object, etc if (in_array('ROLE_SUPER_ADMIN', $token->getRoles())) { return self::ACCESS_GRANTED; } // get the user, force to null if we're anonymous $user = ($token->getUser() instanceof User) ? $token->getUser() : null; if ($object->getOwner() && $object->getOwner() == $user) { return self::ACCESS_GRANTED; } return VoterInterface::ACCESS_DENIED; } Thursday, May 23, 13
  39. @weaverryan • Use existing relationships to enforce authorization • Write

    simple business logic in a voter • Enforce in your controller at a very high level • Unit test them Voters $sc->isGranted('EDIT', $blog) Thursday, May 23, 13
  40. @weaverryan • Voters are loaded with the firewall (on every

    request), but you might not use a voter • Minimize the work it takes to instantiate them Performance Implications Thursday, May 23, 13
  41. Lightweight instantiation private $container; public function __construct(ContainerInterface $c) { $this->container

    = $c; } private function getHeavyService() { return $this->container->get('heavy_service'); } Thursday, May 23, 13
  42. public function editAction($id) { $favrtpgrmr = // ... $form =

    $this->createFormBuilder($favrtpgrmr) ->add('name', 'text') ->getForm() ; // form processing return $this->render( '...:edit.html.twig', array( 'form' => $form->createView(), )); } Thursday, May 23, 13
  43. Every form field has variables, which give you everything you

    need to render things Thursday, May 23, 13
  44. <div class="{{ form.name.vars.errors is empty ? '' : 'errors'}}"> <label

    for="{{ form.name.vars.id }}"> {{ form.name.vars.label }} </label> <input name="{{ form.name.vars.full_name }}" id="{{ form.name.vars.id }}" value="{{ form.name.vars.value }}" /> {% for error in form.name.vars.errors %} {{ error.message }} {% endfor %} </div> Thursday, May 23, 13
  45. {% block form_row %} <div class=" {{ errors is empty

    ? '' : 'errors' }} {{ required ? 'required' : '' }} "> {{ form_label(form) }} {{ form_errors(form) }} {{ form_widget(form) }} </div> {% endblock form_row %} Thursday, May 23, 13
  46. Get to know HttpKernel: all the cool kids are doing

    it @weaverryan 6 Thursday, May 23, 13
  47. HttpKernel @weaverryan Symfony’s component that converts a request into a

    response $response = $kernel->handle($request); At the heart of Symfony Framework Thursday, May 23, 13
  48. HttpKernel @weaverryan Symfony’s component that converts a request into a

    response $response = $kernel->handle($request); At the heart of Symfony Framework, Drupal, Zikula, EzPublisher Thursday, May 23, 13
  49. @weaverryan Welcome to Foo Break your site down into many

    small “fragments” Thursday, May 23, 13
  50. @weaverryan Welcome to Foo /content /side /menu Think of each

    fragment as having its own URL Thursday, May 23, 13
  51. @weaverryan Welcome to Foo /content /side /menu ... and even

    that each could be rendering in HTML, JSON, etc Thursday, May 23, 13
  52. If a page is many individual fragments, what combines these

    into a finished product? Thursday, May 23, 13
  53. Browser Cache App Inline ESI HInclude Request Request Response Request

    Combines the ESI responses I had no idea he (-->) just did that Thursday, May 23, 13
  54. Think about your application in small, simple fragments that can

    be rendered independently Thursday, May 23, 13
  55. What we teach in a training @weaverryan • Routing •

    Controllers • Twig • Assetic • Using Forms • Doctrine • etc • Namespaces • Creating services • Dependency Injection • OO best practices • Dividing logic into small, focused classes • Composer Thursday, May 23, 13
  56. @weaverryan • Namespaces • Creating services • Dependency Injection •

    OO best practices • Dividing logic into small, focused classes • Composer Thursday, May 23, 13
  57. Smaller and Smaller Pieces @weaverryan • Coupled Libraries can’t be

    used by others • Big libraries are hard to figure out Thursday, May 23, 13
  58. Smaller and Smaller Pieces @weaverryan • Can Symfony Bundles be

    broken into “bridge” libraries and used by Drupal? • Can Drupal modules be broken into libraries and used by all of PHP? Thursday, May 23, 13
  59. Example: GuzzleBundle @weaverryan • Adds web profiler information about how

    many HTTP requests were made • The web profiler will be available in Drupal8. Could the bundle be a bridge that works for both? Thursday, May 23, 13
  60. Too Many Pieces @weaverryan • Decoupling gives us the building

    block • But we still need a guide on how to make all the pieces sing together Thursday, May 23, 13
  61. Examples @weaverryan • Install FOSUserBundle, SonataAdminBundle and configure everything to

    quickly have generated admin with a login • REST API: Integrate FOSRestBundle, JSMSerializerBundle, NelmioApiDocBundle, FSCHateoasBundle, HautelookTemplatedUriBundle • Common Security Flows: OAuth, authentication against an API Thursday, May 23, 13
  62. 1) Remove Layers • Opt into your shortcuts • Teach

    people the “raw” and long way of doing things first • Teach people the principles Thursday, May 23, 13
  63. 3) Challenge Symfony • Documentation • Error Messages • Bundle

    README’s and Tutorials • Integration of many tools • How “Common” can things be done? • How easy is it to use a single component • Where can Frameworkisms be made optional or more transparent? Thursday, May 23, 13