استفاده از Service Layer در Laravel 11 برای سازمان‌دهی کد

  • 9 اسفند 1403
0 دیدگاه
خلاصه مطلب

در این مقاله نحوه استفاده از Service Layer در Laravel 11 برای جداسازی Business Logic و سازمان‌دهی بهتر کدها را بررسی می‌کنیم.

چگونه در Laravel 11 از Service Layer برای سازمان‌دهی بهتر کد استفاده کنیم؟


Laravel یک فریمورک محبوب PHP است که برای توسعه سریع و خوانای برنامه‌های وب استفاده می‌شود. یکی از چالش‌های توسعه در پروژه‌های بزرگ، سازمان‌دهی صحیح کدها و جلوگیری از پیچیدگی زیاد در کنترلرها و مدل‌ها است. در این مقاله، به بررسی استفاده از Service Layer در Laravel 11 برای مدیریت بهتر Business Logic می‌پردازیم.


Service Layer چیست؟


Service Layer یک لایه‌ی جداگانه برای مدیریت Business Logic است که به عنوان واسط بین کنترلرها و مدل‌ها عمل می‌کند. این رویکرد باعث می‌شود:

  • کدهای کنترلر تمیزتر و خواناتر شوند.
  • Business Logic از مدل‌ها و کنترلرها جدا شود.
  • قابلیت تست‌پذیری کدها افزایش یابد.
  • امکان استفاده مجدد از Business Logic در بخش‌های مختلف برنامه فراهم شود.


پیاده‌سازی Service Layer در Laravel 11


1. ایجاد پوشه و فایل‌های مربوط به سرویس


در ابتدا، یک پوشه برای سرویس‌ها در مسیر app/Services ایجاد کنید:

mkdir app/Services


2. ایجاد یک کلاس سرویس نمونه


فرض کنیم که یک سرویس برای مدیریت کاربران داریم. یک فایل جدید به نام UserService.php در مسیر app/Services ایجاد کنید و کد زیر را داخل آن قرار دهید:

<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Collection;

class UserService
{
    public function createUser(array $data): User
    {
        try {
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);
            return $user;
        } catch (\Exception $e) {
            Log::error('User creation failed: ' . $e->getMessage());
            throw new \Exception('There was a problem creating the user.');
        }
    }

    public function getAllUsers(): Collection
    {
        return User::all();
    }

    public function getUserById(int $id): ?User
    {
        return User::find($id);
    }

    public function updateUser(int $id, array $data): bool
    {
        $user = User::findOrFail($id);
        return $user->update($data);
    }

    public function deleteUser(int $id): bool
    {
        $user = User::findOrFail($id);
        return $user->delete();
    }
}


3. استفاده از سرویس در کنترلر


حالا، می‌توانیم این سرویس را در کنترلر استفاده کنیم. در UserController.php:

<?php

namespace App\Http\Controllers;

use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\User;

class UserController extends Controller
{
    protected $userService;

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

    public function store(Request $request): JsonResponse
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6',
        ]);

        $user = $this->userService->createUser($validatedData);

        return response()->json(['message' => 'User created successfully.', 'user' => $user]);
    }

    public function index(): JsonResponse
    {
        return response()->json($this->userService->getAllUsers());
    }

    public function show(int $id): JsonResponse
    {
        return response()->json($this->userService->getUserById($id));
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $validatedData = $request->validate([
            'name' => 'string|max:255',
            'email' => 'email|unique:users,email,' . $id,
            'password' => 'nullable|min:6',
        ]);

        $this->userService->updateUser($id, $validatedData);
        return response()->json(['message' => 'User successfully updated.']);
    }

    public function destroy(int $id): JsonResponse
    {
        $this->userService->deleteUser($id);
        return response()->json(['message' => 'User successfully deleted.']);
    }
}


4. تزریق سرویس با استفاده از Service Provider (اختیاری)


می‌توان Service Provider مخصوصی برای سرویس‌ها ایجاد کرد و از آن‌ها در سطح اپلیکیشن استفاده کرد:

php artisan make:provider ServiceServiceProvider

در فایل app/Providers/ServiceServiceProvider.php:

<?php

namespace App\Providers;

use App\Services\UserService;
use Illuminate\Support\ServiceProvider;

class ServiceServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(UserService::class, function ($app) {
            return new UserService();
        });
    }
}

سپس، این Provider را در config/app.php ثبت کنید:

'providers' => [
    App\Providers\ServiceServiceProvider::class,
],


نتیجه‌گیری


استفاده از Service Layer در Laravel 11 باعث جداسازی بهتر Business Logic از کنترلرها و مدل‌ها شده و کدی خواناتر، مقیاس‌پذیرتر و قابل‌تست‌تر ایجاد می‌کند. اگر پروژه‌ی شما در حال رشد است، توصیه می‌شود از این معماری برای بهبود ساختار کد استفاده کنید.

آیا شما هم تجربه‌ای از استفاده از Service Layer در Laravel دارید؟ نظرات خود را در کداکسپرت با ما به اشتراک بگذارید!

در بهبود مقاله شریک باشید

قبل از ثبت نظر باید وارد حساب کاربری خود شوید و اطلاعات پروفایل را کامل کنید

ثبت نام یا ورود
قوانین ارسال دیدگاه

لطفاً قبل از ارسال دیدگاه، قوانین زیر را مطالعه کنید:

  • دیدگاه باید مرتبط با موضوع مقاله باشد.
  • از به‌کار بردن الفاظ نامناسب خودداری کنید.
  • تبلیغات در بخش نظرات مجاز نیست.