maximaster/attributemplate

Create dynamic templates for your classes using attributes.

1.0.0 2025-04-17 11:19 UTC

This package is auto-updated.

Last update: 2025-04-17 11:21:14 UTC


README

This library generates new classes from templates by resolving attributes into executable logic. Ideal for scenarios like creating database migrations from templates, configuration generation, etc.

Features

1. Attribute-Driven Template Customization

Define templates using PHP attributes to dynamically set class names, constants, and other properties:

#[Rename(new EvalString('sprintf("Version%s", date("YmdHis"))')]
class MigrationTemplate {
    #[SetValue(new Guid())]
    public const ID = '';
}

2. Lazy Evaluation Providers

Use built-in providers to resolve values at runtime:

  • EvalString: Execute PHP expressions (e.g., new EvalString('uniqid()'))
  • Guid: Generates UUIDs
  • Expression: Evaluate Symfony expressions
  • Param: Inject values from context

Installation

composer require maximaster/attributemplate

Usage Example

Input Template

// examples/001/input.php
namespace App;

use Maximaster\Attributemplate\TemplateAttribute\Rename;
use Maximaster\Attributemplate\TemplateAttribute\SetValue;
use Maximaster\Attributemplate\JustScalar\EvalString;
use Ramsey\Uuid\Uuid;

#[Rename(new EvalString('sprintf("Version%s", date("YmdHis"))'))]
class Migration
{
    #[SetValue(new EvalString('Uuid::uuid5("namespace", "name")->toString()'))]
    public const ID = '';
}

Generated Output

// examples/001/output.php
namespace App;

class Version20230101120000
{
    public const ID = '550e8400-e29b-41d4-a716-446655440000';
}

Available Attributes

@Rename

Dynamically rename the class:

#[Rename(new EvalString('MyDynamicName'))]
class Base {}
// Output: class MyDynamicName {}

@SetValue

Set constant/property values:

#[SetValue(new Guid())]
public const UUID = '';
// Output: public const UUID = '123e4567-e89b-12d3-a456-426614174000';

Quirks & Considerations

⚠️ Security Note: EvalString executes arbitrary PHP code - only use trusted expressions.

⚠️ Requires PHP 8.3+ and Nette\PhpGenerator.

⚠️ Attributes can only be applied to:

  • Classes
  • Class constants
  • Parameters
  • Properties

Contributing

  • test with composer test
  • lint with composer lint (also see composer fix)
  • composer qa shortcuts both test and lint