architecture Junior

What are service classes?

Short Answer

Service classes encapsulate business logic that doesn't belong in controllers or models, keeping controllers thin and models focused on data.

Detailed Answer

Service classes handle business logic that spans multiple models or involves external services: When to create a service: - Business logic spans multiple models - Controller is getting too long - Logic needs to be reused - Integration with external APIs - Complex operations (payments, notifications) Service class benefits: - Thin controllers (HTTP concerns only) - Fat models avoided (business logic extracted) - Testable in isolation - Reusable across controllers Naming convention: {Entity}Service (PostService, PaymentService, NotificationService)

Code Example

Example
<?php
// Service class
class PostService
{
    public function __construct(
        private PostRepositoryInterface $posts,
        private Mailer $mailer,
        private Cache $cache
    ) {}
    
    public function create(array $data): Post
    {
        $post = $this->posts->create($data);
        
        // Business logic
        if ($post->user->isVerified()) {
            $this->mailer->to($post->user)->send(new PostPublishedMail($post));
        }
        
        $this->cache->forget('posts:all');
        event(new PostCreated($post));
        
        return $post;
    }
    
    public function publish(Post $post): Post
    {
        $post->update(['published_at' => now()]);
        $this->cache->forget('posts:all');
        event(new PostPublished($post));
        return $post;
    }
}

// Thin controller
class PostController extends Controller
{
    public function store(StorePostRequest $request, PostService $service)
    {
        $post = $service->create($request->validated());
        return redirect()->route('posts.show', $post);
    }
}

Interview Tip

Give an example of when a service is needed: "Creating an order involves creating the order, deducting inventory, sending emails, and processing payment — that's a service, not a controller or model."