در حال بارگذاری ...

Lookup Tables Overview0:00

Let's talk about lookup tables, what they are, why they're so great, why I love them, and why you should too. We're going to start with a little code example, we'll say UserType is equal to Admin. This should look familiar to you, it's pretty common to switch on UserTypes in Laravel apps, at least when I was mining through Laravel apps for this video, I kept seeing this. So we'll add a couple of statements, we'll say if UserType is Admin, if UserType is Moderator, if the UserType is an Author, and if those are all met, then we'll do something. Great. So this is our Muse right now, and we're going to refactor it to a strategy that uses lookup tables. So first, what's a lookup table?

Refactor to Array Lookup0:37

So this is our Muse right now, and we're going to refactor it to a strategy that uses lookup tables. So first, what's a lookup table? A lookup table, here's my formal definition. Anything you look something up in, and that can be a php array, it can be a database table, it could be a Redis cache, it can be anything. In our case, and a lot of times when I'm using them, I'm using php arrays, pretty simply. So let's refactor this to use one. If in_array, and for the in_array function in php, I always remember the parameter order with the mnemonic needle in haystack. So if in_array UserType, and then the haystack, or our lookup table is going to be Admin, Mod, Author.

with the mnemonic needle in haystack. So if inArray UserType, and then the haystack, or our lookup table is going to be Admin, Mod, Author. Cool. So it's a really simple little refactoring, but it represents one big shift here. What we've done is we've isolated the thing that changes into one group, in our case, a lookup table. We've taken it from an OR statement that you have to read out, you have to go if UserType is Admin, or Mod, or Author, and we've grouped the things that change into their own little table. So now it's apparent where you need to add something.

Improve Readability with Collections1:45

So now it's apparent where you need to add something. If you edit this code, you just add it right there. It's nice and easy. And it reads a little bit better. If the UserType is in this array, do this, rather than if this step, or this step, or this step. So let's make one more refactor to make this even more readable. We'll put this into a Laravel collection. We'll say we collect up those things, and then we'll say contains UserType.

We'll put this into a Laravel collection. We'll say we collect up those things, and then we'll say contains UserType. So it's the same thing as inArray, it just kind of reverses the order. And to me, it reads much more nicely. If this collection of UserTypes contains the current UserType, then do the thing. So I think that this is a big improvement. It's a small little, it's a small change, and it's a small example, but it represents a bigger concept. And the thing that we learned here, this first principle or benefit of refactoring to lookup tables is isolating change.

Redirects via Key-Value Lookup2:30

And the thing that we learned here, this first principle or benefit of refactoring to lookup tables is isolating change. And that is a benefit of using lookup tables. Usually you're isolating the thing that changes into a table that's kind of in a central location. Great. So let's amp this up a bit and use another pretty common example. Suppose you have a Controller to update a User. So this is in a Laravel Controller, and you're updating a User, and you do all the updating, and then you need to redirect the User to some page on the app, but it changes based

So this is in a Laravel controller, and you're updating a User, and you do all the updating, and then you need to redirect the User to some page on the app, but it changes based on what type they are. So you might say if UserType is equal to admin, then redirect that User to, let's say, the admin route. And then you add a new one for each one. So else if UserType is mod, then redirect to, I don't know, company page, then else if it's an author, redirect to the homepage. So looking at this bit of code, it's kind of just a blob of logic with branches, and it's kind of a bear to read out.

So looking at this bit of code, it's kind of just a blob of logic with branches, and it's kind of a bear to read out. It's annoying. And this is like a simple version. I'm sure you've seen 10 times worse versions. Sandy Metz, she's a wonderful code teacher, one of the best. She has this technique she calls the squint test, where you just kind of squint at a group of code and just look at the colors and the structure. And if they're all jumbled up and muddy together, there's probably room for refactoring. And you can squint and see if the colors are grouped really well.

And if they're all jumbled up and muddy together, there's probably room for refactoring. And you can squint and see if the colors are grouped really well. And if the shapes are grouped well, usually it means the code structure is a little bit better off. So let's make a refactoring here to look up tables and do the squint test and see if we've made any improvement. So in this case, we're going to call our lookup table destinations. And then it's going to be a key value pair instead of just a bunch of values. The key is going to be the userType and the value is going to be the destination that we're refactoring to.

The key is going to be the user type and the value is going to be the destination that we're refactoring to. So admin to admin, mod to company and author to home. Okay. And now we can reference this. We'll return redirect destinations and we can pass in the user type as the key. And now the way we read this out, return, redirect the user to the destination of its type. It reads a little bit better than if this, then that, if this, then that. And if we do our squint test, squinting at this, we have colors grouped all over here.

We've, we've converted that if statement, that branching into a singular execution path. Now it's kind of, I don't know, that's a little bit fancy sounding. And what I mean is just, you're not branching everywhere. You're not forking the logic. You're keeping the logic in one path. We're saying return redirect to destinations user type. There's no if statements and no branches you have to keep in your head. And another benefit is this is, this is declarative code. So this is a word that gets passed around a lot and can mean different things in different contexts, but that all kind of is of the same spirit.

Frontend Pricing with Lookup Tables6:53

Now, I want to show you one more example of using lookup tables in your apps that demonstrates a benefit I haven't even touched on yet. So we're going to use this little dummy page. It's an amount slider. And the idea is the scenario is that a user is maybe buying a car loan. And as they slide this, it's going to tell them the amount of the loan that they're selecting, but it's also going to tell them the price based on their credit score or some other complex calculation in the backend. So let's take a look. We have a root endpoint that returns a basic Blade view called loanPrice.

So let's take a look. We have a root endpoint that returns a basic Blade view called loan-price. So let's go into that Blade view, loan-price, and we have some boilerplate code. We have some HTML with our range input, some H1 tags with amount and price, and then a view instance that we're mounting to the app. So our first goal is to make amount reactive so that as we slide this amount updates in real time. So with view, this kind of thing is pretty simple. It's data driven. So we create a piece of data called amount, and we'll set it to 1000 and then we'll

It's data driven. So we create a piece of data called amount, and we'll set it to 1000 and then we'll bind it to this input here. So we'll say v-model equals amount, and now whatever the amount of this input is, it's going to be stored in that data amount there. Okay, and now we can echo this out into the template using curly braces. We'll say amount. Now Vue and Blade use the same exact syntax for echoing. So we have to tell Blade to not interpret this echo with an @ symbol. Now in the browser, refresh, and there we go.

So we have to tell Blade to not interpret this echo with an at symbol. Now in the browser, refresh, and there we go. We're sliding and it's automatically updating. Okay, that was the easy part. Now, as we slide, we want the price to update, but the price requires some complex calculation on the backend. So we can't just write it in JavaScript. Here's where lookup tables come in handy, because otherwise we'd be forced to send an AJAX request every time amount updates and then update the price if the logic has to live in the backend.

AJAX request every time amount updates and then update the price if the logic has to live in the backend. But with lookup tables, we can kind of expedite that process and pre-calculate all the potential prices up front, and then JavaScript can just use those. So I'll show you what I mean. Let's create a computed property called price. Okay, and then here, let's just pretend that we have a lookup table called loanPricesByAmount, and all the keys are amounts and the values are the prices. We could just say this.amount. Does this look familiar?

We could just say this $amount. Does this look familiar? It's another lookup table, but it's a totally different application. So if we pre-compute this array on the backend or this lookup table, pass it to the front end, as the user drags, the $price is automatically going to update with our pre-computed values. So let's implement this on the backend and see if we can get it to work. So we're returning the Blade view here. Let's return that array. So we'll say loanPricesByAmount, and then we'll need that $value here. So this is a little bit unique because we're going to have to generate the lookup table.

So we'll say loan prices by amount, and then we'll need that value here. So this is a little bit unique because we're going to have to generate the lookup table dynamically. There's a method on the User model called calculateLoanPrice, and you pass in the amount, and then you get out the price. But we're going to have to run this method for every single potential amount and generate this lookup table where the keys are the amounts and the values are the calculated prices, and then pass it to the front end. So let's start with a group of amounts. php has a nice little range function where you can pass in a min, a max, and then the

So let's start with a group of amounts. php has a nice little range function where you can pass in a min, a max, and then the increments. So we'll say 1,000, 10,000, and then steps of 500, and this is mirroring the min, the max, and the step of the actual input. Okay, so there's our amounts, and now we can compute the values. So we'll say prices equals, and we'll use an array_map. The first value will be our callback, and the second value will be the amounts as the input. Okay, and we can return basically this snippet, and if you're not familiar with array_map,

Okay, and we can return basically this snippet, and if you're not familiar with array_map, what's going to happen is php is going to loop through all these amounts from 1,000 to 10,000, and every single time it's going to return the price based on the result of that method. Okay, so we have our amounts, and we have our prices, and now we can kind of zip them up with a php method called array_combine, where the first parameter is the keys, and where the first parameter is the keys to a new array, and then the second parameter is the values. So it's going to take all these amounts and make them the keys, and all these prices and

the values. So it's going to take all these amounts and make them the keys, and all these prices and make them the values. So to give you an idea of what we've generated right here, let's dd this out in the browser so we can actually see what we've done. Refresh the page, and there we go. All the keys are 1,000 through 10,000, and then these are the prices that got calculated from the User model. So now as the User slides that amount button, it's going to magically go up through these keys and show the proper value as the price input.

So now as the User slides that amount button, it's going to magically go up through these keys and show the proper value as the price input. So let's get this loanPrices amount array into the front end so that we can use it. So rather than AJAXing this, there's a nice little @json Blade helper that makes this really easy. So we'll say loanPricesByAmount in the data here, then we can do @json, and then just echo it out here, loanPricesByAmount. Okay, and now the view instance is going to have access to that lookup table. And we can do this->loanPricesByAmount, this->amount, and now everything should work. And now we can echo out the price.

We can't share logic with the front end. Like you can't call a php method in JavaScript, but you can calculate things inside a lookup table and pass that into JavaScript. This is useful for tons of things for like we saw hiding, maybe a proprietary method. Like if we used the user's credit score, we want to keep that on the back end. Lookup tables are great for that. Maybe if it's an expensive operation, you could cache the entire lookup table and just use it whenever you want it. So I think this is a phenomenal approach that helps me to keep my logic and my business critical stuff on the back end and still have dynamic front ends.

This is just a simple explanation with no code.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟