Courses

Design Patterns in Laravel 11

Manager: AuthManager, MailManager, CacheManager

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Understanding Manager pattern implementation in Laravel
- Examining AuthManager, MailManager, and CacheManager
- How Manager pattern handles different drivers
- Integration of Manager pattern with Singleton pattern

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 17 lessons of this course? (72 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord