stefna/php-code-builder

2.0.3 2024-09-12 13:47 UTC

This package is auto-updated.

Last update: 2024-09-12 13:48:53 UTC


README

安装

$ composer require stefna/php-code-builder

API

PhpFile

实际保存的文件。

方法

setStrict()

标记文件包含 declare(strict_types=1);

setNamespace(string $ns)

设置文件命名空间

setSource(string $code)

设置要包含在文件中的原始 PHP 代码

类似

$file = new PhpFile();
$file->setSource("spl_autoload_register('$autoloaderName');");
addFunction(PhpFunction $func)

将函数添加到文件。文件可以包含多个函数

addClass(PhpClass $class)

将类添加到文件。文件可以包含多个类

addTrait(PhpTrait $trait)

将特性添加到文件。文件可以包含多个特性

addInterface(PhpInterface $interface)

将接口添加到文件。文件可以包含多个接口

PhpParam

用于创建复杂的参数参数

用法

new PhpParam('string', 'test') => string $test
new PhpParam('object', 'test', null) => object $test = null

$param = new PhpParam('DateTimeInterface', 'date');
$param->allowNull(true);
$param->getSource() => ?DateTimeInterface $date

$param = new PhpParam('float', 'price', 1.5);
$param->allowNull(true);
$param->getSource() => ?float $price = 1.5

PhpFunction

用法

__construct(string $identifier, array $params, string $source, ?PhpDocComment $comment = null, ?string $returnTypeHint = null)

示例
$func = new PhpFunction(
    'testFunc',
    [
        'param1', // Simple parameter
        new PhpParam('int', 'param2', 1),
    ],
    "return $param1 + $param2",
    null, // no docblock
    'int'
);

echo $func->getSource();
输出
function testFunc($param1, int $param2 = 1): int
{
    return $param1 + $param2;
}

PhpMethod

方法是对 PhpFunction 的扩展,支持访问修饰符如 publicprotectedprivatefinalstaticabstract

用法

带有返回类型提示

$method = new PhpMethod('private', 'test', [], 'return 1', null, 'int');
echo $method->getSource();

-------

private function test(): int
{
    return 1;
}

带有文档注释

$method = new PhpMethod(
    'private',
    'test',
    [],
    'return 1',
    new PhpDocComment('Test Description')
);
echo $method->getSource();

-------
/**
 * Test Description
 */
private function test()
{
    return 1;
}

静态方法

$method = new PhpMethod('protected', 'test', [], 'return 1');
$method->setStatic();
echo $method->getSource();

-------

protected static function test()
{
    return 1;
}

最终方法

$method = new PhpMethod('public', 'test', [], 'return 1');
$method->setFinal();
echo $method->getSource();

-------

final public function test()
{
    return 1;
}

抽象方法

$method = new PhpMethod('public', 'test', [], 'return 1', null, 'int');
$method->setAbstract();
echo $method->getSource();

-------

abstract public function test(): int;