php中使用macro宏

PHP Macro

The PHP Macro package offers closure (anonymous function) based setter dependency injection by providing a trait which can be included into any class.

composer req aimeos/macro

This package is for application, framework and library developers who want to allow customizing the behavior of their code by their users.

Why macros

In applications, frameworks or libraries which are build for customization it’s necessary to allow overwriting existing functionality to be able customize its behavior. This is where macros are very handy because they can add custom code using closures.

With the PHP Macro package, you can also allow users to overwrite methods in base classes without forcing your users to extend these classes. The PHP Macro package uses NO reflection or other hacks, just pure PHP methods.

There are some pros and cons when compared to class based depencency injection:

Pro:

  • Less code to write and much easier to implement for simple stuff
  • Custom closures can be inherited and overwritten like class methods

Con:

  • Limited static code analysis possibilities
  • Anonymous function can not be forced to implement an interface

Thus, it's not a replacement for class based depencency injection but a lightweight addition for small extension points where full-blown dependency injection using classes implementing interfaces are too much work.

Allow customization

The result of existing methods can be modified if the original method checks for an existing macro and use that instead its own implementation:

// original code

class Order
{
    use Aimeos\Macro\Macroable;

    private $id = '123';

    public function getOrderNumber()
    {
        $fcn = static::macro( 'orderNumber' );
        return $fcn ? $fcn( $this->id ) : $this->id;
    }
};

Now, you can add your custom orderNumber macro that will be used instead:

// user code

Order::macro( 'orderNumber', function( string $id ) {
   return date( 'Y' ) . '-' . $id;
} );

(new Order)->getOrderNumber(); // now returns '2020-123'

Thus, you can generate own output or pass a different result to subseqent methods within the application.

Access class properties

When macros are called in an object context, they can also access class properties:

// original code

class A
{
    use Aimeos\Macro\Macroable;
    private $name = 'A';
};

Here, the private property $name is available in the macro:

// user code

A::macro( 'concat', function( array $values ) {
   return $this->name . ':' . implode( '-', $values );
} );

(new A)->concat( ['1', '2', '3'] ); // returns 'A:1-2-3'

The macro can use the property as input for creating the returned value.

Use inherited macros

The PHP macro package also allows to inherit macros from parent classes. Then, they can access class properties of the child class just like regular class methods:

// original code

class A
{
    use Aimeos\Macro\Macroable;
    private $name = 'A';
};

class B extends A
{
    private $name = 'B';
};

Macros added to the parent class will be available in child classes too:

// user code

A::macro( 'concat', function( array $values ) {
   return $this->name . ':' . implode( '-', $values );
} );

(new B)->concat( ['1', '2', '3'] ); // returns 'B:1-2-3'

Class B extends from class A but provides a different $name property. The macro inherited from class A will now use the property of class B.

Overwrite inherited macros

It's also possible to overwrite macros inherited from parent classes as it's possible with regular class methods:

// original code

class A
{
    use Aimeos\Macro\Macroable;

    public function do() {
        return static::macro( 'concat' )( [1, 2, 3] );
    }
};

class B extends A {};

class C extends A {};

Now you can add macros to the parent class and one of the child classes:

// user code

A::macro( 'concat', function( array $values ) {
   return implode( ',', $values );
} );

C::macro( 'concat', function( array $values ) {
   return implode( '-', $values );
} );

(new B)->do(); // returns '1,2,3'

(new C)->do(); // returns '1-2-3'

This enables you to add special handling for single classes even if all other classes still use the macro added to class A.

Overwrite protected methods

Base classes often offer a set of methods that are used by the child classes. In PHP, replacing the methods of a base class is impossible and thus, you have to overwrite each child class with your own implementation.

To avoid that, the original method can use the call() method instead of calling the method of the parent class directly:

// original code

class A
{
    use Aimeos\Macro\Macroable;

    protected function getName( $prefix )
    {
        return $prefix . 'A';
    }
};

class B extends A
{
    public function do()
    {
        return $this->call( 'getName', 'B-' );
    }
};

This will check if there's a macro getName available and will call that instead of the getName() method:

// user code

(new B)->do(); // returns 'B-A'

A::macro( 'getName', function( $prefix ) {
   return $this->getName( $prefix ) . '-123';
} );

(new B)->do(); // returns 'B-A-123'

The original getName() method can still be used in the macro.

Reset macros

Sometimes, it may be necessary to remove macros from objects, especially when running automated tests. You can unset a macro by using:

class A
{
    use Aimeos\Macro\Macroable;
};

// add macro
A::macro( 'test', function() {
   return 'test';
} );

// remove macro
A::unmacro( 'test' );
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市灶平,隨后出現(xiàn)的幾起案子罐监,更是在濱河造成了極大的恐慌弓柱,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異酿箭,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)妇蛀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門古程,熙熙樓的掌柜王于貴愁眉苦臉地迎上來挣磨,“玉大人塘砸,你說我怎么就攤上這事∨危” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我膛壹,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮割卖,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘丙挽。我一直安慰自己颜阐,他們只是感情好瑰艘,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開白布弊琴。 她就那樣靜靜地躺著,像睡著了一般腋寨。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上查刻,一...
    開封第一講書人閱讀 51,482評(píng)論 1 302
  • 那天佃延,我揣著相機(jī)與錄音,去河邊找鬼尺棋。 笑死烘浦,一個(gè)胖子當(dāng)著我的面吹牛脊阴,可吹牛的內(nèi)容都是我干的品擎。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼蹭睡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起琼锋,我...
    開封第一講書人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤恰力,失蹤者是張志新(化名)和其女友劉穎很钓,沒想到半個(gè)月后锭碳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體补疑,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡撵孤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡昂勉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情库菲,我是刑警寧澤奇颠,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響诞吱,放射性物質(zhì)發(fā)生泄漏咙俩。R本人自食惡果不足惜坛猪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望搜立。 院中可真熱鬧颠通,春花似錦启搂、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春题禀,著一層夾襖步出監(jiān)牢的瞬間全庸,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來泰國打工氓英, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留徘键,地道東北人虚青。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像句惯,于是被迫代替她去往敵國和親蒙保。 傳聞我的和親對(duì)象是個(gè)殘疾皇子扁瓢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 在gdb中鍵入help all可以看到所有g(shù)db-peda組件的命令玖雁。復(fù)制粘貼如下以備查: Command cla...
    飛熊先生閱讀 2,539評(píng)論 0 0
  • 在iOS開發(fā)過程中, 我們可能會(huì)碰到一些系統(tǒng)方法棄用, weak劲厌、循環(huán)引用遵绰、不能執(zhí)行之類的警告。 有代碼潔癖的孩子...
    夢翔_d674閱讀 2,383評(píng)論 0 3
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,331評(píng)論 0 10
  • 前言 通過閱讀別人的優(yōu)秀源碼,你會(huì)發(fā)現(xiàn)別人的開源API設(shè)計(jì)中,有一些宏你是經(jīng)常忽略的,或者你不知道的。通過這些宏,...
    gitKong閱讀 5,166評(píng)論 5 41
  • 說明本次redis集群安裝在rhel6.8 64位機(jī)器上吉拳,redis版本為3.2.8炼邀,redis的gem文件版本為...
    讀或?qū)?/span>閱讀 14,738評(píng)論 3 9