Skip to content

Instantly share code, notes, and snippets.

@surajitbasak109
Created September 19, 2024 09:03
Show Gist options
  • Save surajitbasak109/9ef5f932b7649c5b7a94e8b94849a7c9 to your computer and use it in GitHub Desktop.
Save surajitbasak109/9ef5f932b7649c5b7a94e8b94849a7c9 to your computer and use it in GitHub Desktop.
Laravel create service command

Create an artisan command that will generate a service class in Services directory

Step 1: Create a Custom Artisan Command

You can generate a new Artisan command using Laravel’s built-in command generator. Run the following command in your terminal:

php artisan make:command MakeService

Step 2: Modify the Command

Open the MakeService.php file and copy code from the gist.

Step 3: Register the Command

To make this command available in Laravel, you need to register it in the commands array of the app/Console/Kernel.php file:

// app/Console/Kernel.php

protected $commands = [
    Commands\MakeService::class,
];

Step 4: Usage

Now that the command is set up, you can run it to create a service.

Example 1: Create a simple service:

php artisan make:service TestService

This will generate a file called TestService.php inside the app/Services directory:

<?php

namespace App\Services;

class TestService {
    
}

Example 2: Create a service in a subdirectory:

php artisan make:service Test/TestService

This will generate a file called GoogleMeetService.php inside the app/Services/Integration directory, and it will create the Integration directory if it doesn’t exist:

<?php

namespace App\Services\Test;

class TestService {
    
}
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\MakeService::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class MakeService extends Command
{
/**
* The filesystem instance
*
* @var Filesystem
*/
protected Filesystem $files;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:service {name : The name of the service}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new service class';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(FileSystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$name = $this->argument('name');
// Define base directory for services
$baseDir = app_path('Services');
// Replace backslashes or forward slashes with DIRECTORY_SEPARATOR
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $name);
// Determine the final directory and file name
$filePath = $baseDir . DIRECTORY_SEPARATOR . $path . '.php';
// Extract the directory from the path
$dir = dirname($filePath);
// check if already exists, if not create it
if (!is_dir($dir)) {
$this->files->makeDirectory($dir, 0755, true);
}
// check if the file is already exists
if ($this->files->exists($filePath)) {
$this->warn('Service already exists!');
return 1;
}
// Generate the class stub
$namespace = $this->generateNamespace($name);
$stub = $this->getStub($namespace, class_basename($name));
// Write the file
$this->files->put($filePath, $stub);
$this->info("Service created successfully");
return 0;
}
/**
* Generate the namespace for the service.
*
* @param string $name
* @return string
*/
private function generateNameSpace(string $name): string
{
// clean up the name and clean slashes
$newName = trim(str_replace('/', '\\', $name), '\\');
$namespace = 'App\\Services';
// if there are directories specified in the name, add them to the namespace
if (strpos($newName, "\\") !== false) {
$namespace .= '\\' . dirname($name);
}
return $namespace;
}
/**
* Get the service stub to generate the class file.
*
* @param string $namespace
* @param string $className
* @return string
*/
protected function getStub(string $namespace, string $className): string
{
return <<<HEREDOC
<?php
namespace $namespace;
/**
* $className
*
* Descriptio of the service
*/
class $className {
}
HEREDOC;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment