$ composer require stefna/php-code-builder
The actual file to save.
Mark files with declare(strict_types=1);
Set file namespace
Set raw php code to be included in file
Like
$file = new PhpFile();
$file->setSource("spl_autoload_register('$autoloaderName');");
Add function to file. Files can contain multiple functions
Add class to file. Files can contain multiple classes
Add trait to file. Files can contain multiple traits
Add interface to file. Files can contain multiple interfaces
Used to make complex parameter arguments
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
__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;
}
Method is an extension of PhpFunction
with support for accessors like public
, protected
, private
, final
, static
and abstract
With return typehint
$method = new PhpMethod('private', 'test', [], 'return 1', null, 'int');
echo $method->getSource();
-------
private function test(): int
{
return 1;
}
With docblock
$method = new PhpMethod(
'private',
'test',
[],
'return 1',
new PhpDocComment('Test Description')
);
echo $method->getSource();
-------
/**
* Test Description
*/
private function test()
{
return 1;
}
Static method
$method = new PhpMethod('protected', 'test', [], 'return 1');
$method->setStatic();
echo $method->getSource();
-------
protected static function test()
{
return 1;
}
Final method
$method = new PhpMethod('public', 'test', [], 'return 1');
$method->setFinal();
echo $method->getSource();
-------
final public function test()
{
return 1;
}
Abstract method
$method = new PhpMethod('public', 'test', [], 'return 1', null, 'int');
$method->setAbstract();
echo $method->getSource();
-------
abstract public function test(): int;