Files
portal-api/app/Services/StudentService.php

101 lines
2.7 KiB
PHP

<?php
namespace App\Services;
use App\Services\Cache\CacheServiceInterface;
use App\Support\Cache\CacheKey;
/**
* Example service demonstrating the CacheService + CacheKey pattern.
*
* Cache key format: module:type[:param:value...]
*
* Examples produced:
* students:list:page:1
* students:list:page:2:status:active
* students:detail:id:15
*/
class StudentService
{
private const MODULE = 'students';
public function __construct(
private readonly CacheServiceInterface $cache,
) {}
public function getList(int $page = 1, ?string $status = null): array
{
$params = ['page' => $page];
if ($status !== null) {
$params['status'] = $status;
}
$key = CacheKey::build(self::MODULE, 'list', $params);
return $this->cache->remember(
key: $key,
callback: fn () => $this->fetchList($page, $status),
ttl: CacheServiceInterface::TTL_MEDIUM,
tags: [self::MODULE],
);
}
public function getDetail(int $id): array
{
$key = CacheKey::build(self::MODULE, 'detail', ['id' => $id]);
return $this->cache->remember(
key: $key,
callback: fn () => $this->fetchDetail($id),
ttl: CacheServiceInterface::TTL_LONG,
tags: [self::MODULE],
);
}
public function update(int $id, array $_data): void
{
// ... update DB logic ...
// Forget only the stale detail entry
$this->cache->forget(
CacheKey::build(self::MODULE, 'detail', ['id' => $id])
);
// Also bust all list caches for this module
$this->cache->clearByModule(self::MODULE);
}
public function getByIds(array $ids): array
{
// Array params are joined with "," — key: students:bulk:ids:1,2,3
$key = CacheKey::build(self::MODULE, 'bulk', ['ids' => $ids]);
return $this->cache->remember(
key: $key,
callback: fn () => $this->fetchByIds($ids),
ttl: CacheServiceInterface::TTL_SHORT,
tags: [self::MODULE],
);
}
// -------------------------------------------------------------------------
// Private DB fetch methods (replace with real Eloquent/Repository calls)
// -------------------------------------------------------------------------
private function fetchList(int $_page, ?string $_status): array
{
return []; // replace with Eloquent/Repository query
}
private function fetchDetail(int $_id): array
{
return []; // replace with Eloquent/Repository query
}
private function fetchByIds(array $_ids): array
{
return []; // replace with Eloquent/Repository query
}
}