Share
Embed
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
Transcript
169 slides
-
The Traveling Symfony Circus by your friend: Ryan Weaver @weaverryan
Thursday, May 23, 13 -
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 -
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 -
Intro Symphony: So popular, recruiters misspell it less! (the good
news) Thursday, May 23, 13 -
Intro Reasons to be happy as a Symfony Developer (the
good news) Thursday, May 23, 13 -
Cooperation Composer Other Libraries Drupal Aura Packages Symfony Components Symfony
Framework AWS SDK Some random library you wrote! Thursday, May 23, 13 -
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 -
Symfony2: Moving like a bat out of heck @weaverryan B
Thursday, May 23, 13 -
Symfony components are used in an increasing number of open
source projects Thursday, May 23, 13 -
Symfony Components @weaverryan • Drupal • phpBB • eZ publish
• Magento (Twig) • Joomla (Yaml) • Flow3 • Laravel • Zikula • Propel • Behat • Foxycart Thursday, May 23, 13 -
Drupal Hug a Drupaler today http://images.free-extras.com/pics/k/kitten_hug-1451.jpg ... and tell them
about Composer ... Thursday, May 23, 13 -
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 -
10 Lessons from touring like a Symfony Country Music Star
http://www.weavercountry.com/ Thursday, May 23, 13 -
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 -
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 -
#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 -
#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 -
use Symfony\Component\HttpFoundation\Response; $templating = $this->container ->get('templating'); $html = $templating->render( 'DemoBundle:Default:index.html.twig'
); return new Response($html); w/o auto-Response creation Thursday, May 23, 13 -
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 -
Sf\WootBundle\Controller\FooController::indexAction SfWootBundle:Foo:index Use Shortcuts ... but know first that you
don’t need to _controller: Thursday, May 23, 13 -
Yell from a Mountain: The Symfony Framework is only 2
things Thursday, May 23, 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 -
2) A bunch of optional objects to help you build
that page Thursday, May 23, 13 -
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 -
The smaller we make Symfony, the faster a user will
understand it Thursday, May 23, 13 -
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 -
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 -
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 -
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 -
Simplify first, add in things in later if you need
them Thursday, May 23, 13 -
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 -
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 -
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 -
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 -
How do I enforce that a comment is only editable
by its owner *or* an “admin” user? Thursday, May 23, 13 -
@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 -
@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 -
The relationship between the object and the user that defines
access probably already exists Thursday, May 23, 13 -
User A Comment Can this user edit this comment? ???
Thursday, May 23, 13 -
User A Comment Scenario1: The user wrote the comment Comment->getUser():
User A YES! Thursday, May 23, 13 -
User A Comment Scenario2: The user is a super admin
Roles: ROLE_SUPER_ADMIN YES! Thursday, May 23, 13 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
@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 -
@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 -
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 -
Get Wild and Crazy and Simple with Form Variables @weaverryan
5 Thursday, May 23, 13 -
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 -
<form action="..."> {{ form_errors(form) }} {{ form_row(form.name) }} {{ form_rest(form)
}} <input type="submit" /> </form> Thursday, May 23, 13 -
Every form field has variables, which give you everything you
need to render things Thursday, May 23, 13 -
Most form_* functions take an array of “variables” as an
argument Thursday, May 23, 13 -
{{ form_row(form.name, { 'label': 'First Name', 'value': 'Fabien', 'label_attr': {
'class': 'first-name' } }) }} Thursday, May 23, 13 -
Or render the field (or part of) all by yourself:
Thursday, May 23, 13 -
<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 -
{% 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 -
{% block form_row %} {{ dump() }} {% endblock form_row
%} Thursday, May 23, 13 -
Get to know HttpKernel: all the cool kids are doing
it @weaverryan 6 Thursday, May 23, 13 -
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 -
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 -
Learn a framework by building a simple framework on great
tools Thursday, May 23, 13 -
@weaverryan Welcome to Foo Break your site down into many
small “fragments” Thursday, May 23, 13 -
{{ render(controller('ABundle:Default:menu')) }} {{ render(controller('ABundle:Default:article')) }} {{ render(controller('ABundle:Default:sidebar')) }} Each
fragment is its own controller - can be rendered independently Thursday, May 23, 13 -
@weaverryan Welcome to Foo /content /side /menu Think of each
fragment as having its own URL Thursday, May 23, 13 -
@weaverryan Welcome to Foo /content /side /menu ... and even
that each could be rendering in HTML, JSON, etc Thursday, May 23, 13 -
If a page is many individual fragments, what combines these
into a finished product? Thursday, May 23, 13 -
Browser Cache App Inline ESI HInclude Request Request Response Request
Thursday, May 23, 13 -
{{ render_esi(controller('ABundle:Default:menu')) }} ESI <esi:include src="http://localhost/app_dev.php/ _fragment?_path=_format%3Dhtml %26_controller%3DABundle%253ADefault %253Amenu" />
Cache Layer makes another request for only the fragment Thursday, May 23, 13 -
Browser Cache App Inline ESI HInclude Request Request Response Request
Thursday, May 23, 13 -
{{ render_hinclude(controller('ABundle:Default:menu')) }} HInclude <hx:include src="http://localhost/app_dev.php/ _fragment?_path=_format%3Dhtml %26_controller%3DABundle%253ADefault %253Amenu&_hash=XqfhFd6cev75eO5yIPIBdQz PxEw%3D"
></hx:include> Browser makes another request for only the fragment Thursday, May 23, 13 -
Browser Cache App Inline ESI HInclude Request Request Response Request
Thursday, May 23, 13 -
... except that you can’t see what’s happening at the
cache layer Thursday, May 23, 13 -
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 -
X-Symfony-Cache @weaverryan ... you can also copy each URL into
your browser Thursday, May 23, 13 -
Think about your application in small, simple fragments that can
be rendered independently Thursday, May 23, 13 -
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 -
@weaverryan • Namespaces • Creating services • Dependency Injection •
OO best practices • Dividing logic into small, focused classes • Composer Thursday, May 23, 13 -
Smaller and Smaller Pieces @weaverryan • Coupled Libraries can’t be
used by others • Big libraries are hard to figure out Thursday, May 23, 13 -
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 -
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 -
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 -
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 -
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 -
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 -
... and we <3 you! Ryan Weaver @weaverryan https://joind.in/8668 Ryan
Weaver @weaverryan Thursday, May 23, 13