<

div class=”titlepage”>

The Strategy pattern

The best approach to describe the Strategy pattern is through a problem.

<

div class=”section” title=”The need for the Strategy pattern”>

<

div class=”titlepage”>

The need for the Strategy pattern

In this design pattern, the logic is extracted from complex classes into easier components so that they can be replaced easily with simpler methods. For example, you want to show popular blog posts on your website. In a classic approach, you will calculate the popularity, make the pagination, and list the items relative to the current paginated offset and popularity, and make all calculations in a simple class. This pattern aims to separate each algorithm into separate components so that they can be reused or combined in other parts of the application easily. This approach also brings flexibility and makes it easy to change an algorithm system wide.

To understand this better, let’s take a look at the following loader interface located atvendor/Illuminate/Config/LoaderInterface:

<

div class=”informalexample”>

<?php namespace Illuminate\Config;

interface LoaderInterface {

   public function load($environment, $group, $namespace = null);

   public function exists($group, $namespace = null);

    public function addNamespace($namespace, $hint);

   public function getNamespaces();

   public function cascadePackage($environment, $package, $group, $items);

}

When we dig the code, the LoaderInterface works will follow a certain structure. ThegetNamespaces() function loads all namespaces defined in the app\config\app.php file. TheaddNamespace() method passes the namespaces to the load() function as grouped. If theexist() function returns true, there is at least one configuration group that belongs to a given namespace. For the full structure, you can refer to the repository section of this chapter. As a result, you can easily call the method that you need through an interface of the Loader class to load various configuration options. If we download a package through the composer, or implement a package to an application that is being authored, the pattern makes all of them available and loads them from their own namespaces without any conflicts, though they are inside different namespaces or have the same filenames.