基于表的驱动数据解释

0.3.0 2019-03-24 02:03 UTC

This package is auto-updated.

Last update: 2024-09-24 14:49:32 UTC


README

CircleCI codecov

Mesa 是一个程序性表格构建器和/或解释器。

安装

composer require nathanburkett/mesa

使用

通过 GeneratesTables 特性

使用 GeneratesTables 特性是开始使用表格的最简单方式。

<?php namespace Foo\Bar\Baz;

use NathanBurkett\Mesa\GeneratesTables;

class FooClass
{
    use GeneratesTables;
}

然后通过调用以下方法构建表格

<?php namespace Foo\Bar\Baz;

use NathanBurkett\Mesa\GeneratesTables;

class FooClass
{
    use GeneratesTables;
    
    public function run(): iterable
    {
        $tableContext = __DIR__ . '/some/php/file.php';

        return $this->generateTable($tableContext);
    } 
}

$tableContext 是表格解释的数据源。

可以将一个可调用的函数作为 generateTable 的第二个参数传递,该函数将在每个表格迭代的值上运行,并将替换该值。

示例

<?php
// ./some/php/file.php

return [
    'one' => [
        'name' => 'foo',
    ],
    'two' => [
        'name' => 'bar',
    ],
];
<?php namespace Foo\Bar\Baz;

use NathanBurkett\Mesa\GeneratesTables;

class FooClass
{
    use GeneratesTables;
    
    public function run(): iterable
    {
        $tableContext = __DIR__ . '/some/php/file.php'; // THIS IS WHERE $tableContext COMES FROM

        return $this->generateTable($tableContext, function(array $row, $index) {
            if ($index === 'two') {
                $row['name'] = 'baz';
            }
            
            return $row;
        });
    } 
}

在上面的示例中,$table['two']['name'] 将等于 'baz'

加载器

$tableContext 作为第一个参数传递给 GeneratesTables::generateTable() 的当前默认行为是 PHP 或 YAML 文件的绝对路径。其他任何内容都会抛出异常。

可以通过扩展 LoaderFactory 并覆盖任何方法,然后覆盖 GeneratesTables::getLoaderFactory() 来解释其他类型。

<?php namespace Foo\Bar\Baz;

use NathanBurkett\Mesa\GeneratesTables;
use NathanBurkett\Mesa\Loader\LoaderFactoryInterface;

class FooClass
{
    use GeneratesTables;
    
    // ...
    
    protected function getLoaderFactory(): LoaderFactoryInterface
    {
        return new YourNewFactoryLoader();
    }
}

输出

一旦数据被读入表格,它将通过一个 OutputStrategy 输出。默认 OutputStrategy 通过生成器函数迭代表格并生成索引和值。

可以将一个可调用的函数作为第二个参数传递,该函数将在每个迭代的值上运行并替换迭代值。

可以将一个可调用的函数作为 generateTable 的第二个参数传递,该函数将在每个表格迭代的值上运行,并将替换该值。

示例

<?php
// ./some/php/file.php

return [
    'one' => [
        'name' => 'foo',
    ],
    'two' => [
        'name' => 'bar',
    ],
];
<?php namespace Foo\Bar\Baz;

use NathanBurkett\Mesa\GeneratesTables;

class FooClass
{
    use GeneratesTables;
    
    public function run(): iterable
    {
        $tableContext = __DIR__ . '/some/php/file.php'; // THIS IS WHERE $tableContext COMES FROM

        return $this->generateTable($tableContext, function(array $row, $index) {
            if ($index === 'two') {
                $row['name'] = 'baz';
            }
            
            return $row;
        });
    } 
}

在上面的示例中,$table['two']['name'] 将等于 'baz'

可以通过覆盖 GeneratesTables::getOutputStrategy() 来使用替代 OutputStrategy。