Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Freek Van der Herten:
A trait to dynamically add methods to a class
Sep 25, 2017 @ 10:50:51

Freek Van der Herten has posted about a new package that's essentially a stand-alone version of Laravel's own "macros" functionality available via a package: macroable.

We recently released our newest package called macroable. It contains a trait that, when applied to class, can dynamically add methods to that class. This trait is basically a stand alone version of the macroable trait in Laravel. In this post I’d like to show you how you can use it, how it works behind the scenes and explain why we created it.

He then gives examples of how it can be used to add a new simple method (essentially a "named closure") and using the "mixin" functionality to add multiple at once. He wraps up the post with a look at how it works behind the scenes, adding the items to a "macros" list and then looking them up if they're not defined on the class.

tagged: package macroable macro trait laravel standalone

Link: https://murze.be/2017/09/trait-dynamically-add-methods-class/

Nicola Malizia:
Understanding The Laravel Macroable Trait
Feb 14, 2017 @ 10:53:45

In this post to his site Nicola Malizia briefly helps you understand the Laravel "macroable" trait - what it is and how to can be used in your own code.

If you check the Laravel codebase I’m sure that you can observe that Laravel makes use of traits.

There is one trait in the source code that pulls my attention. I’m talking about the Macroable trait. In case you don’t know, you can define custom responses using macros.

He includes an example of extending the default Response class with a "caps" macro and how it would then be used in the resulting object. He talks about how traits work in PHP OOP code and how they can be used to "inherit" functionality into a class. The "macroable" trait then uses the __call magic method to do its thing, looking for macros that match the function being called.

tagged: macro macroable trait laravel example tutorial

Link: https://unnikked.ga/understanding-the-laravel-macroable-trait-dab051f09172#.g5xrqlk5s