Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Manager: AuthManager, MailManager, CacheManager

Premium
5 min read

This pattern is almost a follow-up to the previous lesson on Singleton. We just took a look at Singletons in Laravel, but one thing was constantly repeating:

$this->app->singleton('auth', fn ($app) => new AuthManager($app));
 
$this->app->singleton('mail.manager', function ($app) {
return new MailManager($app);
});
 
$this->app->singleton('cache', function ($app) {
return new CacheManager($app);
});

Why are there "Manager" classes repeating? Well, this is a Manager pattern used in Laravel.


Manager Pattern: What is it?

Before we dive into how the Manager pattern is used in Laravel, let's take a look at what the Manager pattern is.

The idea is to create the first class (Manager), responsible for managing the second class (Driver).

For example:

class ExportManager extends Manager
{
public function getDefaultDriver()
{
return 'csv';
}
 
public function createCsvDriver()
{
return new CsvParser();
}
 
public function createJsonDriver()
{
return new JsonParser();
}
}

While the Manager class comes from `Illuminate\Support\Manager' and handles driver creation, the Driver classes do the actual work.

So let's create a CsvParser class:

class CsvParser
{
public function parse(string $path): array
{
$file = fopen($path, 'r');
 
// Do the parsing here
 
fclose($file);
 
return $rows;
}
}

Note: Our JsonParser class would be similar to this one - just with JSON parsing logic.

Now we can create a singleton for the ExportManager:

$this->app->singleton('export', function ($app) {
return new ExportManager($app);
});

And then we can use it like this:

$export = app('export');
$export->driver('csv')->parse('file.csv');

While we can still improve this code for better implementation, this is the basic idea behind the Manager pattern.

Create a Manager class to manage the Driver classes. Then, use the Manager instance to consume/call the Driver classes.


Laravel AuthManager

In Laravel, the manager pattern appears in a few places. One of them is...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.