Weave 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

Symfony Entity Generator Laravel Package

aitradeinc/symfony-entity-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require aitradeinc/symfony-entity-generator
    

    Ensure your project uses Symfony 5.0+ (or 4.0 for legacy support).

  2. Basic Command Generate entities from an existing database table:

    php bin/console make:entity --db-connection=default --table-name=users
    
    • Replace default with your Doctrine connection name.
    • Replace users with your target table.
  3. Configuration Create a YAML config file (e.g., config/entity_generator.yaml) to customize generation:

    aitradeinc_entity_generator:
        groups: ['User', 'Admin']  # Optional: Group fields by entity
        namespace: 'App\Entity'    # Target namespace
    
  4. First Use Case Generate a User entity with all columns from the users table:

    php bin/console make:entity --db-connection=default --table-name=users --entity-name=User
    

    Outputs a fully typed User.php in src/Entity/ with:

    • Properties (e.g., id, email, isActive).
    • Getters/setters (e.g., getEmail(), setIsActive(bool)).
    • Doctrine annotations (e.g., @ORM\Column(type="boolean")).

Implementation Patterns

Workflows

  1. Database-First Development

    • Generate entities from existing tables to bootstrap a project:
      php bin/console make:entity --db-connection=mysql --table-name=products --entity-name=Product
      
    • Regenerate after schema changes (e.g., adding a created_at column).
  2. Grouping Fields Use YAML config to organize fields into logical groups (e.g., User vs. Admin):

    aitradeinc_entity_generator:
        groups:
            User: [id, email, password]
            Admin: [role, permissions]
    
    • Run with --group=User to generate only User-related fields.
  3. Custom Templates Override Twig templates (located in vendor/aitradeinc/symfony-entity-generator/Resources/views/) to modify output (e.g., add custom annotations):

    {# src/Resources/views/Entity/fields.twig #}
    {% for field in fields %}
        /**
         * @Assert\NotBlank(groups={{ group }})
         */
        private {{ field.type }} ${{ field.name }};
    {% endfor %}
    
  4. Integration with Migrations

    • Generate entities after running migrations to ensure schema parity.
    • Use --force to overwrite existing files:
      php bin/console make:entity --table-name=orders --force
      
  5. Partial Generation Generate only specific columns (e.g., for a new feature):

    php bin/console make:entity --table-name=posts --columns=title,content,author_id
    

Tips for Laravel Adoption

  • Doctrine Bridge: Use doctrine/orm in Laravel via laravel-doctrine to leverage this package.
  • Artisan Alias: Add a custom Artisan command in app/Console/Kernel.php:
    protected $commands = [
        \Aitradeinc\EntityGenerator\Command\MakeEntityCommand::class,
    ];
    
  • IDE Integration: Regenerate entities before commits to keep IDE autocompletion (e.g., PHPStorm) accurate.

Gotchas and Tips

Pitfalls

  1. Boolean Field Naming

    • The generator prefixes boolean getters with get (e.g., getIsActive()), not is (e.g., isActive()).
    • Fix: Manually rename methods or patch the Twig template (getter.twig).
  2. JSON Column Handling

    • Older versions had issues with json Doctrine types. Ensure your composer.json includes:
      "doctrine/dbal": "^3.0"
      
    • Workaround: Explicitly cast JSON fields in the entity:
      private ?array $metadata = null;
      public function getMetadata(): ?array { return json_decode($this->metadata, true); }
      
  3. Namespace Conflicts

    • The generator uses the short namespace (e.g., App\Entity\User) by default.
    • Fix: Set a full namespace in config:
      aitradeinc_entity_generator:
          namespace: 'App\\Entity'
      
  4. YAML Parsing Errors

    • Config files must use Symfony YAML syntax (e.g., groups: [User, Admin]).
    • Debug: Run with --debug to see parsed config:
      php bin/console debug:config aitradeinc_entity_generator
      
  5. File Overwrite Behavior

    • By default, the generator skips existing files. Use --force to overwrite:
      php bin/console make:entity --table-name=users --force
      
    • Risk: Loses manual changes (e.g., custom logic in getters).
  6. PHP 8 Typed Properties

    • The generator supports PHP 8’s typed properties (e.g., private ?string $email).
    • Legacy Support: For PHP 7.4, remove ? from nullable fields manually.

Debugging

  • Dry Run: Use --dry-run to preview changes without writing files:
    php bin/console make:entity --table-name=users --dry-run
    
  • Log Output: Enable debug mode for verbose logs:
    php bin/console make:entity --table-name=users --env=dev
    
  • SQL Parsing Errors: If the generator fails to parse a table, check for:
    • Reserved keywords (e.g., order, group) in column names.
    • Fix: Quote column names in the database or rename them.

Extension Points

  1. Custom Field Mappings Override the FieldTypeMapper service to map database columns to custom PHP types:

    # config/services.yaml
    Aitradeinc\EntityGenerator\FieldTypeMapper:
        arguments:
            $customMappings:
                enum: 'App\Enum\StatusEnum'
    
  2. Post-Generation Hooks Use Symfony’s event system to modify entities after generation. Example:

    // src/EventSubscriber/EntityGeneratorSubscriber.php
    namespace App\EventSubscriber;
    
    use Aitradeinc\EntityGenerator\Event\EntityGeneratedEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class EntityGeneratorSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                EntityGeneratedEvent::NAME => 'onEntityGenerated',
            ];
        }
    
        public function onEntityGenerated(EntityGeneratedEvent $event)
        {
            $entity = $event->getEntity();
            $entity->addMethod('toArray()'); // Inject custom method
        }
    }
    
  3. Template Inheritance Extend Twig templates by copying them to templates/AitradeincEntityGenerator/ and modifying:

    • fields.twig: Add custom annotations.
    • getter.twig: Change boolean getter naming.
  4. Database Connection Flexibility

    • Use environment variables for connection DSN:
      aitradeinc_entity_generator:
          db_connection: '%env(DATABASE_URL)%'
      
    • Laravel: Set DATABASE_URL in .env:
      DATABASE_URL="mysql://user:[email protected]/db_name"
      
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel