Wanna learn design patterns? Here's a "secret": you've all actually USED them already while working with Laravel itself. Let's see the examples of patterns like Facade, Builder, and Adapter in the framework code.
Builder Pattern
The most common and familiar Builder pattern is the Query Builder in Laravel. Of course, it is extended by Eloquent Models but the core example is still the Query Builder. Let's look at the example:
Let's get a basic example:
Query Builder
DB::table('users') ->where('name', 'John') ->where('age', '>', 18) ->orderBy('age') ->get();
So what did we do, and why is it a Builder? We've built a query by chaining methods on top of a base. So what does it do under the hood? Let's look at the example:
-
DB::table('users')
- We indicate that we will work with theusers
table -
->where('name', 'John')
- Added a condition that onlyJohn
users should be selected -
->where('age', '>', 18)
- Added a condition that only users with an age greater than 18 should be selected -
->orderBy('age')
- Order the users by age -
->get()
- Executed the query and retrieved the results from the database
Each of these individual blocks will append to a raw SQL query as we are building it in parts. Think about it like this:
-
DB::table('users')
-SELECT * FROM users...
-
->where('name', 'John')
-...WHERE name = 'John'...
-
->where('age', '>', 18)
-...WHERE name = 'John' AND age > 18...
-
->orderBy('age')
-...ORDER BY age...
-
->get()
-SELECT * FROM users WHERE name = 'John' AND age > 18 ORDER BY age
If we want to look at how we are building an update query we can look at...