SensioFrameworkExtraBundle

repository·master·Indexed 25 days ago

https://github.com/sensiolabs/sensioframeworkextrabundle

A legacy, unmaintained Symfony bundle used to configure controllers using annotations and attributes. It provides functionality for HTTP cache behavior (@Cache), security access control (@IsGranted, @Security), template specification (@Template), and parameter conversion via ParamConverter, including specialized converters like DateTimeParamConverter and DoctrineParamConverter.

Tokens
6.3K
Snippets
12
Records
32
Agent score
85%

What's inside SensioFrameworkExtraBundle

  1. Migration notice for SensioFrameworkExtraBundle

    master

    WARNING: SensioFrameworkExtraBundle is not maintained anymore.

    If you are starting a new project or maintaining an existing one, please migrate to native PHP attribute support as provided by Symfony core. For full support and modern features, it is recommended to use Symfony 6.2 or higher.

  2. Register a custom ParamConverter

    master

    Custom converters can be registered in the Symfony service container. If you are using service auto-registration and autoconfiguration, your converter will be automatically detected and added to the stack with a priority of 0.

    To customize registration, you can use service tags to specify:

    • Priority: An integer determining the order in the stack.
    • Name: A specific name for the converter (used via the converter attribute in the annotation).

    Important Notes:

    • If you need to inject services or additional arguments into your converter, ensure its priority is not higher than 1; otherwise, the service may not load correctly.
    • To explicitly disable registration by priority, set priority="false" in your tag definition.
  3. Replace @Method annotation with Route methods option

    master

    The @Method annotation from SensioFrameworkExtraBundle has been removed. You should now use the methods option within the Symfony @Route annotation to restrict allowed HTTP methods.

    You can use either traditional DocBlock annotations or PHP 8 attributes.

    // Using Annotations
    use Symfony\Component\Routing\Annotation\Route;
    
    class DefaultController extends Controller
    {
        /**
         * @Route("/show/{id}", methods={"GET", "HEAD"})
         */
        public function show($id)
        {
            // ...
        }
    }
    
    // Using PHP 8 Attributes
    use Symfony\Component\Routing\Annotation\Route;
    
    class DefaultController extends Controller
    {
        #[Route('/show/{id}', methods: ['GET', 'HEAD'])]
        public function show($id)
        {
            // ...
        }
    }
  4. Configure HTTP Validation with lastModified and Etag

    master

    The lastModified and etag attributes manage HTTP validation headers.

    • lastModified: Adds a Last-Modified header.
    • etag: Adds an Etag header (the provided expression is hashed using sha256).

    Important: When using these attributes, if the client's cache is still valid, the framework automatically returns a 304 Not Modified response and the controller method code is not executed.

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
    
    #[Cache(lastModified: 'post.getUpdatedAt()', etag: "'Post' ~ post.getId() ~ post.getUpdatedAt().getTimestamp()")]
    public function index(Post $post)
    {
        // This code is skipped if a 304 response is triggered
    }
  5. Use the Doctrine ORM Converter to fetch entities

    master

    The doctrine.orm converter (or the @Entity shortcut) fetches Doctrine entities from the database based on route parameters.

    Automatic Fetching

    If your route wildcards match entity properties, the converter works automatically:

    • If {id} is in the route, it uses find() by primary key.
    • It attempts a findOneBy() using all route wildcards that match entity properties.

    Fetch via Expression

    If automatic fetching is insufficient, use the expr option with the @Entity annotation to call a specific repository method.

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
    
    /**
     * @Route("/blog/{post_id}")
     * @Entity("post", expr="repository.find(post_id)")
     */
    public function show(Post $post)
    {
    }
  6. Migrate @Route annotations to Symfony core

    master

    Since version 5.2, routing annotations from SensioFrameworkExtraBundle are deprecated because routing is now a core Symfony feature. To update your application, change the namespace of the Route annotation from Sensio\Bundle\FrameworkExtraBundle\Configuration\Route to Symfony\Component\Routing\Annotation\Route.

    Note that Symfony's @Route annotation no longer supports the service option. In modern Symfony, controllers are services by default using their fully-qualified class names, making the service option obsolete.

    // Before
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    
    // After
    use Symfony\Component\Routing\Annotation\Route;
    
    class DefaultController extends Controller
    {
        /**
         * @Route("/")
         */
        public function index()
        {
            // ...
        }
    }
  7. Configure HTTP Expiration with @Cache

    master

    Use the #[Cache] attribute (or @Cache annotation) to define HTTP expiration headers. You can apply it to a specific controller method or to an entire controller class to set default caching for all its actions. If both are present, the method-level configuration overrides the class-level configuration.

    The expires attribute accepts any valid date string understood by PHP's strtotime() function.

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
    
    // Applied to a method
    #[Cache(expires: 'tomorrow', public: true)]
    public function index()
    {
    }
    
    // Applied to a class (applies to all actions in the controller)
    #[Cache(expires: 'tomorrow', public: true)]
    class BlogController extends Controller
    {
    }
  8. Use the @ParamConverter annotation to convert request parameters to objects

    master

    The @ParamConverter annotation (or #[ParamConverter] attribute) allows you to convert request parameters (like route placeholders) into objects. These objects are then automatically injected into your controller method arguments.

    If the converter cannot find the object, a 404 response is generated. If the method argument is type-hinted, you can often omit the annotation entirely for automatic conversion.

    use Symfony\Component\Routing\Annotation\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
    
    /**
     * @Route("/blog/{id}")
     * @ParamConverter("post", class="SensioBlogBundle:Post")
     */
    public function show(Post $post)
    {
    }
  9. Configure ParamConverter auto-conversion and disabled converters

    master

    You can globally control the behavior of request converters in your Symfony configuration. Use auto_convert: false to disable the automatic conversion of type-hinted method arguments, and use the disable key to explicitly turn off specific converters by name (e.g., doctrine.orm or datetime).

    # config/packages/sensio_framework_extra.yaml
    sensio_framework_extra:
        request:
            converters: true
            auto_convert: false
            disable: ['doctrine.orm', 'datetime']
  10. Restrict controller access with @Security

    master

    The Security annotation (or attribute) provides more flexibility than IsGranted by allowing complex logic via an expression string. This expression can use any function available in Symfony's access_control configuration, including the is_granted() function.

    Available variables in the expression:

    • token: The current security token.
    • user: The current user object.
    • request: The request instance.
    • roles: The user roles.
    • All request attributes (e.g., route parameters like post).

    Key options:

    • statusCode: Allows throwing an HttpException with a specific code instead of the default AccessDeniedException.
    • message: Customizes the exception message.
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
    
    class PostController extends Controller
    {
        #[Security("is_granted('ROLE_ADMIN') and is_granted('POST_SHOW', post)", statusCode: 404, message: 'Resource not found.')]
        public function show(Post $post)
        {
            // ...
        }
    }
  11. Use the @Template annotation to associate a controller with a view

    master

    The @Template annotation allows a controller action to return an array of parameters instead of a Response object. The bundle then automatically renders the specified template using those parameters.

    Key behaviors:

    • If the action returns a Response object, the @Template annotation is ignored.
    • To enable template streaming, set isStreamable=true.
    • If the template path follows the convention of [BundleName]/[controller_name]/[action_name].html.twig, you can omit the template path value.
    • Sub-namespaces in controller names are converted to underscores (e.g., UserProfileController::showDetails() resolves to @SensioBlog/user_profile/show_details.html.twig).