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

Laravel Module Generator Laravel Package

nahid-ferdous/laravel-module-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require nahid-ferdous/laravel-module-generator
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="NahidFerdous\ModuleGenerator\ModuleGeneratorServiceProvider"
    
  2. First Use Case

    • Create a YAML file (e.g., module.yaml) in your project root or a designated directory.
    • Define a module structure with keys like name, namespace, controllers, models, etc. Example:
      name: "Blog"
      namespace: "App\\Modules\\Blog"
      controllers:
        - name: "BlogController"
          actions: ["index", "store", "show", "update", "destroy"]
      models:
        - name: "Post"
          fillable: ["title", "content"]
      migrations:
        - name: "create_posts_table"
          columns:
            - "title"
            - "content"
      
  3. Generate the Module

    php artisan module:generate module.yaml
    

    The package will scaffold files like:

    • app/Http/Controllers/Modules/Blog/BlogController.php
    • app/Models/Modules/Blog/Post.php
    • Database migration for posts table.

Implementation Patterns

Workflows

  1. Iterative Development

    • Use the generator early in the project lifecycle to scaffold core modules (e.g., Auth, Admin, Blog).
    • Update the YAML file incrementally as requirements evolve (e.g., add new controllers/actions or model fields).
  2. Team Collaboration

    • Store YAML templates in version control (e.g., .github/module-templates/).
    • Standardize module structures across the team to reduce onboarding time.
  3. Integration with CI/CD

    • Add a script in composer.json to regenerate modules on post-install-cmd:
      "scripts": {
        "post-install-cmd": [
          "php artisan module:generate config/module-templates/*.yaml"
        ]
      }
      
    • Useful for spinning up fresh development environments.

Integration Tips

  • Custom Templates Override default file templates by publishing the package’s views:

    php artisan vendor:publish --tag="module-generator-views"
    

    Modify files in resources/views/module-generator/ to match your project’s coding standards.

  • Seeding and Factories Extend the YAML to include seeders or factories:

    seeders:
      - name: "PostSeeder"
        run: true
    factories:
      - name: "PostFactory"
    

    The package will generate corresponding files in database/seeders/ and database/factories/.

  • API Resources Define API resources in YAML:

    resources:
      - name: "PostResource"
        fields: ["id", "title", "content"]
    

    Outputs a PostResource.php in app/Http/Resources/.

  • Request Validation Specify request validation rules:

    requests:
      - name: "StorePostRequest"
        rules:
          title: "required|string|max:255"
          content: "required|string"
    
  • Testing Generate feature tests alongside controllers:

    tests:
      - name: "BlogControllerTest"
        testable: "BlogController"
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Ensure the namespace in YAML matches your project’s autoload paths. Misconfigured namespaces may cause class-not-found errors.
    • Fix: Verify composer dump-autoload runs after generation.
  2. Migration File Naming

    • The package generates migrations with timestamps (e.g., 2023_01_01_create_posts_table.php). If you rename the YAML’s migrations.name, the migration file won’t update automatically.
    • Fix: Manually rename the migration file or regenerate it.
  3. YAML Syntax Errors

    • Invalid YAML (e.g., unquoted keys with special characters) will fail silently or generate malformed files.
    • Fix: Validate YAML using a linter (e.g., yamllint) before running the generator.
  4. Overwriting Existing Files

    • The generator will overwrite existing files without warning. Accidental regeneration may overwrite custom logic.
    • Fix: Use --dry-run to preview changes:
      php artisan module:generate module.yaml --dry-run
      
  5. Laravel Version Compatibility

    • The package may not support the latest Laravel features (e.g., new model events, API resource changes).
    • Fix: Check the package’s composer.json for Laravel version constraints and test thoroughly.

Debugging

  • Verbose Output Enable debug mode for detailed logs:

    php artisan module:generate module.yaml --verbose
    
  • Check Generated Files Inspect the output files for syntax errors (e.g., missing use statements, incorrect method signatures).

  • Artisan Command Help Review available options:

    php artisan module:generate --help
    

    Example flags:

    • --force: Overwrite files without confirmation.
    • --no-migrations: Skip migration generation.

Extension Points

  1. Custom Commands Extend the generator by creating a custom Artisan command:

    // app/Console/Commands/CustomModuleGenerate.php
    use NahidFerdous\ModuleGenerator\Commands\ModuleGeneratorCommand;
    
    class CustomModuleGenerate extends ModuleGeneratorCommand {
        protected $signature = 'module:custom-generate {file} {--force}';
        protected $description = 'Generate modules with custom logic';
    
        public function handle() {
            // Override logic here
            $this->generateModule($this->argument('file'), $this->option('force'));
        }
    }
    
  2. Event Listeners Listen to the module.generated event to post-process files:

    // app/Providers/ModuleGeneratorServiceProvider.php
    use NahidFerdous\ModuleGenerator\Events\ModuleGenerated;
    
    public function boot() {
        ModuleGenerated::listen(function (ModuleGenerated $event) {
            // Add custom logic, e.g., inject code into generated files
            $event->files['app/Http/Controllers/Modules/Blog/BlogController.php']
                  ->append("protected \$customProperty = 'value';");
        });
    }
    
  3. Dynamic YAML Loading Load YAML from a database or API for dynamic module generation:

    $yamlContent = Cache::get('dynamic_module_config');
    file_put_contents(storage_path('app/module.yaml'), $yamlContent);
    
  4. Template Overrides Override specific file templates (e.g., controllers) by extending the package’s views:

    // config/module-generator.php
    'templates' => [
        'controller' => 'custom::module-generator.controller',
    ],
    

    Create resources/views/custom/module-generator/controller.blade.php.

Tips

  • Modular Monorepos Use the generator to scaffold microservices or modules in a monorepo structure. Example YAML:

    namespace: "App\\Modules\\{module_name}"
    path: "modules/{module_name}"
    

    Configure composer.json to autoload modules:

    "autoload": {
        "psr-4": {
            "App\\Modules\\": "modules/"
        }
    }
    
  • Documentation Generate a README.md for each module by extending the YAML:

    documentation:
      - name: "README.md"
        content: |
          # {module_name} Module
          Description: {description}
          Features: {features}
    
  • Performance For large projects, generate modules in batches or use parallel processing:

    find config/module-templates/ -name "*.yaml" | xargs -P 4 php artisan module:generate
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle