Membuat Service Layer Di Laravel Untuk Pemula - CRUDPRO

Membuat Service Layer Di Laravel Untuk Pemula

Membuat Service Layer Di Laravel Untuk Pemula

Service Layer yaitu Design Pattern yang bertujuan sebagai memisahkan logic dengan controller supaya bisa digunakan kembali di controller lainnya.

Jika kamu melihat tulisan ini maka kamu sudah berfikir lebih jauh daripada sebelumnya, karena kamu sudah memikirkan design pattern untuk membuat software yang baik dan sudah memikirkan kualitas kode yang akan kamu tulis dan service layer ini merupakan solusi umum gunakan.

1. Membuat File Stub

Buatlah folder dengan nama stubs dan Scripts di dalam folder app/Console/Commands/Scripts/stubs, kemudian copy dan paste source code dibawah ini lalu simpan di ke dalam file service.stub.

<?php

namespace App\Services;

use Illuminate\Database\Eloquent\Model;

class {{class}} extends Service
{

    public function model(): Model
    {
        // Object Model
    }

    public function datatable($request)
    {

    }

    public function all()
    {

    }

    public function show($id)
    {

    }

    public function update($request, $id)
    {

    }

    public function store($request)
    {

    }

    public function delete($id)
    {

    }
}

2. Membuat Script Service Generator

Selanjutnya kita buat command untuk generate file service secara otomatis menggunakan artisan laravel nantinya, dengan mengetikan perintah berikut :

php artisan make:command Scripts/CreateServiceCommand

Selanjutnya copy paste source code dibawah ini

<?php

namespace App\Console\Commands\Scripts;

use Illuminate\Console\Command;
use Illuminate\Console\GeneratorCommand;

class CreateServiceCommand extends GeneratorCommand
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:service {name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Service';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__ . '/stubs/service.stub';
    }

    /**
     * Get the default namespace for the class.
     *
     * @param string $rootNamespace
     *
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . '\Services';
    }

}

Source code diatas merupakan fungsi command yang akan membuat file service baru secara otomatis, lokasi file ini nantinya akan berada di dalam folder \app\Services\NamaFileService.php

Kemudian daftarkan command yang sudah dibuat pada tahap diatas ke dalam file app/Console/Kernel.php, sehingga akan menjadi seperti ini :

<?php

namespace App\Console;

use App\Console\Commands\Scripts\CreateServiceCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{

    protected $commands = [
        CreateServiceCommand::class
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

3. Membuat File Service

Setelah itu mari kita coba buat file service untuk user atau admin, dengan mengetikan perintah ini

php artisan make:service UserService

Jika berhasil maka akan muncul seperti gambar dibawah ini

4. Buat Fungsi Create Di Dalam File Service

Setelah itu ubah file UserService dengan source code dibawah ini

<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;

class UserService extends Service
{

    public function model(): Model
    {
        return new User;
    }

    public function datatable($request)
    {

    }

    public function all()
    {

    }

    public function show($id)
    {

    }

    public function update($request, $id)
    {

    }

    public function store($request)
    {
        return $this->model()->create($request);
    }

    public function delete($id)
    {

    }
}

4. Memanggil File Service Di Dalam Controller

Langkah terakhir kita panggil file service yang sudah dibuat pada tahap sebelumnya di dalam controller, dan kita buat source code nya seperti ini

<?php

namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller
{

    public function __construct()
    {
        $this->user = new UserService;
    }

    public function create(Request $request)
    {
        return $this->user->store([
            'name' => $request->name,
            'email' => $request->email,
            'password' => \Hash::make($request->password)
        ]);
    }

}