About this book

This book covers how to develop different applications and solve recurring problems using Laravel 4 design patterns. It will walk you through the widely used design patterns—the Builder (Manager) pattern, Factory pattern, Repository pattern, and Strategy pattern—and will empower you to use these patterns while developing various applications with Laravel. This book will help you find stable and acceptable solutions, thereby improving the quality of your applications. Throughout the course of the book, you will be introduced to a number of clear, practical examples about PHP design patterns and their usage in various projects. You will also get acquainted with the best practices for Laravel that will greatly reduce the probability of introducing errors into your web applications.

By the end of the book, you will be accustomed to the best practices and the important design patterns used in Laravel to make a great website.

Publication date:
July 2014


Chapter 1. Design and Architectural Pattern Fundamentals

Programming is actually a lifestyle rather than a job. It's an intense mental activity. The best developers in the world think about their work 24/7. They come up with their best ideas when they are not at their work desks. Generally, their finest work is done away from the keyboard.

As developers need to look at problems from a different standpoint, software projects cannot be accelerated by spending more time in the office or adding more people to a project. Development is not just about timelines and assigned tasks. If you visit the development centers of world-famous software companies such as Google and IBM, you'll see that there are many opportunities for spending time away from the keyboard for developers. Programming questions have to be thought of in the context of the real world. So, object-oriented programming was invented to make writing software more instinctive for our hunter-gatherer brains; that is, software components took on the properties and behavior of objects in the real world. When looking for a solution to a problem or a way to accomplish what we want, we generally hope to find a way that is reusable, optimized, and cheap. We, as developers, have a few standard ways of approaching some commonly recurring problems in programming, which are called design patterns.

When you come across certain problems that recur, you try and find solutions to solve them that can be used by anyone and everyone. This concept is prevalent everywhere – mechanics, architecture, and even human behavior for that matter. Programming is absolutely not an exception.

Programming solutions depend on the needs of the problems and are modified accordingly because each problem has its own unique conditions. Commonly recurring problems exist in both real life and programming life. So, design patterns are given to us to implement our project. These patterns have already been tested and used by many other developers for solving similar problems successfully. Using design patterns also makes it possible to work with clean, standardized, and readable code. Deciding to write a program that does X but using pattern Y is a recipe for disaster. It might work for programs such as hello world, fit for demonstrating the code constructs for patterns, but not much else.

Through patterns, we could also find a way to work around the inefficiencies that a language may have. Also, a thing to note here, inefficiency is usually associated with negativity, but it may not necessarily be bad at all times.

In this book, we'll cover PHP design patterns with the Laravel PHP Framework. In the first few chapters, we'll also give examples from the Laravel core code. In the chapters that follow, we'll cover the MVC pattern fundamentals. Then we'll try to examine the differences between an MVC pattern approach to Laravel and a common MVC approach. We hope this book will help you increase your code quality.

Please note that finding the best stable, high-quality solution directly depends on your knowledge of the platform and language. We highly recommend that you be well-versed with the data types and fundamentals of object-oriented programming in PHP and Laravel Framework.

In this chapter, we'll explain design pattern terms and learn about the classification of these design patterns and their elements. We'll give some examples from the Laravel core code, which contains the design patterns used in the framework. Finally, we'll explain the Mode-View-Controller (MVC) architectural pattern and its benefits.


Design patterns

Design patterns were first introduced by Eric Gamma and his three friends in 1994. A design pattern is basically a pattern of software design that is implemented on multiple projects, and its intended success gives an idea to prove this pattern as a solution of commonly recurring problems.

Design patterns are ways to solve a problem and the way to get your intended result in the best possible manner. So, design patterns are not only ways to create a large and robust system, but they also provide great architectures in a friendly manner.

In software engineering, a design pattern is a general repeatable and optimized solution to a commonly occurring problem within a given context in software design. It is a description or template for how to solve a problem, and the solution can be used in different instances. The following are some of the benefits of using design patterns:

  • Maintenance

  • Documentation

  • Readability

  • Ease in finding appropriate objects

  • Ease in determining object granularity

  • Ease in specifying object interfaces

  • Ease in implementing even for large software projects

  • Implements the code reusability concept

If you are not familiar with design patterns, the best way to begin understanding is observing the solutions we use for commonly occurring, everyday life problems.

Let's take a look at the following image:

Many different types of power plugs exist in the world. So, we need a solution that is reusable, optimized, and cheaper than buying a new device for different power plug types. In simple words, we need an adapter. Have a look at the following image of an adapter:

In this case, an adapter is the best solution that's reusable, optimized, and cheap. But an adapter does not provide us with a solution when our car's wheel blows out.

In object-oriented languages, we the programmers use the objects to do whatever we want to have the outcome we desire. Hence, we have many types of objects, situations, and problems. That means we need more than just one approach to solving different kinds of problems.

Elements of design patterns

The following are the elements of design patterns:

  • Name: This is a handle we can use to describe the problem

  • Problem: This describes when to apply the pattern

  • Solution: This describes the elements, relationships, responsibilities, and collaborations, in a way that we follow to solve a problem

  • Consequences: This details the results and trade-offs of applying the pattern

Classification of design patterns

Design patterns are generally divided into three fundamental groups:

  • Creational patterns

  • Structural patterns

  • Behavioral patterns

Let's examine these in the following subsections.

Creational patterns

Creational patterns are a subset of design patterns in the field of software development; they serve to create objects. They decouple the design of an object from its representation. Object creation is encapsulated and outsourced (for example, in a factory) to keep the context of object creation independent from concrete implementation. This is in accordance with the rule: "Program on the interface, not the implementation."

Some of the features of creational patterns are as follows:

  • Generic instantiation: This allows objects to be created in a system without having to identify a specific class type in code (Abstract Factory and Factory pattern)

  • Simplicity: Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object (Builder (Manager) and Prototype pattern)

  • Creation constraints: Creational patterns can put bounds on who can create objects, how they are created, and when they are created

The following patterns are called creational patterns:

  • The Abstract Factory pattern

  • The Factory pattern

  • The Builder (Manager) pattern

  • The Prototype pattern

  • The Singleton pattern

Structural patterns

In software engineering, design patterns structure patterns facilitate easy ways for communications between various entities.

Some of the examples of structures of the samples are as follows:

  • Composition: This composes objects into a tree structure (whole hierarchies). Composition allows customers to be uniformly treated as individual objects according to their composition.

  • Decorator: This dynamically adds options to an object. A Decorator is a flexible alternative embodiment to extend functionality.

  • Flies: This is a share of small objects (objects without conditions) that prevent overproduction.

  • Adapter: This converts the interface of a class into another interface that the clients expect. Adapter lets those classes work together that would normally not be able to because of the different interfaces.

  • Facade: This provides a unified interface meeting the various interfaces of a subsystem. Facade defines a higher-level interface to the subsystem, which is easier to use.

  • Proxy: This implements the replacement (surrogate) of another object that controls access to the original object.

  • Bridge: This separates an abstraction from its implementation, which can then be independently altered.

Behavioral patterns

Behavioral patterns are all about a class' objects' communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects. The following is a list of the behavioral patterns:

  • Chain of Responsibility pattern

  • Command pattern

  • Interpreter pattern

  • Iterator pattern

  • Mediator pattern

  • Memento pattern

  • Observer pattern

  • State pattern

  • Strategy pattern

  • Template pattern

  • Visitor pattern

We'll cover these patterns in the following chapters. If you want to check out the usage of some patterns in the Laravel core, have a look at the following list:

  • The Builder (Manager) pattern: Illuminate\Auth\AuthManager and Illuminate\Session\SessionManager

  • The Factory pattern: Illuminate\Database\DatabaseManager and Illuminate\Validation\Factory

  • The Repository pattern: Illuminate\Config\Repository and Illuminate\Cache\Repository

  • The Strategy pattern: IIlluminate\Cache\StoreInterface and Illuminate\Config\LoaderInterface

  • The Provider pattern: IIlluminate\Auth\AuthServiceProvider and Illuminate\Hash\HashServiceProvider


What is MVC?

The MVC triad of classes were used to build user interfaces in Smalltalk-80 in 1988. MVC is an architectural pattern that is used in software engineering, whose fundamental principle is based on the idea that the logic of an application should be separated from its presentation. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the way that information is presented to or accepted from the user. Refer to the following figure:

In the preceding figure, you'll see the elements of MVC. It shows the general life cycle on an MVC-based application of a request. As you can see, using an MVC architectural pattern in projects allows you to separate different layers of applications, such as the database layer and the UI layer.

The benefits of using the MVC pattern are as follows:

  • Different views and controllers can be substituted to provide alternate user interfaces for the same model.

  • It provides multiple simultaneous views of the same model.

  • The change propagation mechanism ensures that all views simultaneously reflect the current state of the model.

  • Changes affecting just the user interface of the application become easier to make.

  • It is easier to test the core of the application, as it is encapsulated by the model.

  • One of the great benefits of the MVC pattern is that it allows you to recycle the application's logic when you use different templates. For example, when you want to implement an external API inside a part of your application, it will be very helpful to reuse the application's logic. If the MVC approach of Laravel is followed thoroughly, you will only need to modify the controller to render many different templates/views.



In this chapter, we have explained the fundamentals of design patterns. We've also introduced some design patterns that are used in the Laravel Framework. Finally, we explained the MVC architectural pattern concepts and its benefits.

In the next chapter, we'll cover the MVC concept in depth and its usage in Laravel. Before moving on to learn about design patterns and their usage in Laravel with the actual code, the most important thing is understanding the framework's approach to the MVC concept.

About the Authors

  • Arda Kılıçdağı

    Arda Kılıçdağı is a PHP/MySQL/JavaScript/Linux programmer and server administrator from Turkey. He has been developing applications with PHP since 2005. He administers the Turkish national support site of the world famous open source content management script, PHP-Fusion. He's also one of the international developers and a member of the management team of CMS, and he plays an important role in CMS's future. He has worked as a developer and has experience on projects such as Begendy (an exclusive private shopping website) and Futbolkurdu (a local soccer news website). He has experience working with the Facebook API, the Twitter API, and PayPal's Adaptive Payment API (used on crowdfunding websites such as KickStarter). He's also experienced with JavaScript, and he's infusing his applications with JavaScript and jQuery, both on frontend and backend sides.

    He has developed applications using CodeIgniter and CakePHP for about 4 years, but these PHP frameworks didn't suit his needs completely, and that's why he decided to use another framework for his projects. After getting introduced to Laravel, he has developed all his applications with it.

    He's also interested in Unix and Linux, and he uses Linux on a daily basis. He's administering the world's best-known microcomputer, Raspberry Pi's biggest Turkish community website, Raspberry Pi Türkiye Topluluğu (Raspberry Pi Turkish Community Website).

    Before authoring this book, Arda has written two other books. The first book is Laravel Application Development Blueprints, Packt Publishing, coauthored by H. İbrahim YILMAZ. The second book, Raspberry Pi, Dikeyeksen Consulting & Publishing, is written in Turkish.

    Browse publications by this author
  • H. İbrahim YILMAZ

    H. İbrahim YILMAZ is a daddy, developer, geek, and an e-commerce consultant from Turkey. After his education at Münster University, Germany, he worked as a developer and software coordinator in over a dozen ventures. During this period, he developed the usage of APIs such as Google, YouTube, Facebook, Twitter, Grooveshark, and PayPal.

    Currently, he's focused on creating his company about concurrent computing, Big Data, and game programming. He writes articles on Erlang, Riak, functional programming, and Big Data on his personal blog at http://blog.drlinux.org. He is a big Pink Floyd fan, playing bass guitar is his hobby, and he writes poems at http://okyan.us.

    He has a daughter called İklim. He lives in a house full of Linux boxes in Istanbul, Turkey.

    Browse publications by this author

Latest Reviews

(1 reviews total)