Laravel's secret weapon: macros (watch me code)
Customizing Laravel to do *exactly* what I want, thanks to macros and the container.
Everything I said
This, this is gonna be a little bit of a different video. This is gonna be, uh, kinda like watch me figure stuff out, code along with me, uh, a few twists and turns probably. I was, I was working on my personal website not too long ago, and I was mucking around with macros and stuff in the container, and I thought, "This is...
I think this is kinda interesting." And so what I'm gonna show you here is the power of Laravel's macro-able trait, the container, and the fact that you can figure anything out. I think that's the most important thing that I want to tell you, is you can just go look in the source code. Y- documentation is wonderful and amazing, but you can also just dive into the source code and figure out how to do something.
So this is gonna be a little bit, uh, a, a little bit out there. I don't know if I would necessarily recommend exactly what I'm about to do, but why not? It's my own personal website, I can do whatever I want. So let me show you what we're working with here. This is my website right here. This is what we're going for. Um, I've got an article here called What If You Tried Hard? that just lives on aaronfrancis.com.
And if you click on it, it just takes you to aaronfrancis.com. Pretty basic. I've got an article here that lives on github.com, and if you click on it, it takes you directly to github.com. So I've got this concept of internal articles and external articles. No problems so far, but let's take a look over here and say that an internal article is an article where not null markdown file.
So everything's driven from markdown. So if there's a markdown file, then that's an internal article, and we'll say that an external article is an article where null. And here is where it gets tricky. So if I were to return, um, let's just say, let's just dump out route article.show of internal.
That should be okay. So if I dump that out, you see aaronfrancis.com.test What If You Tried Hard? Good enough. Now, if I route to the external, it makes up this URL that, that simply doesn't exist, because it should, it should link out to github.com, or in this case, planetscale.com, not to aaronfrancis.com.
All right, so you see the problem, right? I just want to call route article.show and pass the article in and have the URL end up correct, but Laravel doesn't support this out of the box. That's fine. We don't need to go on Twitter and complain. We don't need to ask a bunch of questions. We can just figure it out ourselves. Let's see how we do that. All right, I am first going to Command+click into route to see how this routing helper works.
It looks like it defers to something called app URL route, and I can't click on that 'cause I don't have Laravel Idea, I think is what it's called, installed. So what I'm gonna do is I'm just gonna, I'm just gonna dump it out, and we'll see that we have a URL generator. So now, if I come over here and I paste that in, URL generator, now we're in here, and if we look back at the helper, s- this is the URL generator part.
The, um, the URL generator is bound into the container under this alias of URL. So we need to look at the route method on that URL generator. Uh, if I can spell it correctly, we go down to route. There we go. So this is, let's confirm, this is, uh, this is, this is gold right here.
You always just put a DD here. That's, that's what you, that's how you debug these things. So now if we... All right, we're on the right track. Going back to the URL generator, this is where I start to look in and think, "Is there anywhere that I can hook in? Is there anywhere that I can, um, affect change from the outside?" So looks like this does a get route by name.
I think we'll probably end up in here. Yep, we're in there, and so then it defers to this to route. So let's go down to to route, and I think we should be, we should be in here now. Yes, we are. So then this does a bunch of different stuff, and then down here, so this is, uh, collecting up the parameters, resolving route model binding.
It's doing a bunch of stuff here. So if I then dump out parameters down here, what do we have? We've got that article. Okay, that makes enough sense. Then this defers even further to route URL to. So if we click in on to, we are now in this route URL generator class. So we're, we're several levels deep at this point, and this is where it actually, yep, this is where it actually...
There we go. Route UR- URL generator 108. So this is where that URL actually gets generated. It looks like it does some query string stuff. It does the domain here. All right. Usually, Laravel gives us a place to hook in, whether that's some sort of static configuration method or something in the container or some, some sort of optional method on the object that's being passed around.
I don't see that here. I don't see that anywhere here. It looks like, um, there's nowhere to hook into. There's nothing, uh, that is called on the actual route itself, and so there's nowhere that we can sneak in, uh, a- and modify this behavior.
So I think the question is, where does this route URL generator, this class here, can we decorate it, extend it, hook it somehow? So if we go back out here, and we come down- Come back out here. You'll see this RouteUrl2. So if we Command + click on this, well, shoot, that's newed up right here.
So it's not even pulled out of the container. It's actually just a new class that's being instantiated. So we can't override anything in the container here. We're gonna have to figure out a little bit more of a brute force/hacky way to do this. Because that RouteUrlGenerator is newed up inside the class instead of being pulled out of the container, we can't really touch that.
So we're gonna go up a level and look at the UrlGenerator. So we're in this UrlGenerator class, and we know that this gets resolved out of the container. So if we hop over to the app service provider, we can say, this app, extend, and we will just extend the URL. We can actually just extend URL.
And if we come in here, this should be an instance of UrlGenerator. And if we dump this out, hopefully we'll have access to that. So now we have access to the UrlGenerator that is bound in the container, and we can, we can kinda, we can kinda do whatever we want.
Now, this is where we're gonna go off the beaten path a little bit. I think the most proper pattern-friendly, solid design principles way to do this would be return a new URL decorator and pass the generator in, and, you know, sorry, I just, I don't wanna do that. My goal here is to never tell you exactly what you need to be doing, but more kinda show you how I do stuff, and hopefully teach you how to think about things yourself.
I don't wanna do this. You may wanna use a decorator. That's fine. I don't like decorators, 'cause then you have to proxy everything, and then anywhere where UrlGenerator is hinted and you pass URL decorator, you're hosed. So I'm gonna do it a different way. My site, my video, I'm gonna do it a different way. You don't have to do it this way, but it is kinda interesting. So what I'm gonna do is I'm gonna return my own UrlGenerator.
So let's come out here, and let's create a custom CustomUrlGenerator. And what I am gonna do is say that that extends Laravel's UrlGenerator. Okay. So now if I come back here, we can return new URL, or new CustomUrlGenerator.
And you see the problem now. We have to pass through the constructor args. So if we come over to the constructor, we see that these arguments are passed in, and they're set, and are they protected? Bummer. So we don't have access to those from the outside.
But look, UrlGenerator is macroable. One of the greatest things that Laravel has ever done is make almost every class macroable, so you can add methods from the outside. So let's do something a little bit verboten, which I think means bad. I'm not entirely sure. Uh, UrlGenerator::macro, getConstructor.
This is wild. I bet people do not like this. getConstructorArgs. Return. So what are the constructor args? I think it's $this-routes, $this, uh, request, and $this-assetRoute. This refers to UrlGenerator. So now we're inside that UrlGenerator instance, and even though it's protected, we have access to that.
So routes, request, and assetRoute. Let's just make sure that that's right. Routes, request, and assetRoute. Routes, assetRoute, and request. So we are good to go. So now inside of here, we can spread that out and say generator. I'm just gonna copy and paste. getConstructorArgs.
And now we should, we should have... There we go. We're working again. We, it is, it is working again, but now, importantly, we are using our custom UrlGenerator, which means we've got the hooks. We can do whatever we want. So let's do something that we want to do.
Um, what did we wanna do? I think we wanted to muck about with route. That was probably... Let's do toRoute. So if we take toRoute, and we come back to our CustomUrlGenerator, public function toRoute. Yep, yep, yep, and we'll do the classic... Aha. We win.
We're in. Now, let's take a look at what route actually is. Route is Illuminate Routing Route. Okay, where, where does that come from? So we've got the article uri. Do we have parameters yet? We don't have parameters yet. Um, so where do those parameters...
Yep, yep, yep. We don't have parameters yet on the route, but do we have parameters here? We do.
So we have the article. We have the route. We're in good shape. Now, what you could do here, what we could easily do here is we could say if route, um, easily, easily, and then I can't even do it. What is... How do we get the name of this route? It's probably Routing Route, so let's go ahead and hint this just for now, Routing Route, and then we say, uh, name?
getName. All right. So does that give us article.show? So we could do this. I don't like this. I don't like this. You may like it, and that's fine. You do you. Article.show, then- Uh, we could do that. Okay? And we could say, uh, if we're in here, all right, so if parameters instance of article, then...
Okay. We could say if parameters, um, if, let's say, is null parameters, which is now article. If is null parameters, uh, what's it called? Markdown file. Boy, you can see why I don't like this.
Return just, uh, parameters. I think it's called external URL. Um, I messed something up. There we go. There we go. That would work. That would absolutely work. So if we go back to our web, you see... And we can do internal and external.
It works. It totally works. We have an internal article routing internally, and we have an external article routing externally. This is good. Ugh, this is not great. This is not great. We- let's make it great. We always wanna make it great. So this right here is nonsense.
This is way too specific to that route. So we're gonna comment that out, and what we're gonna do instead is we're gonna look at this route here. Um, actually we can go to route down here. This is the actual, uh, route object, and yes, it is macro-able, so we can add a cla- or a, a method to that right here.
So let's say, um, it's actually this guy. This guy. So we can say, what do we wanna call this? We can add any sort of, uh, any sort of method that we want. Let's say, um, generate routes using... No, not routes. That seems bad. Generate URLs using, and we can pass through a function that accepts an article.
That seems cool. Um, and then we can say if... Well, let's just go back to our... Let's just go back here. Um, yes, yes, yes. Let's take that guy, come out here. Um, if... Well, we don't need that. This is now called article.
And generate URLs using this function that accepts an article. Let's simplify FQN. If it's null, if the markdown file is null, return the external URL. Otherwise, return null, and that's gonna be our signal that we just wanna fall through to Laravel's, uh, Laravel's routing. So if we come back to custom...
Isn't this fun? This is why programming is so fun. You can do whatever you want. Let's carry on. All right, so we're back over here. This is not gonna work anymore. It's gonna blow up in a couple different ways. Generate URLs using doesn't exist. You're gosh darn right it doesn't. If we come back to the app service provider, and we do another little macro, route macro, generate URLs using function, whoops, function, and
I think this is the callback, um, or maybe callable. I don't really know. Yes. So that is the closure that we passed to that made-up function earlier. Um, so now what do we do? Now, where do we put this callback? Well, I've got an idea. Let's come over here and say, um, I don't know.
Um, we can make a weak map. We could say, um, public... Well, let's just make it protected for giggles. Weak map, um, ooh, generators. Does that work? Okay, so we're still good so far, and then let's do public function add...
Let's make this... Ooh, yeah, yeah, yeah, yeah, yeah, yeah, yeah. Yep, yep, yep. Static function, add generator, I think. Callable, no, callback, yes, and route, and I think this should be... Yep, that should be a route.
And then if we say DD here, excited about it, we can come in here and say custom URL generator, add generator for this with callback. Hooray. And did we get everything we needed over here? So route and callback. Hooray.
Great. This is going really well. Honestly, I thought this was gonna go a lot worse. Okay, so now in the weak map, if I can remember how to use weak maps whatsoever, um, static generators offset set route callback.
Did that do anything? Must not be accessed before initialization. God, I hate it when that happens. It is an easy fix though, so I can say, um, I can say static generators. I think it's question question equals new weak map. So that's gonna, that's gonna set it if it doesn't exist and ignore it if it does, and I think this can actually just be, uh, array syntax
I think that should work. Okay, so we're back on track. What we have done here is instead of just using an array, we've used a weak map, and that will allow us to set an object as the key, um, and it won't, it won't hang onto it. If, if it should be garbage collected, it'll let it go. But it does l- it does allow you to set an object as a key, which in this case is pretty important.
Now, the fun stuff. Let's come down here and say if, if what? If what? Um, if static generators offset exists, if the route exists, then let's see if that works. Hooray.
So we have registered a callback for that route, and we'll say that URL equals call user func, uh, this guy. Um, we can, at this point, we know it exists, so we can just call it like that. Call user func. And what do we need to pass through?
We probably need to pass through the parameters just like that, and I think we probably... Ooh, I don't know that they're guaranteed to be an array there. So if we come out here, null, that didn't work. But did our, did our callback get called? DD callback.
Callback got called. Did it get called with an article? It got called with an article. Um, so I think it's probably 'cause it's that guy. So, um, I just wanna route the external one right now. Whoa, there we go. Hey, look at that. There is the planescale.com/blog.
So what has actually happened? In this custom URL generator, we said we're gonna extend this to route function, and in that function, we're gonna see if this route has registered a custom URL generator. If it has registered a custom URL generator, we're gonna defer to that generator and pass through the parameters.
Now, if this generator returns null, we want to fall through, we wanna fall through to this part down here. So we can just say, if not is null URL, return URL. And that way, it should still fall through for the internal.
So that external one works. Let's go back for internal and see if that one works. Internal custom URL generator. We did it. We freaking did it. We have external URLs, internal URLs. Everybody's routed to the same spot.
I like this because it keeps it all together, so it's not shoved off into some corner of the custom URL generator. It's right here. This is how you generate URLs for this route. Um, I like that I can just, I don't have to do any sort of checking to see if it's internal or external throughout the rest of my site.
I can just say, "Give me the route to that article," and it's gonna give me the exact correct route, whether it's internal or external. There are a few things that we're gonna clean up here in a second, but first, importantly, you don't have to like this. You don't have to like this. If you hate everything that I have done here, that's okay. I'm okay with that.
You don't actually have to tell me that, but I'm okay with that. I think the thing that I want you to take away from this is that you can figure anything out. You can figure anything out, and you can make Laravel do anything you want it to do, no matter how bizarre or wacky or hacky it might be. In the real world, I would probably add a single test for this and move on, 'cause if they change the URL generator, a bunch of my stuff is gonna change.
I know that. I'm honestly, I'm not gonna add a test. This is my personal website. The stakes are very low. This is pleasing to me, so I'm just gonna leave it as is. Let's clean up a little bit of stuff while you think about all the things that you wanna do in your app. Okay, I think the only thing I wanna clean up here is this feels a little, this feels a little bit messy to me.
I think what I wanna do is say URL equals null, and then get rid of that, and then just say, yeah, we can get rid of that comment, thank you very much. And then say URL. I think that should do it. And also for completeness, we need to pass all of the parameters in there.
So I think that gives me everything that I want. Yep, that gives me everything that I want, and it's a little bit cleaner, and it still accepts all of the parameters that Laravel is giving to us. That's it. Hopefully, you feel confident that you can explore and figure out anything that you need to do. If you wanna see more of these more loose form videos, let me know in the comments below.
If you wanna watch a video on how I generate self-healing URLs that are guaranteed to work forever, I'll put that video on the screen here. Until the next time, see ya.