hoangphison/macroable

一个用于动态向类添加方法的特质

1.0.0 2017-11-24 10:14 UTC

This package is auto-updated.

Last update: 2024-09-12 21:33:58 UTC


README

Build Status StyleCI

此包提供了一种特质,当应用于类时,可以在运行时向该类添加方法。

以下是一个快速示例

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

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

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

可宏化特质的想法和实现来源于macroable 特质,它来自Laravel 框架

安装

您可以通过 composer 安装此包

composer require hoangphison/macroable

用法

您可以使用 macro 向类添加新方法

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

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

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

传递给 macro 函数的可调用项将被绑定到 class

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

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

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

您还可以通过使用混合类一次性添加多个方法。混合类包含返回可调用项的方法。混合类中的每个方法都将注册到可宏化类上。

$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';

变更日志

有关最近更改的更多信息,请参阅变更日志

测试

composer test

贡献

有关详细信息,请参阅贡献指南

安全

如果您发现任何安全问题,请通过电子邮件 freek@spatie.be 而不是使用问题跟踪器。

Postcardware

您可以自由使用此包(它是MIT 许可),但如果它进入了您的生产环境,我们非常欢迎您从家乡给我们寄一张明信片,提到您正在使用我们哪些包。

我们的地址是:Spatie,Samberstraat 69D,2060 安特卫普,比利时。

我们将在我们的公司网站上发布所有收到的明信片。

鸣谢

想法和代码来自macroable 特质,它来自Laravel 框架

支持我们

Spatie 是一家总部位于比利时的安特卫普的网页设计公司。您可以在我们的网站上找到所有开源项目的概述这里

您的业务是否依赖于我们的贡献?请联系我们,并在Patreon 上支持我们。所有承诺都将专门用于分配人力进行维护和新酷炫的功能。

许可证

MIT 许可证(MIT)。有关更多信息,请参阅许可证文件