Skip to content

Omega MVC — DocBlockGenerator Package Manual ​

The Omega\DocBlockGenerator package provides a fluent, programmatic API for generating PHP class, abstract class, and trait source code — including properties, methods, constants, docblock comments, and formatted output. It also includes a VarExport engine for serializing PHP values (including closures and objects) back into executable PHP return statements.

Installation ​

The package ships with the framework and is autoloaded via Composer:

bash
composer require omega-mvc/framework

Core classes ​

ClassPurpose
GenerateTop-level generator for class/trait/abstract declarations
MethodRepresents a single method definition
PropertyRepresents a single property definition
ConstantRepresents a single class constant definition
MethodPoolCollects multiple Method objects for batch insertion
PropertyPoolCollects multiple Property objects for batch insertion
ConstPoolCollects multiple Constant objects for batch insertion
VarExportSerializes PHP values into executable PHP code

Generate ​

Generate is the entry point for building a complete PHP class file. All setter methods return $this for fluent chaining.

Class constants ​

ConstantValueMeaning
SET_CLASS0Regular class
SET_ABSTRACT1Abstract class
SET_TRAIT2Trait

Usage ​

php
use Omega\DocBlockGenerator\Generate;
use Omega\DocBlockGenerator\Method;
use Omega\DocBlockGenerator\Property;

$code = (new Generate('UserService'))
    ->namespace('App\\Service')
    ->use('Psr\\Log\\LoggerInterface')
    ->extend('AbstractService')
    ->implement('LoggerAwareInterface')
    ->rule(Generate::SET_ABSTRACT)
    ->setFinal()
    ->setDeclareStrictTypes()
    ->addProperty('name')
        ->dataType('string')
        ->visibility(Property::PRIVATE_)
    ->methods(function ($pool) {
        $pool->name('getName')
            ->visibility(Method::PUBLIC_)
            ->setReturnType('string')
            ->body('return $this->name;');
    })
    ->generate();

echo $code;

API reference — Generate ​

MethodReturnDescription
__construct(string $name = 'NewClass')—Create generator with a class name
__invoke(string $name): selfselfRename the class being generated
static(string $name): selfselfStatic factory
generate(): stringstringRender the full PHP source code
save(string $pathToSave): int|falseint|falseWrite the generated file to disk
rule(int $rule): selfselfSet class/abstract/trait rule
setFinal(bool $isFinal = true): selfselfMark as final
setEndWithNewLine(bool $enable = true): selfselfAppend trailing newline
addDeclare(string $directive, string|int $value): selfselfAdd a declare directive
setDeclareStrictTypes(int $level = 1): selfselfShorthand for addDeclare('strict_types', 1)
name(string $name): selfselfSet the class name
namespace(string $namespace): selfselfSet the namespace
use(string $useNamespace): selfselfAdd a single use import
uses(array $usesNamespace): selfselfSet multiple use imports
extend(string $extend): selfselfSet the parent class
implement(string $implement): selfselfAdd a single interface
implements(array $implements): selfselfSet multiple interfaces
trait(string $trait): selfselfAdd a single trait
traits(array $traits): selfselfSet multiple traits
body(string $rawBody): selfselfAppend raw PHP to the class body
addConst(string $name): ConstantConstantAdd a single constant (returns it for further config)
constants(callable|ConstPool|Constant $newConst): selfselfAdd one or many constants
addProperty(string $name): PropertyPropertyAdd a single property
properties(callable|Property|PropertyPool $newProperty): selfselfAdd one or many properties
addMethod(string $name): MethodMethodAdd a single method
methods(MethodPool|callable|Method $newMethod): selfselfAdd one or many methods
preReplace(array|string $search, array|string $replace): selfselfPre-generation search/replace
replace(array|string $search, array|string $replace): selfselfPost-generation search/replace

Method ​

Represents a single method definition. Uses FormatterTrait and CommentTrait.

Visibility constants ​

ConstantValue
PUBLIC_0
PRIVATE_1
PROTECTED_2
php
use Omega\DocBlockGenerator\Method;

$method = Method::new('doWork')
    ->visibility(Method::PUBLIC_)
    ->setStatic()
    ->setReturnType('void')
    ->addParam('string $input')
    ->body('echo $input;');

echo $method->generate();

API reference — Method ​

MethodReturnDescription
__construct(string $name)—Create a new method
new(string $name): selfselfStatic factory
generate(): stringstringRender the method source
name(string $name): selfselfSet the method name
visibility(int $visibility): selfselfSet visibility
setFinal(bool $isFinal = true): selfselfEnable/disable final
setStatic(bool $isStatic = true): selfselfEnable/disable static
params(?array $params): selfselfSet the full parameter list
addParams(string $param): selfselfAppend a parameter
setReturnType(?string $returnType): selfselfSet the return type
body(array|string|null $body): selfselfSet the method body

Property ​

Represents a single class property. Uses FormatterTrait and CommentTrait.

php
use Omega\DocBlockGenerator\Property;

$prop = Property::new('count')
    ->dataType('int')
    ->visibility(Property::PRIVATE_)
    ->setStatic()
    ->expecting('0');

echo $prop->generate(); // private static int $count = 0;

API reference — Property ​

MethodReturnDescription
__construct(string $name)—Create a new property
new(string $name): selfselfStatic factory
generate(): stringstringRender the property source
setStatic(bool $isStatic = true): selfselfEnable/disable static
visibility(int $visibility): selfselfSet visibility
dataType(string $dataType): selfselfSet the property type
name(string $name): selfselfSet the property name
expecting(array|string $expecting): selfselfSet the default/expected value

Constant ​

Represents a single class constant. Uses FormatterTrait and CommentTrait.

php
use Omega\DocBlockGenerator\Constant;

$const = Constant::new('MAX_RETRIES')
    ->visibility(Constant::PUBLIC_)
    ->equal('3');

echo $const->generate(); // public const MAX_RETRIES = 3;

API reference — Constant ​

MethodReturnDescription
__construct(string $name)—Create a new constant
new(string $name): selfselfStatic factory
generate(): stringstringRender the constant source
visibility(int $visibility): selfselfSet visibility
name(string $name): selfselfRename the constant
expecting(string $expecting): selfselfSet raw assignment expression (e.g. "= 'val'")
equal(string $expectingWith): selfselfSet value with automatic "= " prefix

Pool classes ​

MethodPool, PropertyPool, and ConstPool are batch-collection containers. Each exposes name(string $name) to create and store an instance, and getPools() to retrieve all stored items.

php
$code = (new Generate('MyClass'))
    ->properties(function ($pool) {
        $pool->name('foo')->dataType('string')->visibility(Property::PUBLIC_);
        $pool->name('bar')->dataType('int')->expecting('42');
    })
    ->methods(function ($pool) {
        $pool->name('getFoo')->visibility(Method::PUBLIC_)->setReturnType('string')->body('return $this->foo;');
        $pool->name('getBar')->visibility(Method::PUBLIC_)->setReturnType('int')->body('return $this->bar;');
    })
    ->generate();

FormatterTrait ​

Used by Generate, Method, Property, and Constant. Provides formatting control:

MethodDescription
tabSize(int $tabSize): selfSet the number of indentation units per level
tabIndent(string $tabIndent): selfSet the indentation character (default "\t")
customizeTemplate(string $template): selfOverride the default code template

CommentTrait ​

Used by Generate, Method, Property, and Constant. Provides docblock generation:

MethodDescription
addComment(?string $comment): selfAppend a raw comment line (null for blank)
addLineComment(): selfAppend a blank separator line
addParamComment(string $datatype, string $name, string $description): selfAdd @param annotation
addVariableComment(string $datatype, string $name): selfAdd @var annotation
addReturnComment(string $datatype, string $name, string $description): selfAdd @return annotation
generateComment(int $tabSize, string $tabIndent): stringRender the docblock string

VarExport ​

VarExport serializes PHP data structures back into executable PHP return statements. It supports scalars, arrays, stdClass, objects (via __set_state()), closures (extracted from source files), and the Constant value object (which exports a constant name rather than its value).

php
use Omega\DocBlockGenerator\VarExport;

$exporter = new VarExport();

// Export to a string
$code = $exporter->export([
    'name' => 'Omega',
    'version' => 2.0,
    'features' => ['routing', 'mvc', 'di'],
]);

// Compile directly to a file
$exporter->compile($data, 'config/cached.php');

API reference — VarExport ​

MethodReturnDescription
__construct()—Create a new exporter
setIndentation(string $indent): selfselfSet indentation string (default " ")
setIndentationLevel(int $indentLevel): selfselfSet initial indentation level
setAlignArray(bool $align = true): selfselfEnable aligned array key output
export(array $data): stringstringSerialize data to a PHP expression string
compileToString(array $data): stringstringFull PHP file with <?php header and return statement
compile(array $data, string $fileName): boolboolWrite compiled PHP to a file

VarExport\Value\Constant ​

When placed inside a data array, VarExport\Value\Constant outputs the constant name verbatim instead of serializing it:

php
use Omega\DocBlockGenerator\VarExport;
use Omega\DocBlockGenerator\VarExport\Value\Constant;

$exporter = new VarExport();
$code = $exporter->export([
    'mode' => new Constant('App::MODE_PROD'),
]);
// Returns: ['mode' => App::MODE_PROD,]

Exceptions ​

All exceptions in this package extend InvalidArgumentException or RuntimeException.

ExceptionThrown when
InvalidArgumentException (from VarExport\Compiler\ClosureCompiler)A non-Closure is passed to ClosureCompiler::compile()
InvalidArgumentException (from VarExport\ClosureExtractor)The closure has no source file, cannot be tokenized, or contains multiple closures on one line

Notes ​

  • All Generate, Method, Property, and Constant instances implement __toString(), so they can be cast to string directly.
  • CommentTrait is only active when at least one comment line has been added; otherwise generateComment() returns an empty string.
  • The VarExport engine handles recursion by inserting null /* RECURSION */ for circular object references.

Reference ​

  • Source: src/Omega/DocBlockGenerator/
  • Tests: tests/Unit/DocBlockGenerator/
  • License: GPL-3.0+