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 Laravel Package

jms/cg

jms/cg is a PHP code generation library that builds classes, methods, and properties programmatically. It provides a fluent API plus reflection and metadata support to generate readable source code, useful for proxies, serializers, and other build-time tooling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jms/cg
    
    • No additional configuration is required for basic usage.
  2. First Use Case: Generate a simple PHP class dynamically.

    use JMS\GeneratorBundle\Generator\Generator;
    use JMS\GeneratorBundle\Generator\PhpClassGenerator;
    use JMS\GeneratorBundle\Generator\PhpFile;
    
    $class = new PhpClassGenerator('MyClass', 'MyNamespace');
    $class->addMethod('getName', [], 'return "Test";');
    
    $file = new PhpFile($class);
    $file->setClass($class);
    
    $generator = new Generator();
    $generator->generate([$file], __DIR__.'/generated');
    
    • Outputs a file MyNamespace/MyClass.php in the generated directory.
  3. Key Classes to Explore:

    • PhpClassGenerator: For class structure.
    • PhpMethodGenerator: For methods.
    • PhpPropertyGenerator: For properties.
    • PhpFile: For file-level configuration.

Implementation Patterns

Common Workflows

1. Dynamic Class Generation

  • Useful for scaffolding, migrations, or DTOs.
$class = new PhpClassGenerator('User', 'App\\Models');
$class->setImplements(['Serializable']);
$class->addProperty('name', 'string')->setVisibility('private');
$class->addMethod('serialize', [], 'return $this->name;');

2. Template-Based Generation

  • Combine with JMS\GeneratorBundle\Generator\TemplateType for reusable templates.
$template = new TemplateType('path/to/template.twig');
$generator = new Generator();
$generator->generateFromTemplate($template, ['name' => 'User'], __DIR__.'/generated');

3. Integration with Laravel

  • Use in service providers for runtime code generation (e.g., dynamic repositories).
// In a Service Provider's boot method
$generator = app(Generator::class);
$generator->generate([$file], storage_path('app/generated'));

4. Batch Processing

  • Generate multiple classes/files in one pass.
$files = [];
foreach ($entities as $entity) {
    $class = new PhpClassGenerator($entity['name'], $entity['namespace']);
    // ... configure class ...
    $files[] = new PhpFile($class);
}
$generator->generate($files, __DIR__.'/generated');

5. Custom Directories and Namespaces

  • Override default paths and namespaces per file.
$file = new PhpFile($class);
$file->setDirectory('Custom/Directory');
$file->setTargetFile('CustomName.php');

Integration Tips

Laravel-Specific

  • Publish Config: If extending, publish the bundle’s templates:
    php artisan vendor:publish --provider="JMS\GeneratorBundle\JMSGeneratorBundle"
    
  • Service Binding: Bind Generator in AppServiceProvider:
    $this->app->bind(Generator::class, function ($app) {
        return new Generator();
    });
    
  • Artisan Commands: Extend JMS\GeneratorBundle\Command\GenerateCommand for CLI tools.

Performance

  • Cache Templates: Pre-compile Twig templates if using TemplateType.
  • Batch Writes: Use Generator::generate() with an array of PhpFile objects for efficiency.

Testing

  • Mock Generator in tests to avoid filesystem I/O:
    $mockGenerator = $this->createMock(Generator::class);
    $mockGenerator->method('generate')->willReturn(true);
    

Gotchas and Tips

Pitfalls

  1. PHP 7+ Compatibility:

    • While the package supports PHP 7, some older features (e.g., use statements) may need manual adjustments.
    • Fix: Use PhpClassGenerator::setUses() to explicitly declare dependencies.
  2. Namespace Collisions:

    • Generating classes with conflicting namespaces will overwrite files silently.
    • Fix: Validate namespaces before generation or use unique directory structures.
  3. Template Caching:

    • Twig templates aren’t cached by default, leading to slow repeated generations.
    • Fix: Configure Twig’s cache directory:
      $template = new TemplateType('template.twig', [], [], ['cache' => sys_get_temp_dir()]);
      
  4. Visibility Defaults:

    • Properties/methods default to public. Omit setVisibility() to retain defaults.
    • Fix: Explicitly set visibility (e.g., ->setVisibility('private')).
  5. File Permissions:

    • The generator writes files to the target directory. Ensure the web server has write permissions.
    • Fix: Use storage_path() or a dedicated generated/ directory outside public/.
  6. Deprecated Methods:

    • Some methods (e.g., addMethod()) may be deprecated in newer versions.
    • Fix: Check the source for updates or use alternatives like addMethodWithBody().

Debugging Tips

  1. Verify Output:

    • Check generated files for syntax errors or missing logic. Use php -l to lint:
      php -l /path/to/generated/file.php
      
  2. Enable Debug Mode:

    • Set JMS_GENERATOR_DEBUG=1 in your environment to log generation steps.
  3. Inspect Generators:

    • Use var_dump($class->generate()) to see raw PHP code before writing to disk.
  4. Template Errors:

    • If using Twig, enable strict mode in the template:
      {# template.twig #}
      {% set strict_variables = true %}
      

Extension Points

  1. Custom Generators:

    • Extend JMS\GeneratorBundle\Generator\AbstractGenerator for domain-specific logic.
    class MyCustomGenerator extends AbstractGenerator {
        protected function generateClass(PhpClassGenerator $class) {
            // Add custom logic (e.g., annotations, traits)
            $class->addTrait('MyCustomTrait');
            return parent::generateClass($class);
        }
    }
    
  2. Template Overrides:

    • Override default Twig templates in resources/views/jms_generator/ or publish them:
      php artisan vendor:publish --tag=jms-generator-templates
      
  3. Event Listeners:

    • Listen to jms.generator.pre_generate and jms.generator.post_generate events (if using Symfony’s event system).
  4. Annotation Support:

    • Combine with doctrine/annotations to parse generated classes for metadata:
    use Doctrine\Common\Annotations\AnnotationReader;
    $reader = new AnnotationReader();
    $reflection = new ReflectionClass($generatedClass);
    $annotations = $reader->getClassAnnotations($reflection);
    
  5. IDE Integration:

    • Add // @generated comments to hint IDEs (e.g., PhpStorm) to ignore these files in "Open File" dialogs:
    $class->addComment('// @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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle