Search

Laravel 5 Macros: Injecting Class-Based Macros With mixin

April 21, 2018 —John Koster

The mixin static method is used to load the methods of a mixin class instance into the target class as macro methods. The mixin method accepts a class instance as its first and only argument.

#Signature

The signature of the mixin method is:

1public static function mixin(
2 $mixin
3);

#Example Use

In the following example, we will define a new string mixin class StringEncryptionMixins that will provide access to Laravel's encryption features through the Illuminate\Support\Str class:

1class StringEncryptionMixins
2{
3 public function encrypt()
4 {
5 return function ($str) {
6 return encrypt($str);
7 };
8 }
9 
10 public function decrypt()
11 {
12 return function ($str) {
13 return decrypt($str);
14 };
15 }
16}

After we have defined our mixin class, we can add it to the Str class like so:

1use Illuminate\Support\Str;
2 
3Str::mixin(new StringEncryptionMixins);

After our mixin class has been loaded into the Str class, the methods defined in the mixin class would become available via static methods of the Str class:

1use Illuminate\Support\Str;
2 
3// Encrypt a string.
4$encrypted = Str::encrypt('string value');
5 
6// Decrypt a string.
7$decrypted = Str::decrypt($encrypted);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.