Links:


Dependencies:


CI

Neuron Scaffolding Component

Code generators and scaffolding tools for the Neuron PHP framework. The Scaffolding component dramatically accelerates development by automating the creation of boilerplate code for controllers, events, listeners, jobs, initializers, migrations, and email templates.

Features

Requirements

Installation

Install as a development dependency:

composer require --dev neuron-php/scaffolding

The scaffolding commands will be automatically available via the Neuron CLI:

./vendor/bin/neuron list

Controller Generation

Generate MVC controllers with views and routes automatically.

Basic Usage

# Generate a basic resource controller
php neuron controller:generate Post

# Generate a namespaced controller (e.g., Admin area)
php neuron controller:generate Admin/Post

# Generate an API controller (JSON responses, no views)
php neuron controller:generate Post --api

Controller Options

Option Description Example
--namespace Controller namespace --namespace="App\Controllers"
--model Model name (defaults to controller name) --model="Article"
--filter Route filter to apply --filter="auth"
--api Generate API controller (JSON) --api
--no-views Skip view generation --no-views
--no-routes Skip route generation --no-routes
--force, -f Overwrite existing files --force

What Gets Generated

When you run php neuron controller:generate Post, the scaffolding component creates:

Controller (app/Controllers/PostController.php):

Views (resources/views/posts/):

Routes (config/routes.yaml):

posts_index:
  method: GET
  route: /posts
  controller: App\Controllers\PostController@index
posts_create:
  method: GET
  route: /posts/create
  controller: App\Controllers\PostController@create
posts_store:
  method: POST
  route: /posts
  controller: App\Controllers\PostController@store
# ... and more

Advanced Examples

# Admin area with authentication filter
php neuron controller:generate Admin/User --filter="auth"

# API controller with custom model
php neuron controller:generate Post --api --model="Article"

# Controller only (no views or routes)
php neuron controller:generate Post --no-views --no-routes

# Force overwrite existing files
php neuron controller:generate Post --force

Event Generation

Generate event classes with typed properties.

Basic Usage

# Simple event without properties
php neuron event:generate UserRegistered

# Event with typed properties
php neuron event:generate UserRegistered \
  --property="userId:int" \
  --property="email:string" \
  --property="timestamp:DateTime"

# Custom namespace
php neuron event:generate OrderPlaced \
  --namespace="App\Events\Orders" \
  --property="orderId:int" \
  --property="total:float"

Event Options

Option Description Example
--namespace Event namespace --namespace="App\Events"
--property Add typed property (repeatable) --property="userId:int"
--force, -f Overwrite existing files --force

Generated Event Class

<?php

namespace App\Events;

class UserRegistered
{
	public int $userId;
	public string $email;
	public DateTime $timestamp;

	public function __construct(int $userId, string $email, DateTime $timestamp)
	{
		$this->userId = $userId;
		$this->email = $email;
		$this->timestamp = $timestamp;
	}
}

Listener Generation

Generate event listener classes.

Basic Usage

# Generate listener for an event
php neuron listener:generate SendWelcomeEmail \
  --event="App\Events\UserRegistered"

# Custom namespace
php neuron listener:generate SendWelcomeEmail \
  --namespace="App\Listeners\Email" \
  --event="App\Events\UserRegistered"

Listener Options

Option Description Example
--namespace Listener namespace --namespace="App\Listeners"
--event Event class to listen for --event="App\Events\UserRegistered"
--force, -f Overwrite existing files --force

Generated Listener Class

<?php

namespace App\Listeners;

use Neuron\Events\IListener;
use App\Events\UserRegistered;

/**
 * SendWelcomeEmail listener
 * Handles UserRegistered events
 */
class SendWelcomeEmail implements IListener
{
	/**
	 * Handle the event
	 *
	 * @param UserRegistered $Event
	 * @return void
	 */
	public function event($Event)
	{
		// TODO: Implement event handling logic
		// Access event data: $Event->userId, $Event->email
	}
}

Event System Workflow

  1. Generate Event:

    php neuron event:generate UserRegistered \
      --property="userId:int" \
      --property="email:string"
    
  2. Generate Listener:

    php neuron listener:generate SendWelcomeEmail \
      --event="App\Events\UserRegistered"
    
  3. Listener Auto-Registered - The listener is automatically registered in config/event-listeners.yaml:

    events:
      userRegistered:
        class: App\Events\UserRegistered
        listeners:
          - App\Listeners\SendWelcomeEmail
    
  4. Emit Event in your code:

    use Neuron\Events\Event;
    use App\Events\UserRegistered;
    
    Event::emit(new UserRegistered($userId, $email));
    

Job Generation

Generate scheduled jobs with cron expressions.

Basic Usage

# Job with cron schedule
php neuron job:generate SendDailyReport --cron="0 9 * * *"

# Job without schedule (queue-only)
php neuron job:generate ProcessImage

# Custom namespace
php neuron job:generate Cleanup \
  --namespace="App\Jobs\Maintenance" \
  --cron="0 0 * * 0"

Job Options

Option Description Example
--namespace Job namespace --namespace="App\Jobs"
--cron Cron expression for scheduling --cron="0 9 * * *"
--force, -f Overwrite existing files --force

Generated Job Class

<?php

namespace App\Jobs;

use Neuron\Jobs\IJob;
use Neuron\Log\Log;

/**
 * SendDailyReport job
 */
class SendDailyReport implements IJob
{
	/**
	 * Get the job name
	 *
	 * @return string
	 */
	public function getName(): string
	{
		return 'send_daily_report';
	}

	/**
	 * Execute the job
	 *
	 * @param array $Argv Arguments passed to the job
	 * @return mixed
	 */
	public function run(array $Argv = []): mixed
	{
		Log::info("SendDailyReport job started");

		// TODO: Implement job logic here

		Log::info("SendDailyReport job completed");

		return true;
	}
}

When using --cron, the job is automatically added to config/schedule.yaml:

schedule:
  sendDailyReport:
    class: App\Jobs\SendDailyReport
    cron: "0 9 * * *"
    args: []

Common Cron Expressions

Expression Description
* * * * * Every minute
0 * * * * Every hour
0 9 * * * Every day at 9:00 AM
0 0 * * 0 Every Sunday at midnight
*/15 * * * * Every 15 minutes
0 0 1 * * First day of month at midnight

Initializer Generation

Generate application initializer classes that run during application startup.

Basic Usage

# Generate an initializer
php neuron initializer:generate DatabaseInitializer

# Custom namespace
php neuron initializer:generate QueueInitializer \
  --namespace="App\Initializers\Queue"

Initializer Options

Option Description Example
--namespace Initializer namespace --namespace="App\Initializers"
--force, -f Overwrite existing files --force

Generated Initializer Class

<?php

namespace App\Initializers;

use Neuron\Patterns\IRunnable;
use Neuron\Patterns\Registry;

/**
 * DatabaseInitializer initializer
 *
 * Initializers are automatically executed on application startup.
 * Use them to configure services, register components, or set up
 * application state before request handling begins.
 */
class DatabaseInitializer implements IRunnable
{
	/**
	 * Run the initializer
	 *
	 * @param array $argv Command-line arguments (if applicable)
	 * @return mixed
	 */
	public function run(array $argv = []): mixed
	{
		// TODO: Implement initialization logic here

		// Example: Register a service in the Registry
		// $registry = Registry::getInstance();
		// $registry->set('MyService', new MyService());

		return null;
	}
}

Email View Template Generation

Generate HTML email view templates for use with Neuron's email system.

Basic Usage

# Generate email view template
php neuron mail:generate welcome

# Generate with hyphenated name
php neuron mail:generate order-confirmation

# Generate password reset template
php neuron mail:generate password-reset

What Gets Generated

The mail:generate command creates an HTML email template in resources/views/emails/ with:

Note: This generates view template files, not email classes. Use these templates with Neuron's email system by referencing them in your email sending code.

Complete Example Workflow

Here's a complete example of scaffolding a blog system:

# 1. Generate the Post controller with views and routes
php neuron controller:generate Post

# 2. Generate an event for when posts are published
php neuron event:generate PostPublished \
  --property="postId:int" \
  --property="title:string" \
  --property="authorId:int"

# 3. Generate listener to send notifications
php neuron listener:generate NotifySubscribers \
  --event="App\Events\PostPublished"

# 4. Generate a job to clean up old draft posts
php neuron job:generate CleanupDrafts --cron="0 0 * * *"

# 5. Generate an initializer for blog configuration
php neuron initializer:generate BlogInitializer

# 6. Generate HTML email view template for post notifications
php neuron mail:generate post-notification

This creates a complete blog system structure in seconds!

Generated File Structure

After running the scaffolding commands, your project structure will look like:

project/
├── app/
│   ├── Controllers/
│   │   └── PostController.php
│   ├── Events/
│   │   └── PostPublished.php
│   ├── Listeners/
│   │   └── NotifySubscribers.php
│   ├── Jobs/
│   │   └── CleanupDrafts.php
│   └── Initializers/
│       └── BlogInitializer.php
├── resources/
│   └── views/
│       ├── posts/
│       │   ├── index.php
│       │   ├── create.php
│       │   └── edit.php
│       └── emails/
│           └── post-notification.php
└── config/
    └── routes.yaml

Stub Templates

All generated code uses carefully crafted templates (stubs) that:

Customization

The generated code is meant to be a starting point. After generation:

  1. Controllers: Add validation, business logic, and data access
  2. Events: Add additional properties or methods as needed
  3. Listeners: Implement event handling logic
  4. Jobs: Add job processing logic and error handling
  5. Views: Customize Bootstrap 5 templates to match your design
  6. Email Templates: Customize HTML email templates with your branding and content

Tips and Best Practices

Naming Conventions

Organization

# Group related controllers in namespaces
php neuron controller:generate Admin/User
php neuron controller:generate Admin/Post
php neuron controller:generate Api/User --api

Overwriting Files

Always review generated files before using --force:

# Check what exists first
ls -la app/Controllers/

# Use force only when you're sure
php neuron controller:generate Post --force

Version Control

Generated files should be committed to version control:

git add app/Controllers/PostController.php
git add resources/views/posts/
git add config/routes.yaml
git commit -m "Add scaffolded Post controller"

Troubleshooting

Permission Errors

If you encounter permission errors:

# Ensure directories are writable
chmod -R 755 app/
chmod -R 755 resources/
chmod -R 755 config/

Namespace Issues

Ensure your composer.json has proper PSR-4 autoloading:

{
  "autoload": {
    "psr-4": {
      "App\\": "app/"
    }
  }
}

Then regenerate autoload:

composer dump-autoload

Routes Not Working

After generating routes, ensure:

  1. Routes file exists: config/routes.yaml
  2. Routes are properly formatted (YAML syntax)
  3. Application is loading routes configuration

Integration with Other Components

With MVC Component

The scaffolding component generates controllers and views that work seamlessly with the Neuron MVC component.

With Events Component

Generated events and listeners integrate directly with the Neuron Events component's emit/listen system.

With Jobs Component

Generated jobs work with the Neuron Jobs scheduler and queue system.

With CLI Component

All scaffolding commands are registered automatically via the CLI component's provider system.

Contributing

When extending the scaffolding component:

  1. Add new stub templates in src/Scaffolding/Stubs/
  2. Create command classes in src/Scaffolding/Commands/
  3. Register commands in the provider
  4. Follow existing patterns and conventions
  5. Add tests for new generators

License

This component is part of the Neuron PHP Framework and is released under the MIT License.

Available Commands Summary

Command Purpose Auto-Configuration
controller:generate Generate RESTful controllers with views Auto-generates routes in routes.yaml
event:generate Generate event classes with properties Manual registration required
listener:generate Generate event listeners Auto-registers in event-listeners.yaml
job:generate Generate scheduled jobs Auto-adds to schedule.yaml (with --cron)
initializer:generate Generate application initializers Auto-loaded by InitializerRunner
mail:generate Generate HTML email view templates Manual usage in code