ProductService.php
app/Services/ProductService.php
Service Layer for Product Business Logic
The ProductService orchestrates business rules, repository access, and query objects for the Product domain.
• Centralizes business logic
• Abstracts repository and query usage
• Handles pagination, creation, update, and deletion
• Ensures data integrity and extensibility
Complete Implementation
// filepath: app/Services/ProductService.php <?php namespace App\Services; use App\Models\Product; use App\Repositories\ProductRepository; use Illuminate\Pagination\LengthAwarePaginator; use App\Queries\ProductQueries; /** * Class ProductService * @package App\Services * * This Service Layer handles the business logic for Products. * It abstracts data access (via Repository) and query building (via Query Objects), * orchestrating complex operations and ensuring data integrity. */ class ProductService { protected $productRepository; protected $productQueries; public function __construct(ProductRepository $productRepository, ProductQueries $productQueries) { $this->productRepository = $productRepository; $this->productQueries = $productQueries; } public function getPaginatedProducts(array $filters): LengthAwarePaginator { // Extract filter values with sensible defaults $perPage = $filters['per_page'] ?? 10; $sortBy = $filters['sort_by'] ?? 'created_at'; $sortOrder = $filters['sort_order'] ?? 'desc'; $search = $filters['search'] ?? null; // Start with a base query builder instance for the Product model $query = Product::query(); // Apply filters, sorting, and eager loads using the dedicated Query Object $query = $this->productQueries->applySearch($query, $search); $query = $this->productQueries->applySorting($query, $sortBy, $sortOrder); $query = $this->productQueries->applyEagerLoads($query); // Eager load relationships if any // Execute the paginated query return $query->paginate($perPage); } public function createProduct(array $data): Product { // Add any complex business rules before creation here if needed. // Example: check for existing product with similar attributes, calculate default values. return $this->productRepository->create($data); } public function updateProduct(Product $product, array $data): Product { // Add any complex business rules before update here if needed. return $this->productRepository->update($product, $data); } public function deleteProduct(Product $product): ?bool { // Add any complex business rules before deletion here if needed. // Example: Check if product has active orders, prevent deletion. return $this->productRepository->delete($product); } }