https://github.com/ledccn/macroable
通过PHP语言的trait特性,使用宏给一个类添加一个新方法
https://github.com/ledccn/macroable
Last synced: 11 months ago
JSON representation
通过PHP语言的trait特性,使用宏给一个类添加一个新方法
- Host: GitHub
- URL: https://github.com/ledccn/macroable
- Owner: ledccn
- Created: 2023-07-31T10:11:30.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2024-03-26T16:08:55.000Z (about 2 years ago)
- Last Synced: 2025-02-01T23:35:11.526Z (over 1 year ago)
- Language: PHP
- Homepage: httpw://www.iyuu.cn
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# 安装
```
composer require ledc/macroable
```
# 使用
```
macro('hello', function () {
echo 'hello Tests' . PHP_EOL;
});
$ts->hello();
$req = new Request();
$req->macro('hello', function () {
echo 'hello Request' . PHP_EOL;
});
$req->hello();
```
## Usage
You can add a new method to a class using `macro`:
```php
$macroableClass = new class() {
use Ledc\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`
```php
$macroableClass = new class() {
protected $name = 'myName';
use Ledc\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.
```php
$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';
```
# 最佳实践
- 宏指令方法不存在状态:用`Ledc\Macroable\Macroable`
- 宏指令方法存在状态或依赖上下文时,用:`Ledc\Macroable\Macro`
# 使用场景
| 特性trait | 使用场景 |
| -------------------------- | ------------------------------------------------- |
| `Ledc\Macroable\Macroable` | PHP-FPM,或宏指令方法无状态 |
| `Ledc\Macroable\Macro` | PHP-CLI,中间件内对请求对象注入方法(请求结束销毁) |