The Strategy pattern in laravel

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

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.

Recommended :  Putting the Loop in Context in wordpress

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

<?php namespace IlluminateConfig;

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 appconfigapp.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.

Recommended :  Creating a user login in yii framework

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares