项目作者: dunglas

项目描述 :
Symfony controllers, redesigned
高级语言: PHP
项目地址: git://github.com/dunglas/DunglasActionBundle.git
创建时间: 2016-01-20T17:53:00Z
项目社区:https://github.com/dunglas/DunglasActionBundle

开源协议:MIT License

下载


DunglasActionBundle: Symfony controllers, redesigned

Build Status
Build status
SensioLabsInsight
Scrutinizer Code Quality
StyleCI

This bundle is a replacement for the controller system of the Symfony framework and for its command system.

It is as convenient as the original but doesn’t suffer from its drawbacks:

DunglasActionBundle allows to create reusable, framework agnostic (especially when used with the PSR-7 bridge)
and easy to unit test classes.

See https://github.com/symfony/symfony/pull/16863#issuecomment-162221353 for the history behind this bundle.

Note for Symfony >=3.3 users

If you use Symfony at version 3.3 or superior, you do not need to use this bundle as all the features were ported
in Symfony. You can learn more about it in the Symfony blog
or in the Symfony documentation.

Installation

Use Composer to install this bundle:

  1. composer require dunglas/action-bundle

Add the bundle in your application kernel:

  1. // app/AppKernel.php
  2. public function registerBundles()
  3. {
  4. return [
  5. // ...
  6. new Dunglas\ActionBundle\DunglasActionBundle(),
  7. // ...
  8. ];
  9. }

Optional: to use the @Route annotation add the following lines in app/config/routing.yml:

  1. app:
  2. resource: '@AppBundle/Action/' # Use @AppBundle/Controller/ if you prefer
  3. type: 'annotation'

If you don’t want to use annotations but prefer raw YAML, use the following syntax:

  1. foo:
  2. path: /foo/{bar}
  3. defaults: { _controller: 'AppBundle\Action\Homepage' } # this is the name of the autoregistered service corresponding to this action

Usage

  1. Create an invokable class
    in the Action\ namespace of your bundle:
  1. // src/AppBundle/Action/MyAction.php
  2. namespace AppBundle\Action;
  3. use Symfony\Component\Routing\Annotation\Route;
  4. use Symfony\Component\Routing\RouterInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. class Homepage
  9. {
  10. private $router;
  11. private $twig;
  12. /**
  13. * The action is automatically registered as a service and dependencies are autowired.
  14. * Typehint any service you need, it will be automatically injected.
  15. */
  16. public function __construct(RouterInterface $router, \Twig_Environment $twig)
  17. {
  18. $this->router = $router;
  19. $this->twig = $twig;
  20. }
  21. /**
  22. * @Route("/myaction", name="my_action")
  23. *
  24. * Using annotations is not mandatory, XML and YAML configuration files can be used instead.
  25. * If you want to decouple your actions from the framework, don't use annotations.
  26. */
  27. public function __invoke(Request $request)
  28. {
  29. if (!$request->isMethod('GET')) {
  30. // Redirect to the current URL using the the GET method if it's not the current one
  31. return new RedirectResponse($this->router->generateUrl('my_action'), 301);
  32. }
  33. return new Response($this->twig->render('mytemplate.html.twig'));
  34. }
  35. }

Alternatively, you can create a typical Symfony controller class with several *Action methods in the Controller directory
of your bundle, it will be autowired the same way.

There is no step 2! You’re already done.

All classes inside Action/ and Controller/ directories of your project bundles are automatically registered as services.
By convention, the service name is the Fully Qualified Name of the class.

For instance, the class in the example is automatically registered with the name AppBundle\Action\Homepage.

There are other classes/tags supported:

Class Name Tag automatically added Directory
Command console.command Command
EventSubscriberInterface kernel.event_subscriber EventSubscriber
Twig_ExtensionInterface twig.extension Twig

Thanks to the autowiring feature of the Dependency Injection
Component, you can just typehint dependencies you need in the constructor, they will be automatically initialized and injected.

Service definition can easily be customized by explicitly defining a service named according to the same convention:

  1. # app/config/services.yml
  2. services:
  3. # This is a custom service definition
  4. 'AppBundle\Action\MyAction':
  5. arguments: [ '@router', '@twig' ]
  6. 'AppBundle\Command\MyCommand':
  7. arguments: [ '@router', '@twig' ]
  8. tags:
  9. - { name: console.command }
  10. # With Symfony < 3.3
  11. 'AppBundle\EventSubscriber\MySubscriber':
  12. class: 'AppBundle\EventSubscriber\MySubscriber'
  13. tags:
  14. - { name: kernel.event_subscriber }

This bundle also hooks into the Routing Component (if it is available): when the @Route annotation is used as in the example,
the route is automatically registered: the bundle guesses the service to map with the path specified in the annotation.

Dive into the TestBundle to discover more examples such as using custom services with ease
(no configuration at all) or classes containing several actions.

Using the Symfony Micro Framework

You might be interested to see how this bundle can be used together with the Symfony “Micro” framework.

Here we go:

  1. // MyMicroKernel.php
  2. use AppBundle\Action\Homepage;
  3. use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
  4. use Symfony\Component\Config\Loader\LoaderInterface;
  5. use Symfony\Component\DependencyInjection\ContainerBuilder;
  6. use Symfony\Component\HttpKernel\Kernel;
  7. use Symfony\Component\Routing\RouteCollectionBuilder;
  8. final class MyMicroKernel extends Kernel
  9. {
  10. use MicroKernelTrait;
  11. public function registerBundles()
  12. {
  13. return [
  14. new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
  15. new Dunglas\ActionBundle\DunglasActionBundle(),
  16. new AppBundle\AppBundle(),
  17. ];
  18. }
  19. protected function configureRoutes(RouteCollectionBuilder $routes)
  20. {
  21. // Specify explicitly the controller
  22. $routes->add('/', Homepage::class, 'my_route');
  23. // Alternatively, use @Route annotations
  24. // $routes->import('@AppBundle/Action/', '/', 'annotation');
  25. }
  26. protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
  27. {
  28. $c->loadFromExtension('framework', ['secret' => 'MySecretKey']);
  29. }
  30. }

Amazing isn’t it?

Want to see a more advanced example? Checkout our test micro kernel.

Configuration

  1. # app/config/config.yml
  2. dunglas_action:
  3. directories: # List of directories relative to the kernel root directory containing classes to auto-register.
  4. - '../src/*Bundle/{Controller,Action,Command,EventSubscriber}'
  5. # This one is not registered by default
  6. - '../src/*Bundle/My/Uncommon/Directory'
  7. tags:
  8. 'Symfony\Component\Console\Command\Command': console.command
  9. 'Symfony\Component\EventDispatcher\EventSubscriberInterface': kernel.event_subscriber
  10. 'My\Custom\Interface\To\Auto\Tag':
  11. - 'my_custom.tag'
  12. - [ 'my_custom.tag_with_attributes', { attribute: 'value' } ]

Credits

This bundle is brought to you by Kévin Dunglas and awesome contributors.
Sponsored by Les-Tilleuls.coop.