VOOZH about

URL: https://deepwiki.com/hypervel/devtool/4.1-stub-template-system

⇱ Stub Template System | hypervel/devtool | DeepWiki


Loading...
Menu

Stub Template System

Purpose and Scope

The stub template system is the templating engine that powers all code generation commands in the Hypervel/Devtool package. It provides a simple, file-based approach to generating PHP classes by replacing placeholders in template files (stubs) with actual values derived from user input and configuration.

This document covers the stub file format, placeholder syntax, resolution mechanisms, and customization options. For information about how generator commands use these stubs as part of the overall generation pipeline, see Code Generation System. For details on specific generator commands and their stub variations, see the relevant command documentation sections (e.g., Model and Factory Generation, Controller Generation).


Stub File Organization

Stub files are template files with a .stub extension, stored in the src/Generator/stubs/ directory. Each stub file contains the skeleton structure for a specific type of generated class, with placeholders that are replaced during generation.

Directory Structure:

Stub FilePurposeUsed By Command
model.stubModel class templatemake:model
factory.stubFactory class templatemake:factory
seeder.stubSeeder class templatemake:seeder
console.stubConsole command templatemake:command
rule.stubValidation rule templatemake:rule
cache-table.stubCache table migrationmake:cache-table
cache-locks-table.stubCache locks migrationmake:cache-locks-table

Each stub file is a syntactically valid PHP file containing placeholder markers that follow a consistent naming convention.

Sources: src/Generator/stubs/


Stub File Anatomy

Basic Structure

All stub files follow a standard PHP file structure with placeholders embedded at specific locations:

<?php

declare(strict_types=1);

namespace %NAMESPACE%;

use %USES%;

class %CLASS% extends BaseClass
{
 // Class body with additional placeholders
}

The stub files are designed to generate valid PHP code that conforms to the Hypervel framework's coding standards, including strict type declarations and proper namespace organization.

Sources: src/Generator/stubs/model.stub1-21 src/Generator/stubs/console.stub1-28


Placeholder Syntax and Conventions

Standard Placeholders

The stub system uses uppercase placeholders wrapped in percent signs: %PLACEHOLDER%. This convention makes them easily identifiable and prevents accidental conflicts with legitimate code.

Common Placeholder Types:

PlaceholderPurposeExample Value
%NAMESPACE%Full namespace of the classApp\Models
%CLASS%Class name without namespaceUser
%USES%Use statementsHypervel\Database\Eloquent\Model
%TABLE%Database table namecache
%MODEL%Model class name referenceUser
%MODEL_NAMESPACE%Full model namespaceApp\Models\User
%COMMAND%Console command signatureapp:process-data

Context-Specific Placeholders

Different generator commands introduce specialized placeholders relevant to their domain:

Example: Console Command Stub

src/Generator/stubs/console.stub1-28 demonstrates a command-specific placeholder:


This %COMMAND% placeholder is replaced by either a user-provided command name or an auto-generated kebab-case version of the class name.

Sources: src/Generator/stubs/console.stub14 src/Generator/ConsoleCommand.php28-34


Stub Resolution Process

Diagram: Stub File Location Resolution


Sources: src/Generator/ConsoleCommand.php36-39 src/Generator/RuleCommand.php23-26

Implementation Pattern

Every generator command implements a getStub() method that follows this resolution pattern:


This pattern provides:

  1. Customization: Users can override stub paths via configuration
  2. Default behavior: Falls back to bundled stubs if no custom path is configured
  3. Consistency: All commands follow the same resolution logic

Configuration Override Example:

Configuration can be provided through the generator command's config system (inherited from Hyperf's GeneratorCommand):


Sources: src/Generator/ConsoleCommand.php36-39 src/Generator/RuleCommand.php23-26 src/Generator/SeederCommand.php23-26


Placeholder Replacement Mechanism

Diagram: Placeholder Replacement Pipeline


Sources: src/Generator/ConsoleCommand.php28-34 src/Generator/CacheTableCommand.php61-64

Standard Replacements

The base GeneratorCommand class (from Hyperf) provides standard replacement methods that handle common placeholders:

  • replaceClass(string $stub, string $name): string: Replaces %CLASS% with the class name
  • replaceNamespace(string $stub, string $name): string: Replaces %NAMESPACE% with the namespace

These methods are called automatically during the generation process and can be overridden in child classes to add custom replacement logic.

Sources: src/Generator/ConsoleCommand.php28-30

Custom Replacements

Generator commands extend the base replacement behavior by overriding methods or implementing additional string replacements:

Example: Console Command Custom Replacement

src/Generator/ConsoleCommand.php28-34 demonstrates custom placeholder replacement:


This method:

  1. Calls the parent method to handle standard replacements
  2. Determines the command signature from user input or generates one automatically
  3. Replaces the %COMMAND% placeholder with the final value

Example: Cache Table Migration Replacement

src/Generator/CacheTableCommand.php61-64 shows a simpler direct replacement:


This method directly replaces the %TABLE% placeholder with the configured table name.

Sources: src/Generator/ConsoleCommand.php28-34 src/Generator/CacheTableCommand.php61-64


Complete Generation Flow

Diagram: Full Stub Processing Pipeline


Sources: src/Generator/ConsoleCommand.php28-34 src/Generator/CacheTableCommand.php29-58

Code Entity Mapping: CacheTableCommand Example

The following table maps the generation process to actual code constructs in src/Generator/CacheTableCommand.php:

Process StepCode EntityLine Reference
Determine table namemigrationTableName()100-105
Check if file existsalreadyExists($path)41
Create directorymakeDirectory($path)49
Load stub templatefile_get_contents($this->getStub())51
Replace placeholdersbuildMigration($stub, $tableName)52
Write output filefile_put_contents($path, ...)52
Report success$output->writeln(...)54

Sources: src/Generator/CacheTableCommand.php29-59


Stub Template Examples

Model Stub

The src/Generator/stubs/model.stub1-21 template demonstrates a standard class stub with multiple placeholders:

Key Features:

  • %NAMESPACE%: Replaced with the target namespace (e.g., App\Models)
  • %USES%: Replaced with the base model import (e.g., Hypervel\Database\Eloquent\Model)
  • %CLASS%: Replaced with the model class name
  • Includes predefined $fillable and $casts properties for ORM functionality

Sources: src/Generator/stubs/model.stub1-21

Factory Stub

The src/Generator/stubs/factory.stub1-27 template shows relationship-aware placeholders:

Key Features:

  • Fixed namespace: Database\Factories (factories follow a convention-based location)
  • %MODEL_NAMESPACE%: Full path to the associated model class
  • %MODEL%: Model class name used in type hints and class naming
  • PHPDoc @extends annotation for IDE support

Sources: src/Generator/stubs/factory.stub1-27

Console Command Stub

The src/Generator/stubs/console.stub1-28 template includes command-specific metadata:

Key Features:

  • %COMMAND%: The Artisan command signature (e.g., app:process-data)
  • Predefined $signature and $description properties
  • Empty handle() method for command logic

Sources: src/Generator/stubs/console.stub1-28

Rule Validation Stub

The src/Generator/stubs/rule.stub1-22 template shows interface implementation:

Key Features:

  • Implements ValidationRule interface
  • PHPDoc with type hints for the $fail closure parameter
  • Minimal structure focused on the validate() method signature

Sources: src/Generator/stubs/rule.stub1-22

Migration Stub (Cache Table)

The src/Generator/stubs/cache-table.stub1-29 template demonstrates migration structure:

Key Features:

  • Returns an anonymous class extending Migration
  • %TABLE%: Replaced with the configured cache table name
  • Includes both up() and down() methods for migration reversibility
  • Schema definition specific to cache storage requirements

Sources: src/Generator/stubs/cache-table.stub1-29


Customization Options

Configuration-Based Customization

Generator commands support configuration overrides at two levels:

1. Custom Stub Path:


2. Command-Specific Configuration:

Each generator command accesses its configuration through $this->getConfig(), which typically corresponds to a configuration key matching the command type. For example:

  • ConsoleCommand: Checks for console-specific configuration
  • RuleCommand: Checks for rule-specific configuration
  • SeederCommand: Checks for seeder-specific configuration with custom path handling

Sources: src/Generator/ConsoleCommand.php36-44 src/Generator/RuleCommand.php23-30 src/Generator/SeederCommand.php23-44

Namespace Customization

The getDefaultNamespace() method defines where generated classes are placed. Commands override this to provide sensible defaults while allowing configuration overrides:

CommandDefault NamespaceConfiguration Key
ConsoleCommandApp\Console\Commandsnamespace
RuleCommandApp\Rulesnamespace
SeederCommand(empty, uses path-based location)path

Sources: src/Generator/ConsoleCommand.php41-44 src/Generator/RuleCommand.php28-31 src/Generator/SeederCommand.php46-49

Path Resolution

Different generator types handle output paths differently:

Standard Path Resolution: Most commands use the base class's path resolution, which combines the namespace with the base application path.

Custom Path Resolution: Commands like SeederCommand and CacheTableCommand override path resolution entirely:

src/Generator/SeederCommand.php39-44 demonstrates custom path handling:


This allows seeders to be placed in database/seeders/ regardless of namespace considerations.

Sources: src/Generator/SeederCommand.php39-44 src/Generator/CacheTableCommand.php34-36


Stub Replacement Patterns

Diagram: Common Replacement Patterns by Command Type


Sources: src/Generator/ConsoleCommand.php28-34 src/Generator/RuleCommand.php23-26 src/Generator/SeederCommand.php23-26 src/Generator/CacheTableCommand.php61-64

Pattern Analysis

Pattern 1: Direct String Replacement

The simplest pattern uses str_replace() directly in a custom method:


Pattern 2: Override with Chaining

More complex commands override replaceClass() and chain parent replacements:


Pattern 3: Multi-Step Replacement

Some generators perform multiple replacement passes for related placeholders:


Sources: src/Generator/CacheTableCommand.php61-64 src/Generator/ConsoleCommand.php28-34


Integration with Generator Commands

The stub template system integrates seamlessly with the broader generator command architecture. Each command follows this general pattern:

  1. Stub Selection: getStub() determines which stub file to use
  2. Content Loading: The stub file is read into a string
  3. Placeholder Processing: Replacement methods transform placeholders into actual values
  4. Path Resolution: Output path is determined based on namespace and configuration
  5. File Writing: The processed content is written to the target file

This separation of concerns allows the stub system to remain simple while generator commands handle the complexity of user input, option processing, and filesystem operations.

Sources: src/Generator/CacheTableCommand.php29-59 src/Generator/ConsoleCommand.php1-52


Stub File Conventions

Coding Standards

All stub files adhere to the following conventions:

  • Strict Types: All stubs include declare(strict_types=1);
  • PSR-12: Follow PSR-12 coding style guidelines
  • Empty Implementations: Methods contain only comments (//) to indicate where developers should add code
  • Type Hints: Include proper type hints for method parameters and return types
  • DocBlocks: Include PHPDoc blocks where helpful for IDE support

Placeholder Naming

Placeholder naming follows these rules:

  • All Uppercase: %PLACEHOLDER% not %placeholder% or %Placeholder%
  • Descriptive: Names clearly indicate what they represent
  • Consistent: Same placeholder name across different stubs for the same concept
  • No Ambiguity: Different placeholders for different purposes (e.g., %CLASS% vs %MODEL%)

Sources: src/Generator/stubs/console.stub1-28 src/Generator/stubs/rule.stub1-22 src/Generator/stubs/model.stub1-21

Refresh this wiki

On this page