Skip to content

Instantly share code, notes, and snippets.

@aphoe
Created August 16, 2021 01:12
Show Gist options
  • Save aphoe/bbaf7d4bea4f4ab22604e69815fc69ec to your computer and use it in GitHub Desktop.
Save aphoe/bbaf7d4bea4f4ab22604e69815fc69ec to your computer and use it in GitHub Desktop.
Laravel command to create repository file, if using the repository pattern
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MakeRepository extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:repository {name : Name of the repository}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create eloquent model repository';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$path = app_path('Repositories');
if(!is_dir($path)){
mkdir($path);
}
// File name
$repo_class_name = studly_case($this->argument('name')) . 'Repository';
$repo_name = $path . DIRECTORY_SEPARATOR . $repo_class_name . '.php';
// If repository already exists
if(file_exists($repo_name)){
$this->error($repo_class_name . ' repository already exists');
return 1;
}
$stub = 'Console/Commands/stubs/repository.stub';
$stub = app_path(str_replace('/', DIRECTORY_SEPARATOR, $stub));
if(file_exists($stub)){
$content = file_get_contents($stub);
$content = str_replace('class_name', $repo_class_name, $content);
if(file_put_contents($repo_name, $content )){
$this->info($repo_class_name . ' has been created.');
}else{
$this->error('Could not create ' . $repo_class_name);
}
}else{
$this->error('Repository stub does not exist.');
}
return 0;
}
}
<?php
namespace App\Repositories;
class class_name
{
//
}
@aphoe
Copy link
Author

aphoe commented Aug 16, 2021

To create a repository run php artisan make:repository ModelName

The command appends Repository to the file name so the above with create a file called ModelNameRepository into app\Repositories folder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment