Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Cg Lib Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dmp/cg-lib
    

    Ensure your project uses PHP 8.1+ (as per package requirements).

  2. 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();
    
  3. Key Entry Points:

    • Review the src/ directory for core classes (ClassGenerator, TraitGenerator, InterfaceGenerator).
    • Check tests/ for usage examples and edge cases.

Implementation Patterns

Core Workflows

  1. 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);
    
  2. 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.
    
  3. Integration with Laravel:

    • Service Providers: Dynamically generate service classes:
      $provider = new ClassGenerator('AppServiceProvider');
      $provider->addMethod('register', 'void', '
          $this->app->singleton(MyService::class, fn() => new MyService());
      ');
      
    • Migrations: Auto-generate migration classes for complex schemas.
  4. 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');
    

Best Practices

  • Namespacing: Always set a namespace (setNamespace()) to avoid collisions.
  • DocBlocks: Use setDocBlock() for IDE autocompletion and maintainability.
  • Validation: Extend ClassGenerator to add custom validation (e.g., check for required methods).

Gotchas and Tips

Pitfalls

  1. PHP Version Quirks:

    • The package targets PHP 8.1+. Test with declare(strict_types=1) to catch type issues early.
    • Avoid mixing dynamic properties with typed properties in generated classes.
  2. Namespace Conflicts:

    • Generated classes without namespaces will pollute the global scope. Always specify:
      $generator->setNamespace('App\Generated');
      
  3. Trait/Interface Limitations:

    • Traits cannot have constructors or destructors. Workaround: Use __construct() in the host class.
    • Interfaces cannot implement methods; use abstract classes for partial implementations.
  4. File System Handling:

    • The package doesn’t auto-save files. Use file_put_contents() or Laravel’s File facade:
      use Illuminate\Support\Facades\File;
      File::put("app/Generated/{$className}.php", $generator->generate());
      

Debugging Tips

  • Generated Code Inspection:
    echo $generator->generate(); // Check raw output before saving.
    
  • Error Handling: Wrap generation in a try-catch:
    try {
        $code = $generator->generate();
    } catch (\InvalidArgumentException $e) {
        Log::error("Generation failed: " . $e->getMessage());
    }
    

Extension Points

  1. 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;
        }
    }
    
  2. 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();
        }
    }
    
  3. 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.)

Pro Tips

  • 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.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor