Courses

Design Patterns in Laravel 11

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

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 68 courses (1183 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord