3 Crazy Microsoft Excel Formulas That Are Extremely Useful

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2018/10/conditional-formatting-excel.png

Microsoft Excel formulas can do almost anything. In this article, you’ll learn how powerful Microsoft Excel formulas and conditional formatting can be, with three useful examples.

Getting to Know Microsoft Excel

We’ve covered a number of different ways to make better use of Excel, such as where to find great downloadable Excel templates, and how to use Excel as a project management tool.

Much of the Excel power lies behind the Excel formulas and rules that help you manipulate data and information automatically, regardless of what data you insert into the spreadsheet.

Let’s dig into how you can use formulas and other tools to better use Microsoft Excel.

Conditional Formatting With Excel Formulas

One of the tools that people don’t use often enough is Conditional Formatting. With the use of Excel formulas, rules, or just a few really simple settings, you can transform a spreadsheet into an automated dashboard.

To get to Conditional Formatting, you just click on the Home tab and click on the Conditional Formatting toolbar icon.


Under Conditional Formatting, there are a lot of options. Most of these are beyond the scope of this particular article, but the majority of them are about highlighting, coloring, or shading cells based on the data within that cell.

This is probably the most common use of conditional formatting—things like turning a cell red using less-than or greater-than formulas. Learn more about how to use IF statements in Excel.

One of the lesser-used conditional formatting tools is the Icon Sets option, which offers a great set of icons you can use to turn an Excel data cell into a dashboard display icon.


When you click on Manage Rules, it’ll take you to the Conditional Formatting Rules Manager.

Depending on the data you selected before choosing the icon set, you’ll see the cell indicated in the Manager window with the icon set you just chose.


When you click on Edit Rule, you’ll see the dialog where the magic happens.

This is where you can create the logical formula and equations that will display the dashboard icon you want.

This example dashboard will show time spent on different tasks versus budgeted time. If you go over half the budget, a yellow light will display. If you’re completely over budget, it’ll go red.


As you can see, this dashboard shows that time budgeting isn’t successful.

Almost half of the time is spent way over the budgeted amounts.


Time to refocus and better manage your time!

1. Using the VLookup Function

If you’d like to use more advanced Microsoft Excel functions, then here are a couple for you to try.

You’re probably familiar with the VLookup function, which lets you search through a list for a particular item in one column, and return the data from a different column in the same row as that item.

Unfortunately, the function requires that the item you’re searching for in the list is in the left column, and the data that you’re looking for is on the right, but what if they’re switched?

In the example below, what if I want to find the Task that I performed on 6/25/2018 from the following data?


In this case, you’re searching through values on the right, and you want to return the corresponding value on the left.

If you read Microsoft Excel pro-user forums, you’ll find many people saying this isn’t possible with VLookup. You have to use a combination of Index and Match functions to do this. That’s not entirely true.

You can get VLookup to work this way by nesting a CHOOSE function into it. In this case, the Excel formula would look like this:

"=VLOOKUP(DATE(2018,6,25),CHOOSE({1,2},E2:E8,A2:A8),2,0)"

This function means that you want to find the date 6/25/2013 in the lookup list and then return the corresponding value from the column index.

In this case, you’ll notice that the column index is "2", but as you can see, the column in the table above is actually 1, right?


That’s true, but what you’re doing with the "CHOOSE" function is manipulating the two fields.

You’re assigning reference "index" numbers to ranges of data – assigning the dates to index number 1 and the tasks to index number 2.

So, when you type "2" in the VLookup function, you’re actually referring to Index number 2 in the CHOOSE function. Cool, right?


The VLookup now uses the Date column and returns data from the Task column, even though Task is on the left.

Now that you know this little tidbit, just imagine what else you can do!

If you’re trying to do other advanced data lookup tasks, then check out this article on finding data in Excel using lookup functions.

2. Nested Formula to Parse Strings

Here’s one more crazy Excel formula for you! There may be cases where you either import data into Microsoft Excel from an outside source consisting of a string of delimited data.

Once you bring in the data, you want to parse that data out into the individual components. Here’s an example of name, address, and phone number information delimited by the ";" character.


Here’s how you can parse this information using an Excel formula (see if you can mentally follow along with this insanity):

For the first field, to extract the leftmost item (the person’s name), you would simply use a LEFT function in the formula.

"=LEFT(A2,FIND(";",A2,1)-1)"

Here’s how this logic works:

  • Searches the text string from A2
  • Finds the ";" delimiter symbol
  • Subtracts one for the proper location of the end of that string section
  • Grabs the leftmost text to that point

In this case, the leftmost text is "Ryan". Mission accomplished.

3. Nested Formula in Excel

But what about the other sections?

There may be easier ways to do this, but since we want to try and create the craziest Nested Excel formula possible (that actually works), we’re going to use a unique approach.

To extract the parts on the right, you need to nest multiple RIGHT functions to grab the section of text up until that first ";" symbol, and perform the LEFT function on it again. Here’s what that looks like for extracting the street number part of the address.

"=LEFT((RIGHT(A2,LEN(A2)-FIND(";",A2))),FIND(";",(RIGHT(A2,LEN(A2)-FIND(";",A2))),1)-1)"

It looks crazy, but it’s not hard to piece together. All I did is took this function:

RIGHT(A2,LEN(A2)-FIND(";",A2))

And inserted it into every place in the LEFT function above where there’s an "A2".

This correctly extracts the second section of the string.

Each subsequent section of the string needs another nest created. Now all you need to do is take the "RIGHT" equation that you created in the last section, and paste it into a new RIGHT formula with the previous RIGHT formula pasted into it where you see "A2". Here’s what that looks like.

(RIGHT((RIGHT(A2,LEN(A2)-FIND(";",A2))),LEN((RIGHT(A2,LEN(A2)-FIND(";",A2))))-FIND(";",(RIGHT(A2,LEN(A2)-FIND(";",A2))))))

Then, you need to take THAT formula and place it into the original LEFT formula wherever there’s an "A2".

The final mind-bending formula looks like this:

"=LEFT((RIGHT((RIGHT(A2,LEN(A2)-FIND(";",A2))),LEN((RIGHT(A2,LEN(A2)-FIND(";",A2))))-FIND(";",(RIGHT(A2,LEN(A2)-FIND(";",A2)))))),FIND(";",(RIGHT((RIGHT(A2,LEN(A2)-FIND(";",A2))),LEN((RIGHT(A2,LEN(A2)-FIND(";",A2))))-FIND(";",(RIGHT(A2,LEN(A2)-FIND(";",A2)))))),1)-1)"

That formula correctly extracts "Portland, ME 04076" out of the original string.


To extract the next section, repeat the above process all over again.

Your Excel formulas can get really loopy, but all you’re doing is cutting and pasting long formulas into themselves, making long nests that still work.

Yes, this meets the requirement for "crazy". But let’s be honest, there is a much simpler way to accomplish the same thing with one function.

Just select the column with the delimited data, and then under the Data menu item, select Text to Columns.

This will bring up a window where you can split the string by any delimiter you want. Simply input ‘;‘ and you’ll see that the preview of your selected data changes accordingly.


In a couple of clicks, you can do the same thing as that crazy formula above… but where’s the fun in that?

Getting Crazy With Microsoft Excel Formulas

So there you have it. The above formulas prove just how over-the-top a person can get when creating Microsoft Excel formulas to accomplish certain tasks.

Sometimes those Excel formulas aren’t actually the easiest (or best) way to accomplish things. Most programmers will tell you to keep it simple, and that’s as true with Excel formulas as it is with anything else.

If you really want to get serious with using Excel, you’ll want to read through our beginner’s guide to using Microsoft Excel. It has everything you need to start boosting your productivity with Excel. After that, make sure to consult our essential Excel functions cheat sheet for more guidance.

Image Credit: kues/Depositphotos

MUO – Feed

Comic for July 04, 2021

https://assets.amuniversal.com/ef5645f0a0e201396138005056a9545d

Thank you for voting.

Hmm. Something went wrong. We will take a look as soon as we can.

Dilbert Daily Strip

Why We Love Thermacell

https://cdn.thewirecutter.com/wp-content/media/2021/06/52-things-thermacell-2048px-0115-3×2-1.jpg?auto=webp&quality=60&width=630&dpr=2

Why We Love Thermacell

I hate bugs.

I hate them so much that when my husband suggests having dinner outside or playing a lawn game, I immediately start to wonder about the swarms of mosquitoes that will attack me.

How about a card game inside instead?

But ever since we started using Thermacell devices, I have happily said yes to the outdoors more often.

Wirecutter: Reviews for the Real World

Military-style gun confiscation hits a snag!

https://www.buckeyefirearms.org/sites/buckeyefirearms.org/files/styles/slideshow/public/field/image/Gun%20Pile.jpg?itok=0S9sTixg

by Gary Evens

The efforts of officials to confiscate military-style firearms in Massachusetts ran into trouble recently when armed militia groups confronted a government raid to seize a stockpile of guns and ammunition and arrest leading anti-government activists rumored to be in a small town outside of Boston.

The government forces were initially met by a small number of militia members in Lexington. After their show of force, the militia leader ordered his men to stand down and allow the government’s troops to pass. They were in the process of dispersing when a shot rang out. No one is sure just who fired that shot, but in response government troops opened fire, killing eight and wounding several others before their officers could regain control of the situation. Government forces then proceeded west towards their original destination of Concord, Massachusetts.

At Concord, the government troops spread out through the community searching for banned goods and the individuals they had been instructed to arrest. One group headed toward William Barret’s farm where it was reported that a stockpile of guns and ammunition was being collected. Meanwhile, some prohibited items were found in the town and set on fire in a vacant lot. However, the fire soon spread to a nearby building and the resulting smoke led some militia leaders that had assembled their men in the area to believe the town was being deliberately burned down. They began advancing and confronted a group of government troops at a bridge on the north side of the town. A brisk exchange of gunfire resulted in about a dozen casualties and government forces retreating back towards the center of town.

At this point, the raid’s leaders decided it would be best to return to Boston rather than continuing on their mission. During the subsequent retreat, an estimated seventy troops were killed and about two hundred were wounded as thousands of militiamen from the area rushed to confront the retreating government forces.

Following the abortive raid, an investigation was launched into why it had failed. The raid had been planned in the utmost secrecy, with the troops and leaders learning of their mission only at the last possible moment. Still word leaked out, probably by someone that overheard the planning of the raid at the governor’s mansion. Knowledge of the potential raid quickly spread to militia leaders but the exact target of the raid was not known. The individual that leaked the information about the raid was never identified.

This most recent raid was part of a trend that started last year when a law was passed banning the importation of military-style firearms and ammunition into the state. Subsequently, government forces began conducting warrantless searches for guns and ammunition. A successful raid was conducted on September 1, when a stockpile of ammunition was seized from a site about six miles northwest of Boston. A similar effort to seize ammunition stockpiles occurred in Williamsburg, Virginia. Rumors quickly spread that the government was deliberately trying to deny citizens the ability to acquire ammunition. Hoarding and shortages soon followed.

These initial successful efforts led the Massachusetts and Virginia governors to order further raids. A second attempt to seize illegal guns and ammunition was aimed at the Salem community. This one failed when local citizens learned of the raid and took efforts to block roads and bridges, preventing government officials from reaching the town.

Gun control efforts in Massachusetts increased in response to protests in Boston resulting from raising taxes and harsh treatment by government officials. This latest series of protests turned violent a few years ago when government officials opened fire on a crowd, killing five, including one black man. A couple of years later another group of protesters seized control of an embargoed shipment of goods pending payment of import taxes. Although the protest was non-violent, several thousand dollars in goods were destroyed. In an effort to restore order, Massachusetts’ governor imposed martial law in the area immediately around Boston and ordered the confiscation of firearms and ammunition.

In response to the governor’s action, Massachusetts gun rights leaders pointed to a resolution that was voted on almost ten years ago that stated every citizen was entitled to possess a firearm for their own personal protection and to defend the state from outside attack. They said that the government’s latest efforts fly in the face of long-standing tradition that people have the right to defend themselves.

[Author’s Note: You probably have not heard about these incidents in any of the major news outlets. However, they all happened, just not recently. Instead they occurred in the late eighteenth century and involved the events surrounding the Boston Massacre (1770), the Boston Tea Party (1773), and the Battles of Lexington and Concord (1775). Even then, gun control was used in an attempt to control the rights of citizens to protest government actions.]

Buckeye Firearms Association

Comic for July 01, 2021

https://assets.amuniversal.com/2f2280d0b1d401396577005056a9545d

Thank you for voting.

Hmm. Something went wrong. We will take a look as soon as we can.

Dilbert Daily Strip

How Tennis Rackets Are Made

http://img.youtube.com/vi/YVs-Suu-ljE/0.jpg

How Tennis Rackets Are Made

Link

Yonex is one of the most respected brands in tennis, and their rackets are the choice of many pro players. Tennis Warehouse takes us inside the Japanese company’s warehouse for a look at their production process, which seamlessly blends a human and robotic workforce.

The Awesomer

How to Build Your Own Rain Barrel

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/3f215c88231ce9686e4b107e68becf22.jpg

My sustainable homestead is evolving—and the new addition to the ever-growing project involves using rain barrels to provide my chickens with drinking water, irrigate my garden, and keep my compost pile moist.

Luckily for me, my local municipality teamed up with our state college to offer residents classes and incentives to help grow our community’s conservation effort (you can check with your local government to see if they offer anything similar). Through the program, I was able to purchase a 55-gallon rain barrel for just $37—a deal so good I opted to purchase three barrels. The barrels were guaranteed to be food-grade, which meant I avoided the toxic residuals that might have been lurking in any old barrel. Instead, my barrel had been used exclusively to store juice, so it was actually designed to withstand both the pressure and weight of 55 gallons of liquid, which weighs roughly just under 500 pounds.

The sweet juice residuals meant I needed to clean the barrel out with a solution, though. You can use a solution of one ounce of bleach to five gallons of water or, as I did, opt for a vinegar and baking soda alternative. However you get the job done, you’ll want to make sure the barrel is fresh and clean before you start collecting water in it.

Here are a few things I’ve learned throughout the process:

  • You don’t need a water pump to get the water out if you use gravity to your advantage and place the barrel on a raised base.
  • You want your base to be level and balanced.
  • 55 gallons of water is very heavy.
  • You’ll need to use fine mesh as a barrier at every entry point you create; otherwise, debris can clog everything up, and bugs are attracted to the water.
  • It’s important to avoid placing your barrel in direct sunlight because algae will grow inside it. You can also paint your barrel to keep the light out.

The build itself is rather simple: Rain barrels have inlets into which you direct a water source—you can direct the water from your gutter system by modifying your downspout to pour directly into the inlet, for example. Add another hole toward the top of the barrel for overflow and plan to direct that water away from your foundation—or into another barrel.

Next, you’ll need to cut a hole toward the bottom of the barrel and install a spigot. From the spigot, you can use a garden hose to direct the water to wherever you want it to go. How high you place the barrel will determine how much pressure you are going to get.

G/O Media may get a commission

   

Lifehacker

Another Recall: Herter’s 9mm Lots Added to List of Defective Ammo

https://www.thefirearmblog.com/blog/wp-content/uploads/2021/06/hr1-180×180.jpg

On the heels of a recent Winchester and Browning-branded 9mm recall, now certain lots of Herter's ammo have been added to the list.TFB recently reporting on the announcement of a safety recall for certain lots of Winchester and Browning 9mm ammunition. The 115-grain rounds in question, manufactured for these brands in East Alton, Illinois by the Olin Corporation, are subject to a factory defect causing the powder to burn improperly. This can cause what is known as […]

Read More …

The post Another Recall: Herter’s 9mm Lots Added to List of Defective Ammo appeared first on The Firearm Blog.

The Firearm Blog

Couple Builds $30K Garage for $6K, Using Prefab Quonset Hut Manufacturer

https://s3files.core77.com/blog/images/1197497_81_109313_WaOdEJNif.jpg

After years of living in NYC, Jean and Joe moved to Minneapolis, where they could afford to build a house. But one thing that wasn’t in their budget was the freestanding garage required by local housing ordinances. They took bids from contractors, and the price for building a garage from scratch came in at $30,000. Their story was captured by Fair Companies in the video below.

To summarize the garage story: After doing some research, Jean found a company in Canada that manufacturers Quonset huts to custom sizes. While she doesn’t mention the company by name, I looked at several fitting that description and believe they went with Mississauga-based Metal Pro Buildings.

MPB cranks out prefabricated sheet metal arches to whatever dimensions you need. They’re shipped to you in pieces, and all you need to do is bolt each arch together, stand them up, bolt them to each other, then bolt the end pieces on.

By going with the prefabricated Quonset hut approach and DIY assembly, Jean and Joe paid just $6,000, versus the $30,000 cost of a stick-built garage. (One thing they don’t mention in the video is the cost of the concrete slab, which they apparently did have in their budget.)

While the "shotgun"-style layout dictated by their plot seems inconvenient, I’m amazed that you can get a two-car garage for six grand. If you’re seeking a similarly cheap outbuilding, you can check out MPD’s different Quonset models (it looks like Jean and Joe went with the S-Series, but there are five styles total) here.

Core77

Using the Bridge Pattern in Laravel

https://ashallendesign.ams3.digitaloceanspaces.com/public/blog/23/using-the-strategy-pattern-in-laravel.png

Introduction

In software and web development, it’s always important to write code that is maintainable and extendable. The solution that you first create will likely change over time. So, you need to make sure you write your code in a way that doesn’t require a whole rewrite or refactor in the future.

The strategy pattern can be used to improve the extendability of your code and also improve the maintainability over time.

Intended Audience

This post is written for Laravel developers who have an understanding of how interfaces work and how to use them to decouple your code. If you’re a little unsure about this subject, check out my post from last week that discusses using interfaces to write better PHP code.

It’s also strongly advised that you have an understanding of dependency injection and how the Laravel service container works.

What Is the Strategy Pattern?

Refactoring Guru defines the strategy pattern as a “behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.”. This might sound a bit scary at first, but I promise that it’s not as bad as you think. If you want to read more into design patterns, I’d highly recommend checking out Refactoring Guru. They do a great job of explaining the strategy pattern in depth as well as other structural patterns.

The strategy pattern is basically a pattern that helps us to decouple our code and make it super extendable. In fact, you probably use it every day with Laravel without even noticing whenever you use the Storage and Cache facades (and a few other places too). Let’s say that you use this code:

Cache::put('name', 'Ash Allen', 600);

The code above is resolving a class from the service container by using the facade. I won’t get into how facades work as it’s not really the purpose of this article, but the important bit to know is that the Cache facade here is binding an interface (Illuminate\Contracts\Cache\Factory to be specific) to a class and using it. It is then storing the word ‘Ash Allen’ under the key ‘name’ for 10 minutes.

As you’ll have probably noticed in the Laravel documentation and in your project’s config, Laravel supports a few different drivers for caching, including: Redis, DynamoDB, Memcached and the database. So, for example, if we were to set our cache driver in our .env file to CACHE_DRIVER=redis, when we run our code snippet above, the data would be stored in our Redis cache. However, if we were to change the driver to be CACHE_DRIVER=database, this would result in data being stored in the database instead.

Each different cache driver has it’s own respective class that deals with how the framework interacts with the cache. So, when we change the driver in our .env, Laravel needs to know which driver to use. This is where the strategy pattern steps in. Under the hood, whenever we use the Cache facade, Laravel is actually resolving an Illuminate\Contracts\Cache\Factory interface from the service container. It does this by checking the config value (e.g. redis, database, etc.) and then mapping that interface to a class. For example, whenever we have our cache driver set to CACHE_DRIVER=redis and we try to resolve the Factory interface, we will get a class that specifically interacts with the Redis cache and nothing else.

As you can see, the strategy pattern can improve the extendability of your code. For example, if we wanted to create our own custom cache driver, we could just create the implementation and then let Laravel know that it is available for using. For a bit more context, check out the Laravel documentation to see an example of how you can add your own driver.

Using the Strategy Pattern in Laravel

Now that we have a basic idea of what the strategy pattern is, let’s look at how we can use it ourselves in our own Laravel application.

Let’s imagine that we have a Laravel application that users can use for getting exchange rates and currency conversions. Now, let’s say that our app uses an external API (exchangeratesapi.io) for getting the latest currency conversions.

We could create this class for interacting with the API:

class ExchangeRatesApiIO
{
    public function getRate(string $from, string $to): float
    {
        // Make a call to the exchangeratesapi.io API here and fetch the exchange rate.

        return $rate;
    }
}

Now, let’s use this class in a controller method so that we can return the exchange rate for a given currency. We’re going to use dependency injection to resolve the class from the container:

class RateController extends Controller
{
    public function __invoke(ExchangeRatesApiIO $exchangeRatesApiIO): JsonResponse
    {
        $rate = $exchangeRatesApiIO->getRate(
            request()->from,
            request()->to,
        );

        return response()->json(['rate' => $rate]);
    }
}

This code will work as expected, but we’ve tightly coupled the ExchangeRatesApiIO class to the controller method. This means that if we decide to migrate over to using a different API, such as Fixer, in the future, we’ll need to replace everywhere in the codebase that uses the ExchangeRatesApiIO class with our new class. As you can imagine, in large projects, this can be a slow and tedious task sometimes. So, to avoid this issue, instead of trying to instantiate a class in the controller method, we can use the strategy pattern to bind and resolve an interface instead.

Let’s start by creating a new ExchangeRatesService interface:

interface ExchangeRatesService
{
    public function getRate(string $from, string $to): float;
}

We can now update our ExchangeRatesApiIO class to implement this interface:

class ExchangeRatesApiIO implements ExchangeRatesService
{
    public function getRate(string $from, string $to): float
    {
        // Make a call to the exchangeratesapi.io API here and fetch the exchange rate.

        return $rate;
    }
}

Now that we’ve done that, we can update our controller method to inject the interface rather than the class:

class RateController extends Controller
{
    public function __invoke(ExchangeRatesService $exchangeRatesService): JsonResponse
    {
        $rate = $exchangeRatesService->getRate(
            request()->from,
            request()->to,
        );

        return response()->json(['rate' => $rate]);
    }
}

Of course, we can’t instantiate an interface; we want to instantiate the ExchangeRatesApiIO class. So, we need to tell Laravel what to do whenever we try and resolve the interface from the container. We can do this by using a service provider. Some people prefer to keep things like this inside their AppServiceProvider and keep all of their bindings in one place. However, I prefer to create a separate provider for each binding that I want to create. It’s purely down to personal preference and whatever you feel fits your workflow more. For this example, we’re going to create our own service provider.

Let’s create a new service provider using the Artisan command:

php artisan make:provider ExchangeRatesServiceProvider

We’ll then need to remember to register this service provider inside the app/config.php like below:

return [
    
    'providers' => [
        // ...
        \App\Providers\ExchangeRatesServiceProvider::class,
        // ...
    ],
	
]

Now, we can add our code to the service provider to bind the interfaces and class:

class ExchangeRatesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ExchangeRatesService::class, ExchangeRatesApiIO::class);
    }
}

Now that we’ve done all of this, when we dependency inject the ExchangeRatesService interface in our controller method, we’ll receive an ExchangeRatesApiIO class that we can use.

Taking It Further

Now that we know how to bind an interface to a class, let’s take things a bit further. Let’s imagine that we want to be able to decide whether to use the ExchangeRatesAPI.io or the Fixer.io API whenever we’d like just by updating a config field.

We don’t have a class yet for dealing with the Fixer.io API yet, so let’s create one and make sure that it implements the ExchangeRatesService interface:

class FixerIO implements ExchangeRatesService
{
    public function getRate(string $from, string $to): float
    {
        // Make a call to the Fixer API here and fetch the exchange rate.

        return $rate;
    }
}

We’ll now create a new field in our config/services.php file:

return [

    //...

    'exchange-rates-driver' => env('EXCHANGE_RATES_DRIVER'),

];

We can now update our service provider to change which class will be returned whenever we resolve the interface from the container:

class ExchangeRatesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ExchangeRatesService::class, function ($app) {
            if (config('services.exchange-rates-driver') === 'exchangeratesapiio') {
                return new ExchangeRatesApiIO();
            }
		  
            if (config('services.exchange-rates-driver') === 'fixerio') {
                return new FixerIO();
            }
		  
            throw new Exception('The exchange rates driver is invalid.');
        });
    }
}

Now if we set our exchanges rates driver in our .env to EXCHANGE_RATES_DRIVER=exchangeratesapiio and try to resolve the ExchangeRatesService from the container, we will receive an ExchangeRatesApiIO class. If we set our exchanges rates driver in our .env to EXCHANGE_RATES_DRIVER=fixerio and try to resolve the ExchangeRatesService from the container, we will receive an FixerIO class. If we set driver to anything else accidentally, an exception will be thrown to let us know that it’s incorrect.

Due to the fact that both of the classes implement the same interface, we can seamlessly change the EXCHANGE_RATES_DRIVER field in the .env file and not need to change any other code anywhere.

Conclusion

Is your brain fried yet? If it is, don’t worry! Personally, I found this topic pretty difficult to understand when I first learnt about it. I don’t think I started to really understand it until I put it into practice and used it myself. So, I’d advise spending a little bit of time experimenting with this yourself. Once you get comfortable with using it, I guarantee that you’ll start using it in your own projects.

Hopefully, this article has given you an overview of what the strategy pattern is and how you can use it in Laravel to improve the extendability and maintainability of your code.

If you found this post useful, I’d love to hear about it in the comments.

Keep on building awesome things! 🚀

Laravel News Links