xtompie/

flow

Flow 收集

1.2.0 2021-03-02 19:23 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:48 UTC


README

Flow 是构建丰富集合的方式,这些集合更好地描述业务语言。

Flow 提供

  • 从执行中分离出的定义,
  • 使用通用/业务语言的命名转换,
  • 封装,
  • 清洁、更易读的代码。

Flow 是不可变的。

示例

为了说明,让我们探讨各种实现选项

普通过程式

<?php

$animals = ['rat', 'cat', 'lion', 'puma', 'dog'];

// alfabetic 
sort($animals);

// pets
$animalPets = [];
$pets = ['cat', 'dog', 'rat'];
foreach ($animals as $animal) {
    if (in_array($animal, $pets)) {
        $animalPets = $animal; 
    }
}
$animals = $animalPets;

// pretty
foreach ($animals as $index => $animal) {
    $animals[$index] = ucfirst($animal);
}

// first
print_r($animals->get());

使用 Flow

<?php

use Xtompie\Flow\Flow;
use Xtompie\Flow\FlowFilter;
use Xtompie\Flow\FlowGet;
use Xtompie\Flow\FlowMap;
use Xtompie\Flow\FLowSort;

class Animals
{
    use Flow;
    use FlowFilter;
    use FlowGet;
    use FlowMap;
    use FLowSort;

    public function alfabetic()
    {
        return $this->sort();
    }
    
    public function pets()
    {
        $pets = ['cat', 'dog', 'rat'];
        return $this->filter(function($animal) use ($pets) {
            return in_array($animal, $pets);
        });
    }
    
    public function pretty()
    {
        return $this->map(function($animal) {
            return ucfirst($animal);
        });
    }
}

$animals = (new Animals(['rat', 'cat', 'lion', 'puma', 'dog']))
    ->alfabetic()
    ->pets()
    ->pretty()
;

print_r($animals->get());