Kévin Dunglas
Contributed by Kévin Dunglas in #28875

The WebLink component introduced in Symfony 3.3 provides tools to manage the Link HTTP header needed for Web Linking when using HTTP/2 Server Push as well as Resource Hints. In practice, it can improve the performance of your web apps dramatically.

In order to simplify its usage, in Symfony 4.2 we've added a new addLink() shortcut to AbstractController. For example, this is how you can preload a CSS file (to send it before the browser requests it):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/Controller/BlogController.php
namespace App\Controller;

use Fig\Link\GenericLinkProvider;
use Fig\Link\Link;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class BlogController extends AbstractController
{
    public function index(Request $request)
    {
        // BEFORE
        $linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
        $request->attributes->set('_links', $linkProvider->withLink(new Link('preload', '/app.css')));

        // AFTER
        $this->addLink($request, new Link('preload', '/app.css'));

        return $this->render('...');
    }
}
Published in #Living on the edge