composer require illuminate/macroable
<?phpuse Illuminate\Support\Traits\Macroable;class Greeting
{
    use Macroable;

    public function __construct(protected string $name)
    {
    }

    public function sayHello()
    {
        return sprintf('Hello %s%s', $this->name, PHP_EOL);
    }
}
Greeting::macro('greet', function (?string $greeting = null) {
    return !is_null($greeting)
        ? sprintf('%s %s%s', $greeting, $this->name, PHP_EOL)
        : $this->sayHello();
});
$greeting = new Greeting('Anik');// Calling class's method
echo $greeting->sayHello(); // "Hello Anik"// Calling the greet method, we defined using Class::macro
echo $greeting->greet('Good evening'); // "Good evening Anik"
echo $greeting->greet('Goodbye'); // "Goodbye Anik"
echo $greeting->greet(); // "Hello Anik"
Greeting::macro('whatTimeIsIt', function () {
    return sprintf(
        'Hey, it is %s',
        (new DateTimeImmutable())->format('H:i:s')
    );
});echo Greeting::whatTimeIsIt(); // "Hey, it is 06:47:52"
<?phpclass GreetingMixin
{
    public function greet()
    {
        return function (?string $greeting = null) {
            return $greeting 
               ? sprintf('%s %s%s', $greeting, $this->name, PHP_EOL)
               : $this->sayHello();
        };
    }

    public function whatTimeIsIt()
    {
        return function () {
            return sprintf(
                'Hey, it is %s',
                (new DateTimeImmutable())->format('H:i:s')
            );
        };
    }
}
Greeting::mixin(new GreetingMixin());
$greeting = new Greeting('Anik');// Class method
echo $greeting->sayHello(); // "Hello Anik"//Macro methods, added through ::mixin
echo $greeting->greet('Good evening'); // "Good evening Anik"
echo $greeting->greet('Goodbye'); // "Goodbye Anik"
echo $greeting->greet(); // "Hello Anik"

echo Greeting::whatTimeIsIt(); // "Hey, it is 07:02:01"

Laravel Macroable: 理解 macros 和 mixin
标签: