lightster/named-sprintf

此包已弃用且不再维护。未建议替代包。

增强PHP的sprintf,支持Python风格的命名参数

v0.2.1 2019-03-11 06:01 UTC

This package is not auto-updated.

Last update: 2023-04-23 23:48:16 UTC


README

Build Status Test Coverage Code Climate

增强PHP的sprintf,支持Python风格的命名参数

要求

  • PHP >= 7.0
  • Composer

安装

composer require lightster/named-sprintf:dev-master

基本用法

<?php

use Lstr\Sprintf\Sprintf;

require_once __DIR__ . '/vendor/autoload.php';

$sprintf = new Sprintf();

echo $sprintf->sprintf(
    "Hello %(first_name)s %(last_name)s\n",
    ['first_name' => 'Matt', 'last_name' => 'Light']
);
?>

类型用法

类似于PHP内置的sprintf,可以在命名参数后传递类型和格式选项

<?php

$sprintf = new Sprintf();

echo $sprintf->sprintf(
    "PI is approximately %(pi).5f, or %(pi).8f if you need more accuracy\n",
    ['pi' => pi()]
);

echo $sprintf->sprintf(
    "The type is optional and defaults to string (e.g. 's'): %(name)\n",
    ['name' => 'Typeless!']
);
?>

中间件

可以通过将中间件传递给Sprintf的构造函数来在格式化之前处理值。中间件可以是任何类型的PHP调用者,并将传递即将格式化的参数名称以及一个可调用对象,该对象允许中间件访问传递给$sprintf->sprintf()的所有值。

以下示例将任何作为数组传递的参数转换为空格分隔的单词字符串,然后再将其传递给sprintf字符串格式化程序

<?php
$sprintf = new Sprintf(
    function ($name, callable $values) {
        $value = $values($name);

        if (is_array($value)) {
            return implode(' ', $value);
        }

        return $value;
    }
);

echo $sprintf->sprintf(
    "Middleware %(action_words) to pre-process %(what)!\n",
    [
        'action_words' => ['can', 'be', 'used'],
        'what'         => 'parameters',
    ]
);
?>

可重用中间件

可以通过扩展AbstractInvokable类来开发可重用、可链式的中间件。named-sprintf附带了一些可重用中间件。

Cli\Bundle 中间件

Cli\Bundle 中间件是一系列捆绑在一起的中间件,允许轻松生成命令行字符串。

<?php

use Lstr\Sprintf\Middleware\Cli\Bundle as CliBundle;

$sprintf = new Sprintf(new CliBundle());

echo $sprintf->sprintf(
    "php bin/some-cli %(sub-command) %(long-options) %(short-options)",
    [
        'sub-command'  => 'commit',
        'long-options' => [
            'message' => 'Showing off a CLI command',
            'author'  => 'Matt',
        ],
        'short-options' => [
            'a' => null,
        ],
    ]
) . "\n";
?>