All Projects → dunglas → Dunglasactionbundle

dunglas / Dunglasactionbundle

Licence: mit
Symfony controllers, redesigned

Projects that are alternatives of or similar to Dunglasactionbundle

Auditor Bundle
Doctrine audits logs made easy.
Stars: ✭ 221 (-17.84%)
Mutual labels:  symfony, symfony-bundle
Framework Bundle
The FrameworkBundle defines the main framework configuration, from sessions and translations to forms, validation, routing and more.
Stars: ✭ 3,056 (+1036.06%)
Mutual labels:  symfony, symfony-bundle
Victoire
Fullstack Symfony CMS: The perfect mix between a framework and a CMS
Stars: ✭ 227 (-15.61%)
Mutual labels:  symfony, symfony-bundle
Monolog Bundle
Symfony Monolog Bundle
Stars: ✭ 2,532 (+841.26%)
Mutual labels:  symfony, symfony-bundle
Csaguzzlebundle
A bundle integrating Guzzle >=4.0 in Symfony
Stars: ✭ 248 (-7.81%)
Mutual labels:  symfony, symfony-bundle
Sonataintlbundle
Symfony SonataIntlBundle
Stars: ✭ 212 (-21.19%)
Mutual labels:  symfony, symfony-bundle
Fmelfinderbundle
📁 ElFinderBundle provides ElFinder integration with TinyMCE, CKEditor, Summernote editors
Stars: ✭ 231 (-14.13%)
Mutual labels:  symfony, symfony-bundle
Alice
Expressive fixtures generator
Stars: ✭ 2,289 (+750.93%)
Mutual labels:  symfony, symfony-bundle
Fosrestbundle
This Bundle provides various tools to rapidly develop RESTful API's with Symfony
Stars: ✭ 2,683 (+897.4%)
Mutual labels:  symfony, symfony-bundle
Enqueue Bundle
[READ-ONLY] Message queue bundle for Symfony. RabbitMQ, Amazon SQS, Redis, Service bus, Async events, RPC over MQ and a lot more
Stars: ✭ 233 (-13.38%)
Mutual labels:  symfony, symfony-bundle
Liiphellobundle
[DEPRECATED] Alternative Hello World Bundle for Symfony2 using several FriendsOfSymfony Bundles
Stars: ✭ 206 (-23.42%)
Mutual labels:  symfony, symfony-bundle
Controllerextrabundle
Controller extra Bundle for Symfony2
Stars: ✭ 157 (-41.64%)
Mutual labels:  controller, symfony
Rich Model Forms Bundle
Provides additional data mappers that ease the use of the Symfony Form component with rich models.
Stars: ✭ 198 (-26.39%)
Mutual labels:  symfony, symfony-bundle
Schedule Bundle
Schedule Cron jobs (commands/callbacks/bash scripts) within your Symfony application.
Stars: ✭ 216 (-19.7%)
Mutual labels:  symfony, symfony-bundle
Gifexceptionbundle
😛 The GhostBuster of your exception page!
Stars: ✭ 197 (-26.77%)
Mutual labels:  symfony, symfony-bundle
Alicedatafixtures
Nelmio Alice extension to persist the loaded fixtures.
Stars: ✭ 228 (-15.24%)
Mutual labels:  symfony, symfony-bundle
Webauthn Framework
FIDO-U2F / FIDO2 / Webauthn Framework
Stars: ✭ 182 (-32.34%)
Mutual labels:  symfony, symfony-bundle
Mercure Bundle
The MercureBundle allows to easily push updates to web browsers and other HTTP clients in the Symfony full-stack framework, using the Mercure protocol.
Stars: ✭ 195 (-27.51%)
Mutual labels:  symfony, symfony-bundle
Easyadminextensionbundle
Provides some additional features to EasyAdminBundle for Symfony
Stars: ✭ 232 (-13.75%)
Mutual labels:  symfony, symfony-bundle
Lexikmaintenancebundle
This Symfony2 bundle allows you to place your website in maintenance mode by calling two commands in your console. A page with status code 503 appears to users, it is possible to authorize certain ips addresses stored in your configuration.
Stars: ✭ 253 (-5.95%)
Mutual labels:  symfony, symfony-bundle

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:

  • Action and console classes are automatically registered as services by the bundle
  • Their dependencies are explicitly injected in the constructor (no more ugly access to the service container) using the autowiring feature of the Dependency Injection Component
  • Only one action per class thanks to the __invoke() method (but you're still free to create classes with more than 1 action if you want to)
  • 100% compatible with common libraries and bundles including SensioFrameworkExtraBundle annotations

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:

composer require dunglas/action-bundle

Add the bundle in your application kernel:

// app/AppKernel.php

public function registerBundles()
{
    return [
        // ...
        new Dunglas\ActionBundle\DunglasActionBundle(),
        // ...
    ];
}

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

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

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

foo:
    path:      /foo/{bar}
    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:
// src/AppBundle/Action/MyAction.php

namespace AppBundle\Action;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class Homepage
{
    private $router;
    private $twig;

    /**
     * The action is automatically registered as a service and dependencies are autowired.
     * Typehint any service you need, it will be automatically injected.
     */
    public function __construct(RouterInterface $router, \Twig_Environment $twig)
    {
        $this->router = $router;
        $this->twig = $twig;
    }

    /**
     * @Route("/myaction", name="my_action")
     *
     * Using annotations is not mandatory, XML and YAML configuration files can be used instead.
     * If you want to decouple your actions from the framework, don't use annotations.
     */
    public function __invoke(Request $request)
    {
        if (!$request->isMethod('GET')) {
            // Redirect to the current URL using the the GET method if it's not the current one
            return new RedirectResponse($this->router->generateUrl('my_action'), 301);
        }

        return new Response($this->twig->render('mytemplate.html.twig'));
    }
}

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:

# app/config/services.yml

services:
    # This is a custom service definition
    'AppBundle\Action\MyAction':
        arguments: [ '@router', '@twig' ]

    'AppBundle\Command\MyCommand':
        arguments: [ '@router', '@twig' ]
        tags:
            - { name: console.command }

    # With Symfony < 3.3
    'AppBundle\EventSubscriber\MySubscriber':
        class: 'AppBundle\EventSubscriber\MySubscriber'
        tags:
            - { 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:

// MyMicroKernel.php

use AppBundle\Action\Homepage;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;

final class MyMicroKernel extends Kernel
{
    use MicroKernelTrait;

    public function registerBundles()
    {
        return [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Dunglas\ActionBundle\DunglasActionBundle(),
            new AppBundle\AppBundle(),
        ];
    }

    protected function configureRoutes(RouteCollectionBuilder $routes)
    {
        // Specify explicitly the controller
        $routes->add('/', Homepage::class, 'my_route');
        // Alternatively, use @Route annotations
        // $routes->import('@AppBundle/Action/', '/', 'annotation');
    }

    protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
    {
        $c->loadFromExtension('framework', ['secret' => 'MySecretKey']);
    }
}

Amazing isn't it?

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

Configuration

# app/config/config.yml

dunglas_action:
    directories: # List of directories relative to the kernel root directory containing classes to auto-register.
        - '../src/*Bundle/{Controller,Action,Command,EventSubscriber}'
        # This one is not registered by default
        - '../src/*Bundle/My/Uncommon/Directory'
    tags:
        'Symfony\Component\Console\Command\Command': console.command
        'Symfony\Component\EventDispatcher\EventSubscriberInterface': kernel.event_subscriber
        'My\Custom\Interface\To\Auto\Tag':
            - 'my_custom.tag'
            - [ '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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].