Php artisan make:command to generate new directory file
I came across this article on Spatie Actions https://freek.dev/1371-refactoring-to-actions from a suggestion on this forum and I would like to make a command to generate the files for me, similar how you can generate Model or livewire components etc.
php artisan make:action PublishPostAction Post
This is as far as I got
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class GenerateActionTemplate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:action {name} {model}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new action file.';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$name = $this->argument('name');
$model = $this->argument('model');
$fileContents = <<<'EOT'
<?php
namespace App\Actions;
class PublishPostAction // name
{
private $post;
public function execute(Post $post) // model
{
$this->post = $post;
}
}
EOT;
$this->info($name . 'has been created successfully!');
}
}
How would I do the logic, so if I do like make:action post.PublishPostAction would create a new folder called post in App\Actions\Post\
In the EOT how would I pass in the variables?
Any help or link to an example would be great! I have looked through a few tutorials and was able to scrap this up and laravel docs don't really show any example to generate a new file.
For stub generation, you should look into extending the GeneratorCommand class instead, Laravel makes use of this class for every make command. You can just point to a stub file in your project directory such as stubs/action.stub.
In here, you'd do something like:
namespace {{ namespace }};
class {{ class }}
{
private ${{ variable }};
public function execute({{ model }} ${{ variable }})
{
$this->{{ variable }}= ${{ variable }};
}
}