Installation:
composer require binafy/laravel-stub
Publish the config file (optional):
php artisan vendor:publish --provider="Binafy\Stub\StubServiceProvider"
First Use Case:
Generate a basic stub file (e.g., UserController.stub) in resources/stubs/ and publish it to app/Http/Controllers/UserController.php:
use Binafy\Stub\Facades\Stub;
Stub::create('UserController.stub')
->to(app_path('Http/Controllers/UserController.php'))
->moveStub();
resources/stubs/. Check the stub config for custom paths.Binafy\Stub\Facades\Stub for fluent stub generation.php artisan stub:create for interactive stub creation.Stub Generation Pipeline:
Stub::create('stub-name.stub')
->to('destination/path.php') // Required
->name('CustomName') // Optional: Rename output file
->ext('php') // Optional: Force extension
->replace(['old' => 'new']) // Replace placeholders
->replaces(['old' => 'new']) // Replace in stub file (pre-processing)
->conditions(['key' => 'value']) // Conditional logic
->moveStub(); // Execute
Dynamic Stubs with Conditions:
Use conditions() to branch logic (e.g., generate different stubs for Model vs Controller):
Stub::create('Base.stub')
->conditions(['type' => 'Model'])
->replace(['{{namespace}}' => 'App\Models'])
->moveStub();
Stub Templates for Teams:
Store reusable stubs in resources/stubs/ and version-control them. Example:
resources/stubs/
├── controllers/
│ ├── BaseController.stub
│ └── ApiController.stub
└── migrations/
└── BaseMigration.stub
Integration with Artisan Commands:
Extend Laravel’s scaffolding (e.g., make:controller) by hooking into Stub:
// app/Console/Commands/MakeCustomController.php
public function handle()
{
Stub::create('ApiController.stub')
->to($this->getPath())
->replace(['DummyNamespace' => $this->rootNamespace])
->moveStub();
}
Stub Preprocessing:
Use replaces() to modify stubs before rendering (e.g., inject auth scaffolding):
Stub::create('AuthController.stub')
->replaces([
'{{uses}}' => 'use App\Models\User;',
'{{middleware}}' => '@auth',
])
->moveStub();
barryvdh/laravel-ide-helper to auto-generate stubs for IDE hints.webpack.mix.js configurations dynamically.Stub::fake() (if supported) or temporary stub files.Stub File Encoding:
Ensure stub files use UTF-8 encoding to avoid encoding issues with special characters (e.g., ©, →).
Placeholder Conflicts:
Avoid overlapping placeholders (e.g., {{name}} vs {{namespace}}). Use unique prefixes like {{controller.name}}.
File Overwrites:
moveStub() overwrites files silently. Use --force flag in CLI or check file existence first:
if (!file_exists($destination)) {
Stub::create('stub.stub')->to($destination)->moveStub();
}
Path Resolution:
Relative paths in to() are resolved from the current working directory, not the project root. Use absolute paths or base_path():
->to(base_path('app/Http/Controllers/UserController.php'))
Conditions Logic:
Conditions use array_key_exists() internally. Empty arrays or null values may cause unexpected behavior:
// Avoid:
->conditions(['key' => null])
// Use:
->conditions(['key' => 'value'])
Dry Run:
Use ->dump() to preview the final stub content before writing:
Stub::create('stub.stub')->to('path.php')->dump();
Stub Path Issues:
Verify the stubs path in config/stub.php:
'paths' => [
resource_path('stubs'),
// Add custom paths here
],
Placeholder Errors:
Check for unclosed placeholders (e.g., {{name without }}). Use replaces() to validate:
->replaces(['{{missing' => 'default']) // Will throw an error
Custom Stub Providers:
Register additional stub paths in the StubServiceProvider:
public function register()
{
$this->app->singleton('stub', function () {
$stub = new StubManager();
$stub->addPath(base_path('custom/stubs'));
return $stub;
});
}
Stub Events:
Listen for stub generation events (if the package supports them) or wrap Stub calls in a service:
event(new StubGenerated($destination, $stubContent));
Stub Validation: Add pre-flight checks (e.g., validate stub syntax with a regex):
if (!preg_match('/{{.*}}/', file_get_contents($stubPath))) {
throw new \Exception('Stub must contain placeholders.');
}
Stub Caching:
Cache compiled stubs for performance (e.g., in a StubCompiler class):
$cacheKey = md5($stubContent);
if (cache()->has("stub.$cacheKey")) {
return cache()->get("stub.$cacheKey");
}
Stub Testing:
Test stubs in PHPUnit by mocking the Stub facade:
Stub::shouldReceive('create')
->once()
->with('test.stub')
->andReturnSelf();
How can I help you explore Laravel packages today?