Laravel Macroable Trait

kbzaman2

K B Zaman

Posted on November 5, 2021

Laravel Macroable Trait

Laravel is very popular with developers for its beautiful features. Macroable trait is one of its many beautiful features.

Definition in my language:

Speaking of this trait, I would like to say that it is a virtual method maker of class. That means there is a class in your project where you want to call some methods dynamically, but those methods do not have any physical presence in that class. In that case, you can get help from Macroable Trait.

How to use:

The first requirement to use this is to use the macroable trait in the class in which you want to create the macro. Then in the boot method of AppServiceProvider class, you have to write the code to create a macro of your class. A format of code is written below:

public function boot (){
    YourClass::macro('methodName', function ($arg)
        // Your method body and your code
    });
}
Enter fullscreen mode Exit fullscreen mode

Suppose you think Laravel's Str class should have a method to connect two strings. But there is no such method in this class. Then you can create your own method for this class, without making any changes anywhere in this class. Because Laravel has some classes that use the Macroable trait by default. Among them Str class one. I will give the list of classes below. So how do we create a method in Str class to concat? You have already seen a demo format. That is the format we will use now.

public function boot (){
    Str::macro('concat', function ($str1, $str2)
        return $str1. ' '. $str2;
    });
}
Enter fullscreen mode Exit fullscreen mode

Now if you write $str = Str::concat('My String 1', 'My String 2'); then you will see that the two strings are connected. This means that a virtual method has been created in this class without any change in the Str class.

How it works:

When you call the macro method in a class Macroable, it enters the static macro method of the Macroable Trait. I mentioned the method below:

public static function macro($name, $macro)
{
    static::macros[$name] = $macros;
}
Enter fullscreen mode Exit fullscreen mode

It registers custom macros and stores them in its static macro property. Here comes the name of the custom method in the name variable and the instance of Closure in the macro variable.
And when you call the custom method, the __call() and __callStatic() magic methods of Macroable Trait handle it dynamically.
There is one more feature called mixin in Macroable Trait. I will try to talk about it in a later post InshaAllah.

💖 💪 🙅 🚩
kbzaman2
K B Zaman

Posted on November 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Laravel Macroable Trait
php Laravel Macroable Trait

November 5, 2021