Chapter

Patterns in the real world

Where the principles and patterns show up in everyday Laravel: dependency injection, the repository pattern, when not to use a pattern, and refactoring toward one.

Design Patterns & Principles 5 Lessons from courses

About this chapter

The first six chapters taught the principles and the patterns in isolation, one small example at a time. This chapter puts them where you actually meet them: inside a real framework, in real project code, in the decisions you make every week.

You'll see that a modern framework like Laravel 11 is built out of the patterns you just learned, so you already use them daily without naming them. Then we get practical: dependency injection and the service container, the much-debated repository pattern, how to tell when a pattern is the wrong choice, and how to refactor messy code toward a pattern instead of starting there. The theme of the whole chapter is judgment - knowing which tool fits, and when reaching for none is the better call.

Lessons from courses

  1. 1 Patterns you already use in Laravel Facades, the container, events, middleware, notifications - the design patterns in Laravel you use every day, named and mapped to the Gang of Four.
  2. 2 Dependency injection and the container How dependency injection in Laravel works: type-hint an interface, bind it once, and the service container auto-resolves it via constructor injection.
  3. 3 The repository pattern The repository pattern in Laravel, with a PHP example and the honest debate: Eloquent is already a repository, so when does the extra layer earn its keep?
  4. 4 When not to use a pattern Knowing when not to use a design pattern beats knowing the patterns. Avoid over-engineering, the golden hammer, and speculative abstraction in your code.
  5. 5 Refactoring toward a pattern A worked PHP example of refactoring to the strategy pattern: a growing if/elseif becomes clean classes, step by step. Refactor toward patterns, don't start there.
Design Patterns & Principles Go to course