VOOZH about

URL: https://deepwiki.com/hypervel/components/4.3-code-generation-and-development-tools

⇱ Code Generation and Development Tools | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

Code Generation and Development Tools

Purpose and Scope

This document covers the code generation and development tooling infrastructure provided by the hypervel/devtool package. This includes the 25+ make:* commands for scaffolding framework components, stub-based template generation, command aliasing for Laravel compatibility, and the hot-reload watcher for development workflows.

For information about console command registration and discovery, see Console Kernel and Command Discovery. For scheduled task execution, see Task Scheduling.


Code Generation Architecture

The devtool package provides a comprehensive suite of code generators that follow Hyperf's GeneratorCommand base class pattern while maintaining Laravel-compatible command naming and output structure.

Devtool Package Registration

The src/devtool/src/ConfigProvider.php39-82 registers all generator commands with Hyperf's command system:


Generator Command Categories

CategoryCommandsPurpose
HTTP LayerControllerCommand, MiddlewareCommand, ResourceCommand, RequestCommandHTTP controllers, middleware, API resources, form requests
Database LayerModelCommand, FactoryCommand, SeederCommand, ObserverCommandEloquent models, factories, seeders, model observers
Event SystemEventCommand, ListenerCommand, EventListCommandEvent classes, event listeners, event listing
Queue SystemJobCommand, QueueTableCommand, QueueFailedTableCommand, BatchesTableCommandQueue jobs, database tables for queues
BroadcastingChannelCommand, NotificationCommandBroadcast channels, notifications
ConsoleConsoleCommandConsole commands
Service LayerProviderCommand, PolicyCommand, ExceptionCommand, RuleCommandService providers, authorization policies, exceptions, validation rules
TestingTestCommand, ComponentCommandPHPUnit tests, component tests
Cache/SessionCacheTableCommand, CacheLocksTableCommand, SessionTableCommandDatabase tables for cache/sessions
MailMailCommand, NotificationCommandMailable classes, notifications

Sources: src/devtool/src/ConfigProvider.php39-82


Generator Command Implementation

Each generator command extends Hyperf\Devtool\Generator\GeneratorCommand and implements three key methods: configure(), getStub(), and getDefaultNamespace().

Middleware Generator Example

The src/devtool/src/Generator/MiddlewareCommand.php10-44 demonstrates the generator pattern:


Command Options

OptionTypePurpose
--namespace, -NVALUE_OPTIONALOverride default namespace
--force, -fVALUE_NONEOverwrite existing file
--psr15VALUE_NONEGenerate PSR-15 compatible middleware

Sources: src/devtool/src/Generator/MiddlewareCommand.php10-44

Resource Generator Example

The src/devtool/src/Generator/ResourceCommand.php10-47 shows conditional stub selection:


The command automatically selects the collection stub if:

  • The class name ends with "Collection" (e.g., UserCollection)
  • The --collection flag is provided

Sources: src/devtool/src/Generator/ResourceCommand.php10-47


Stub-Based Template System

Generator commands use stub files as templates, replacing placeholders with actual values during code generation.

Standard Middleware Stub

The src/devtool/src/Generator/stubs/middleware.stub1-21 defines the closure-based middleware template:

%NAMESPACE% → Replaced with App\Http\Middleware or configured namespace
%CLASS% → Replaced with user-provided class name

Template Structure:

  • Namespace declaration with %NAMESPACE% placeholder
  • Import statements for required classes
  • Class definition with %CLASS% placeholder
  • Standard handle() method signature
  • Pass-through implementation calling $next($request)

Sources: src/devtool/src/Generator/stubs/middleware.stub1-21

PSR-15 Middleware Stub

The src/devtool/src/Generator/stubs/middleware.psr15.stub1-21 provides an alternative PSR-15 compatible implementation:

Key Differences:

  • Implements MiddlewareInterface instead of using closures
  • Uses process() method instead of handle()
  • Accepts RequestHandlerInterface instead of Closure
  • Follows PSR-15 middleware standard

Sources: src/devtool/src/Generator/stubs/middleware.psr15.stub1-21

Resource Stubs

Single Resource Stub src/devtool/src/Generator/stubs/resource.stub1-19:

  • Extends JsonResource
  • Provides toArray() method for data transformation
  • Default implementation calls parent::toArray()

Resource Collection Stub src/devtool/src/Generator/stubs/resource-collection.stub1-19:

  • Extends ResourceCollection
  • Handles collections of resources
  • Allows custom collection transformation logic

Sources: src/devtool/src/Generator/stubs/resource.stub1-19 src/devtool/src/Generator/stubs/resource-collection.stub1-19


Command Aliasing System

The CommandReplacer class provides Laravel compatibility by aliasing Hyperf's gen:* commands to Laravel's make:* naming convention.

Command Replacement Mapping

The src/console/src/CommandReplacer.php9-72 implements a static command aliasing system:


Replacement Strategy Table

Hyperf CommandReplacementAlias RetainedNotes
startserveYesCustom description: "Start Hypervel servers"
info(removed)N/AHidden from command list
server:watch(removed)N/AReplaced by custom WatchCommand
gen:controllermake:controllerYesOriginal name as alias
gen:middlewaremake:middlewareYesOriginal name as alias
gen:migrationmake:migrationYesOriginal name as alias
gen:model(removed)N/AHypervel provides custom model generator
gen:request(removed)N/AHypervel provides custom request generator
gen:listenermake:listenerYesOriginal name as alias
describe:routesroute:listYesCustom description: "List all registered routes"

Replacement Logic

The src/console/src/CommandReplacer.php50-71 implements the replacement logic:

  1. Check if command exists in mapping - Returns original command if not in $commands array
  2. Handle NULL replacements - Returns null to hide the command
  3. Rename command - Sets new name from mapping
  4. Retain alias - Optionally keeps original name as alias (default: true)
  5. Update description - Applies custom description if provided

Sources: src/console/src/CommandReplacer.php9-72


Development Watcher

The WatchCommand provides hot-reload functionality during development, automatically restarting the server when files change.

Watch Command Architecture

The src/devtool/src/Commands/WatchCommand.php17-66 integrates with Hyperf's watcher system:


Configuration Options

OptionFlagTypeDefaultPurpose
config-CVALUE_OPTIONAL.watcher.phpCustom config file path
file-FVALUE_OPTIONAL, IS_ARRAY[]Additional files to watch
dir-DVALUE_OPTIONAL, IS_ARRAY[]Additional directories to watch
no-restart-NVALUE_NONEfalseSkip server restart (watch only)

Configuration Loading Priority

The src/devtool/src/Commands/WatchCommand.php32-50 follows this loading sequence:

  1. Load from ConfigInterface - Gets watcher config key
  2. Load default config - Falls back to vendor/hyperf/watcher/publish/watcher.php
  3. Load custom config file - Merges with config from --config option
  4. Set default command - Ensures command key is set to artisan serve
  5. Merge CLI options - Applies --dir, --file, --no-restart flags

Default Command Behavior:

If no command is specified in configuration, the watcher defaults to:

artisan serve

This starts the Hypervel HTTP server and restarts it on file changes.

Sources: src/devtool/src/Commands/WatchCommand.php17-66


Closure Commands

The ClosureCommand class enables defining console commands inline as closures, useful for quick prototyping or application-specific commands.

Closure Command Structure

The src/console/src/ClosureCommand.php18-97 implements closure-based command execution:


Parameter Resolution

The src/console/src/ClosureCommand.php38-59 implements automatic parameter injection:

  1. Merge inputs - Combines arguments and options into single array
  2. Reflect closure - Uses ReflectionFunction to get parameter names
  3. Match parameters - Maps input keys to closure parameter names
  4. Bind context - Binds closure to command instance ($this)
  5. Container resolution - Calls closure via container for dependency injection

Example Parameter Mapping:

Closure: fn($env, $force = false) => ...
CLI Input: deploy production --force
Result: ['env' => 'production', 'force' => true]

Scheduling Support

The src/console/src/ClosureCommand.php80-96 provides fluent scheduling API:


Usage Pattern:


Manual Failure Handling

The src/console/src/ClosureCommand.php55-58 catches ManuallyFailedException:

When a closure command throws ManuallyFailedException src/console/src/ManuallyFailedException.php9-11:

  • Error message is displayed via $this->components->error()
  • Command returns static::FAILURE exit code
  • Allows graceful failure without exception propagation

Sources: src/console/src/ClosureCommand.php18-97 src/console/src/ManuallyFailedException.php9-11


Generator Command Configuration

All generator commands support configuration overrides through the application's config files.

Configuration Structure

Each generator can be configured with custom stub paths and namespaces:


Namespace Resolution Priority

  1. CLI option - --namespace flag (highest priority)
  2. Config override - $this->getConfig()['namespace']
  3. Default namespace - getDefaultNamespace() method return value

Stub Resolution Priority

  1. Config override - $this->getConfig()['stub']
  2. Conditional logic - Based on command options (e.g., --collection, --psr15)
  3. Default stub - Bundled stub in Generator/stubs/ directory

Sources: src/devtool/src/Generator/MiddlewareCommand.php24-36 src/devtool/src/Generator/ResourceCommand.php24-36


Application Factory Integration

The console application is bootstrapped through the ApplicationFactory src/console/src/ApplicationFactory.php11-25:


The factory:

  1. Resolves the KernelContract from the container
  2. Retrieves the Artisan application instance via getArtisan()
  3. Catches any bootstrap exceptions
  4. Renders errors using ErrorRenderer
  5. Exits process on failure

Sources: src/console/src/ApplicationFactory.php11-25


Summary

The code generation system provides:

ComponentPurposeKey Classes
Generator Commands25+ make:* commands for scaffoldingMiddlewareCommand, ResourceCommand, ControllerCommand
Stub TemplatesFile templates with placeholder replacement*.stub files in Generator/stubs/
Command AliasingLaravel compatibility layerCommandReplacer
Hot ReloadDevelopment file watcherWatchCommand
Closure CommandsInline command definitionsClosureCommand
ConfigurationOverride namespaces and stubsgenerators.* config keys

The system integrates Hyperf's generator infrastructure with Laravel-familiar naming conventions, providing a consistent developer experience while leveraging Hyperf's underlying code generation capabilities.