Giter Site home page Giter Site logo

spatie / macroable Goto Github PK

View Code? Open in Web Editor NEW
675.0 9.0 25.0 81 KB

A trait to dynamically add methods to a class

Home Page: https://freek.dev/857-a-trait-to-dynamically-add-methods-to-a-class

License: MIT License

PHP 100.00%
php macros utility runtime

macroable's Introduction

A trait to dynamically add methods to a class

Latest Version on Packagist run-tests Total Downloads

This package provides a trait that, when applied to a class, makes it possible to add methods to that class at runtime.

Here's a quick example:

$myClass = new class() {
    use Spatie\Macroable\Macroable;
};

$myClass::macro('concatenate', function(... $strings) {
   return implode('-', $strings);
});

$myClass->concatenate('one', 'two', 'three'); // returns 'one-two-three'

The idea of a macroable trait and the implementation is taken from the macroable trait of the Laravel framework.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/macroable

Usage

You can add a new method to a class using macro:

$macroableClass = new class() {
    use Spatie\Macroable\Macroable;
};

$macroableClass::macro('concatenate', function(... $strings) {
   return implode('-', $strings);
});

$macroableClass->concatenate('one', 'two', 'three'); // returns 'one-two-three'

Callables passed to the macro function will be bound to the class

$macroableClass = new class() {
    
    protected $name = 'myName';
    
    use Spatie\Macroable\Macroable;
};

$macroableClass::macro('getName', function() {
   return $this->name;
};

$macroableClass->getName(); // returns 'myName'

You can also add multiple methods in one go by using a mixin class. A mixin class contains methods that return callables. Each method from the mixin will be registered on the macroable class.

$mixin = new class() {
    public function mixinMethod()
    {
       return function() {
          return 'mixinMethod';
       };
    }
    
    public function anotherMixinMethod()
    {
       return function() {
          return 'anotherMixinMethod';
       };
    }
};

$macroableClass->mixin($mixin);

$macroableClass->mixinMethod() // returns 'mixinMethod';

$macroableClass->anotherMixinMethod() // returns 'anotherMixinMethod';

Changelog

Please see CHANGELOG for more information on what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package (it's MIT-licensed), but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

Idea and code is taken from the macroable trait of the Laravel framework.

License

The MIT License (MIT). Please see License File for more information.

macroable's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

macroable's Issues

Macro test trait

What you think about a macro test trait, to check if a class is macroable

What is the usecase?

Hey guys!

Not sure if this is the right place for this but I am really interested for use cases you encountered where you want this.

The idea itself is very interesting.

Unable to use ray on docker with PHP 7.4 (php:7.4.9-fpm-alpine image)

Hi guys,

I can't use ray in docker container when i use php version 7.4 (php:7.4.9-fpm-alpine), but i have'nt any problems with php version 8.0.

I really can't update all this project for php 8.0 .
Can you help me??
During class fetch: Uncaught ParseError: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /var/www/html/vendor/spatie/macroable/src/Macroable.php:14 Stack trace: #0 /var/www/html/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/var/www/html/v...') #1 [internal function]: Composer\Autoload\ClassLoader->loadClass('Spatie\\Macroabl...') #2 /var/www/html/vendor/spatie/ray/src/Ray.php(50): spl_autoload_call('Spatie\\Macroabl...') #3 /var/www/html/vendor/composer/ClassLoader.php(480): include('/var/www/html/v...') #4 /var/www/html/vendor/composer/ClassLoader.php(346): Composer\Autoload\includeFile('/var/www/html/v...') #5 [internal function]: Composer\Autoload\ClassLoader->loadClass('Spatie\\Ray\\Ray') #6 /var/www/html/vendor/spatie/laravel-ray/src/Ray.php(41): spl_autoload_call('Spatie\\Ray\\Ray') #7 /var/www/html/vendor/composer/ClassLoader.php(480): include('/var/www/html/v...')

Small typo

Concatinate should be spelled concatenate.

error

getting this error after updating

PHP Fatal error:  During class fetch: Uncaught ParseError: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /vendor/spatie/macroable/src/Macroable.php:14

Parent macros get overriden by descendants

The current mechanism overrides the parent's macros when using the same name. Check this test for example:

Class A {
    use Macroable;
}

class B extends A {}

it('should not override parent macros', function () {
    A::macro('test', function () {
        return 'A';
    });

    B::macro('test', function () {
        return 'B';
    });

    $this->assertEquals('A', A::test());
    $this->assertEquals('B', B::test());
});

The first assertion will fail. That's actually a side-effect of a bigger issue - all of the class descendants will share the same macros object instead of having their own object and just inherit from the parent when needed (like pure OOP).

I'm not sure how we can solve this. The only way that came to my mind is to change the macros object structure a little bit, maybe something like this:

protected $macros = [
    'Namespace\To\Class\A' => [
        'testMacro' => function () {
            return 'A';
        },
        'shouldBeInherited' => function () {
            return 'A';
        },
    ],
    'Namespace\To\Class\B' => [
        'testMacro' => function () {
            return 'B';
        },
    ],
];

And then when calling the macro, maybe use ReflectionClass::getParentClass() recursively, but it feels kinda complicated. WDYT?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.