If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeWe have this problem: we know the cause, but not the solution. Basically, we're reading this ?isMac=false
from both our master request - where it's being read correctly - and our sub-request - where it is not. That's because those are two separate request objects. And, in general, we should avoid reading request info from a sub-request... because we're not working with the real Request
object!
But accidentally trying to use data from the real request in a sub-request was so easy to do! Inside of PartialController
, we simply added an $isMac
argument like we do everywhere else. This argument was passed thanks to our custom IsMacArgumentValueResolver
: this is executed on every request. But the second time it's called, the request is not the real request.
Here's the plan: I want to prevent any controllers that are being called on a sub-request from being able to have an $isMac
argument. If we try, I want an exception to be thrown.
By the way, it is actually possible to use the RequestStack
from anywhere to get the "master" request: it has a getMasterRequest()
method. But! If you're using HTTP caching with edge side includes, this will break. The solution we're going to show is the proper one... and a lot more fun to implement for a deep dive.
The easiest way to do this would be to go to our argument value resolver, find out if this is a sub-request and return false
from supports()
in that case. But... there's not a great way to figure out if this is the master or sub-request from here. That's mostly a superpower of event listeners.
So, let's use a trick: let's allow the listener to figure out whether or not we're using a Mac. And then, it can pass that information over to our argument value resolver.
Inside the subscriber, create a new private function called isMac()
: it will take in the Request
object from HttpFoundation
and return a boolean. For the logic, copy everything from inside of resolve()
, remove it and paste it here. Change both of the yield
calls to return
.
... lines 1 - 10 | |
class UserAgentSubscriber implements EventSubscriberInterface | |
{ | |
... lines 13 - 46 | |
private function isMac(Request $request): bool | |
{ | |
if ($request->query->has('mac')) { | |
return $request->query->getBoolean('mac'); | |
} | |
$userAgent = $request->headers->get('User-Agent'); | |
return stripos($userAgent, 'Mac') !== false; | |
} | |
} |
Perfect! We now have a function to tell us if we're using a Mac. Now, up in onKernelRequest()
, if this is a sub-request, the method returns immediately. But if it's a master request, let's work some magic. How can we pass the isMac
value to the argument value resolver? We could create and call a setter on it. Or, we could put that into the request attributes! I mean, that is the proper place for information about the request that is specific to your app. This is a perfect example!
Do it with $request->attributes->set()
and create a key called _isMac
set to $this->isMac($request)
.
... lines 1 - 19 | |
public function onKernelRequest(RequestEvent $event) | |
{ | |
... lines 22 - 38 | |
$request->attributes->set('_isMac', $this->isMac($request)); | |
} | |
... lines 41 - 60 |
We're calling it _isMac
because if we called it just isMac
, we wouldn't even need the argument value resolver! It would immediately be possible to have an $isMac
argument without an error. So... I want to try to do this, kind of, the hard way.
Move over to the IsMacArgumentValueResolver
. Here, we're going to read that attribute, which will only exist on the master request. Inside of supports()
, add && $request->attributes->has('_isMac')
. Supports will now return false for a sub request.
... lines 1 - 8 | |
class IsMacArgumentValueResolver implements ArgumentValueResolverInterface | |
{ | |
public function supports(Request $request, ArgumentMetadata $argument) | |
{ | |
return $argument->getName() === 'isMac' && $request->attributes->has('_isMac'); | |
} | |
... lines 15 - 19 | |
} |
In resolve
, yield $request->attributes->get('_isMac')
... lines 1 - 15 | |
public function resolve(Request $request, ArgumentMetadata $argument) | |
{ | |
yield $request->attributes->get('_isMac'); | |
} | |
... lines 20 - 21 |
That's it! Does it work? In your browser, first open an article show page in a new tab. Here, it works: you can see it on the web debug toolbar: we're dumping the $isMac
argument in the controller. This proves that we haven't broken the master request.
But now, refresh the homepage. It explodes!
An exception has been throwing during the rendering of a template: could not resolve
$isMac
argument.
And you can see that it hits this on our {{ render(controller()) }}
line. This is exactly what I wanted: I can no longer accidentally use this argument: it only works on the master request.
Of course... the question now is: how do we fix this? What if I really do need to know the $isMac
value from inside a sub request? I mean, that's a valid thing to want to know!
The solution is to pass the isMac
value from your main request to your sub request object. In a Twig template, you can do this by passing an optional second array argument. Pass isMac
set to isMac
.
... lines 1 - 45 | |
<div class="col-sm-12 col-md-4 text-center"> | |
... lines 47 - 57 | |
{{ render(controller('App\\Controller\\PartialController::trendingQuotes', { | |
isMac: isMac | |
})) }} | |
</div> | |
... lines 62 - 65 |
Before we chat about this, let's see if it works. Refresh and... it does! Woh! Let... me explain. The second argument to controller()
is an array of values that you want to pass to the attributes of the sub-request object. Why does that work? Well, for the sub-request, the $isMac
controller argument is actually not being passed to us thanks to the IsMacArgumentValueResolver
. Nope! It works simply because we put an isMac
key into the request attributes... and anything inside request attributes are allowed as controller arguments.
It feels like the second argument to the Twig controller()
function is just an "array of variables to pass to the controller". And while that's essentially true, it really works thanks to the request attributes.
Back on the homepage, because we still have the ?mac=false
query parameter, the message is not rendered in both places. If we remove that query parameter... yes! It's displayed consistently.
As an added benefit, this was of passing variables from the master to the sub-request works perfectly with edge side includes and HTTP caching. Open the profiler, go to the Performance tab, find the sub request and click to go into its profiler. See this internal URL up here? If we were truly using edge side includes, this URL would be a real URL used by your HTTP cache to fetch this fragment and the URL would have an extra isMac=true
or false
query parameter. For ESI, request attributes becomes part of the URL. And since the URL operates as the cache key for HTTP caching, this means that you would have a separate cache for the version of your trending quotes with the "isMac" message and without. That's perfect.
Close up that tab. Now that we know that this array become request attributes, another solution would be to pass _isMac
. If we did that, it would be used by our argument value resolver. UserAgentSubscriber
would still do nothing because it's a sub request... but the _isMac
attribute would be there and the IsMacArgumentValueResolver
would make the isMac
argument available to PartialController
. Two different ways to do the exact same thing... and both are super nerdy.
Ok friends! Wow! That was fun! I hope you enjoyed this deep dive into the heart of Symfony's HttpKernel as much as I did. If you have still have questions or want to deep-dive into a different part of Symfony, let us know in the comments.
Happy hacking! And we'll see ya next time.
Hey Authoritas
They main reason of this tutorial is for you to know what's really happening under the hood, and how things works so you get more comfortable when working with Symfony. It's like unveiling the Symfony magic :)
Cheers!
Wow! This tutorial was a great one. I wonder how you crank out these high quality tutorials and doing so much for the community in general as well as coding and maintaining symfony. I mean - you must have so much work to do - that I feel kinda bad for saying: "I barely can't wait for the next deep dive tutorial no matter what area of symfony will be covered!"
Hey Michael B.!
Haha - thank you for the kind words ❤️. I do stay pretty busy ;). But also, many other people do the less-obvious work around Symfony... while I get to run around doing the *more* obvious stuff. Anyways, these types of messages make my day - thanks for dropping it!
Cheers!
I feel powerful after watching this tutorial. However I feel like I need to know more about containers, sessions and their life cycle. Is there an upcoming Deep dive tutorial about that soon?
Hey FaresG
Yeah! This tutorial is awesome. At this point, we're not working on another deep-dive tutorial but we already have one in mind. It would be about the Container
Cheers!
Thank's a lot for this tutorial !!!! Exactly what I dreamed for ! Ryan you are my hero ! What's about the Security component ? And the containers ?
Hey Matheo D.
We're glad to hear that you liked this tutorial :)
At the moment we don't have a "deep-dive" Security tutorial but we still cover that topic in this course: https://symfonycasts.com/sc...
The next "deep-dive" course would be about the container but I know a release date yet. What I can offer you is this tutorial https://symfonycasts.com/sc... it is old but the core concepts haven't change
Cheers!
// composer.json
{
"require": {
"php": ">=8.1",
"ext-iconv": "*",
"antishov/doctrine-extensions-bundle": "^1.4", // v1.4.3
"aws/aws-sdk-php": "^3.87", // 3.133.20
"composer/package-versions-deprecated": "^1.11", // 1.11.99
"doctrine/annotations": "^1.0", // 1.12.1
"doctrine/doctrine-bundle": "^2.0", // 2.2.3
"doctrine/doctrine-migrations-bundle": "^1.3|^2.0", // 2.2.2
"doctrine/orm": "^2.5.11", // 2.8.2
"easycorp/easy-log-handler": "^1.0", // v1.0.9
"http-interop/http-factory-guzzle": "^1.0", // 1.0.0
"knplabs/knp-markdown-bundle": "^1.7", // 1.9.0
"knplabs/knp-paginator-bundle": "^5.0", // v5.4.2
"knplabs/knp-snappy-bundle": "^1.6", // v1.7.1
"knplabs/knp-time-bundle": "^1.8", // v1.16.0
"league/flysystem-aws-s3-v3": "^1.0", // 1.0.24
"league/flysystem-cached-adapter": "^1.0", // 1.0.9
"league/html-to-markdown": "^4.8", // 4.9.1
"liip/imagine-bundle": "^2.1", // 2.5.0
"oneup/flysystem-bundle": "^3.0", // 3.7.0
"php-http/guzzle6-adapter": "^2.0", // v2.0.2
"phpdocumentor/reflection-docblock": "^5.2", // 5.2.2
"sensio/framework-extra-bundle": "^5.1", // v5.6.1
"symfony/asset": "5.0.*", // v5.0.11
"symfony/console": "5.0.*", // v5.0.11
"symfony/dotenv": "5.0.*", // v5.0.11
"symfony/flex": "^1.9", // v1.17.5
"symfony/form": "5.0.*", // v5.0.11
"symfony/framework-bundle": "5.0.*", // v5.0.11
"symfony/mailer": "5.0.*", // v5.0.11
"symfony/messenger": "5.0.*", // v5.0.11
"symfony/monolog-bundle": "^3.5", // v3.6.0
"symfony/property-access": "5.0.*|| 5.1.*", // v5.1.11
"symfony/property-info": "5.0.*|| 5.1.*", // v5.1.10
"symfony/routing": "5.1.*", // v5.1.11
"symfony/security-bundle": "5.0.*", // v5.0.11
"symfony/sendgrid-mailer": "5.0.*", // v5.0.11
"symfony/serializer": "5.0.*|| 5.1.*", // v5.1.10
"symfony/twig-bundle": "5.0.*", // v5.0.11
"symfony/validator": "5.0.*", // v5.0.11
"symfony/webpack-encore-bundle": "^1.4", // v1.11.1
"symfony/yaml": "5.0.*", // v5.0.11
"twig/cssinliner-extra": "^2.12", // v2.14.3
"twig/extensions": "^1.5", // v1.5.4
"twig/extra-bundle": "^2.12|^3.0", // v3.3.0
"twig/inky-extra": "^2.12", // v2.14.3
"twig/twig": "^2.12|^3.0" // v2.14.4
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.0", // 3.4.0
"fakerphp/faker": "^1.13", // v1.13.0
"symfony/browser-kit": "5.0.*", // v5.0.11
"symfony/debug-bundle": "5.0.*", // v5.0.11
"symfony/maker-bundle": "^1.0", // v1.29.1
"symfony/phpunit-bridge": "5.0.*", // v5.0.11
"symfony/stopwatch": "^5.1", // v5.1.11
"symfony/var-dumper": "5.0.*", // v5.0.11
"symfony/web-profiler-bundle": "^5.0" // v5.0.11
}
}
Great tutorial, as ever and has definitely helped me understand what Symfony is doing under the hood. I've now just got to work out how I'd ever make use of this knowledge in practice - what sort of edge cases, I'd need to consider.... 🤔