dmp/cg-lib
CG library is a PHP 8.1+ toolset for generating PHP code. It helps assemble and enhance classes by adding reusable behaviors, making it easier to build and modify code structures programmatically during code generation workflows.
Installation:
composer require dmp/cg-lib
Ensure your project uses PHP 8.1+ (as per package requirements).
First Use Case:
Generate a simple PHP class dynamically. Start with the ClassGenerator:
use Dmp\CgLib\ClassGenerator;
$generator = new ClassGenerator('MyDynamicClass');
$generator->addProperty('name', 'string', 'John Doe');
$generator->addMethod('getName', 'string', 'return $this->name;');
echo $generator->generate();
Key Entry Points:
src/ directory for core classes (ClassGenerator, TraitGenerator, InterfaceGenerator).tests/ for usage examples and edge cases.Dynamic Class Generation:
$generator = new ClassGenerator('UserRepository');
$generator
->setNamespace('App\Repositories')
->addTrait('Serializable')
->addMethod('findById', '?User', 'return User::find($id);')
->setDocBlock('Handles user data persistence.');
$code = $generator->generate();
file_put_contents('UserRepository.php', $code);
Trait/Interface Enhancement:
Use TraitGenerator or InterfaceGenerator to extend existing classes:
$trait = new TraitGenerator('Loggable');
$trait->addMethod('log', 'void', 'Log::info($message);');
$trait->generate(); // Outputs trait code; inject via `addTrait()` in ClassGenerator.
Integration with Laravel:
$provider = new ClassGenerator('AppServiceProvider');
$provider->addMethod('register', 'void', '
$this->app->singleton(MyService::class, fn() => new MyService());
');
Template-Based Generation: Combine with Laravel’s Blade or custom templates for reusable patterns:
$generator = new ClassGenerator('Model');
$generator->setTemplate('resources/views/generators/model.blade.php');
setNamespace()) to avoid collisions.setDocBlock() for IDE autocompletion and maintainability.ClassGenerator to add custom validation (e.g., check for required methods).PHP Version Quirks:
declare(strict_types=1) to catch type issues early.Namespace Conflicts:
$generator->setNamespace('App\Generated');
Trait/Interface Limitations:
__construct() in the host class.File System Handling:
file_put_contents() or Laravel’s File facade:
use Illuminate\Support\Facades\File;
File::put("app/Generated/{$className}.php", $generator->generate());
echo $generator->generate(); // Check raw output before saving.
try {
$code = $generator->generate();
} catch (\InvalidArgumentException $e) {
Log::error("Generation failed: " . $e->getMessage());
}
Custom Generators:
Extend ClassGenerator to add domain-specific methods:
class ModelGenerator extends ClassGenerator {
public function addFillable(string $field): self {
$this->addProperty($field, 'string');
return $this;
}
}
Template System:
Override the default template by extending Dmp\CgLib\Template\ClassTemplate:
class CustomTemplate extends ClassTemplate {
protected function renderProperties(): string {
return "/* Custom property format */\n" . parent::renderProperties();
}
}
Laravel Integration: Publish config (if added later) via:
php artisan vendor:publish --provider="Dmp\CgLib\CgLibServiceProvider"
(Note: Check if the package includes a service provider.)
Use for Testing: Generate mock classes for unit tests:
$mock = new ClassGenerator('UserMock');
$mock->addMethod('find', 'User', 'return new User();');
eval($mock->generate()); // Runtime generation (use cautiously).
Performance:
Cache generated classes in bootstrap/cache/ to avoid regeneration on every request.
Collaboration:
Document generated classes with @generated tags in PHPDoc to signal they’re auto-generated.
How can I help you explore Laravel packages today?