This commit is contained in:
Doar Mihai
2026-04-03 20:55:51 +03:00
parent a8a48f3f6f
commit 31e666ef33
7 changed files with 586 additions and 68 deletions
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
class CacheService
{
// Cache durations (in seconds)
const CACHE_JOB_LISTINGS = 300; // 5 minutes
const CACHE_SEARCH_RESULTS = 600; // 10 minutes
const CACHE_CATEGORIES = 3600; // 1 hour
const CACHE_STATISTICS = 1800; // 30 minutes
const CACHE_FILTER_OPTIONS = 3600; // 1 hour
const CACHE_FEATURED_JOBS = 900; // 15 minutes
/**
* Generate cache key for job listings
*/
public function jobListingsKey(array $filters = [], int $page = 1, int $perPage = 20): string
{
ksort($filters);
return 'jobs:list:' . md5(serialize($filters) . ":{$page}:{$perPage}");
}
/**
* Generate cache key for search results
*/
public function searchResultsKey(array $filters = [], int $page = 1): string
{
ksort($filters);
return 'jobs:search:' . md5(serialize($filters) . ":{$page}");
}
/**
* Generate cache key for job details
*/
public function jobDetailsKey(int $jobId): string
{
return "job:details:{$jobId}";
}
/**
* Generate cache key for categories
*/
public function categoriesKey(): string
{
return 'categories:all';
}
/**
* Generate cache key for category jobs
*/
public function categoryJobsKey(int $categoryId, int $page = 1): string
{
return "category:{$categoryId}:jobs:{$page}";
}
/**
* Generate cache key for statistics
*/
public function statisticsKey(): string
{
return 'stats:dashboard';
}
/**
* Generate cache key for filter options
*/
public function filterOptionsKey(): string
{
return 'filters:options';
}
/**
* Generate cache key for featured jobs
*/
public function featuredJobsKey(int $limit = 10): string
{
return "jobs:featured:{$limit}";
}
/**
* Generate cache key for recent jobs
*/
public function recentJobsKey(int $days = 7, int $limit = 6): string
{
return "jobs:recent:{$days}:{$limit}";
}
/**
* Clear job-related caches
*/
public function clearJobCaches(): void
{
Cache::tags(['jobs'])->flush();
}
/**
* Clear category caches
*/
public function clearCategoryCaches(): void
{
Cache::tags(['categories'])->flush();
}
/**
* Clear statistics caches
*/
public function clearStatisticsCaches(): void
{
Cache::forget($this->statisticsKey());
}
/**
* Clear all application caches
*/
public function clearAllCaches(): void
{
Cache::flush();
}
/**
* Remember with tags (for better cache management)
*/
public function rememberWithTags(array $tags, string $key, int $ttl, callable $callback)
{
return Cache::tags($tags)->remember($key, $ttl, $callback);
}
/**
* Get cached value or store new one
*/
public function remember(string $key, int $ttl, callable $callback)
{
return Cache::remember($key, $ttl, $callback);
}
/**
* Get from cache
*/
public function get(string $key, $default = null)
{
return Cache::get($key, $default);
}
/**
* Put value in cache
*/
public function put(string $key, $value, int $ttl): bool
{
return Cache::put($key, $value, $ttl);
}
/**
* Forget cache key
*/
public function forget(string $key): bool
{
return Cache::forget($key);
}
/**
* Increment counter (useful for statistics)
*/
public function increment(string $key, int $value = 1): int
{
return Cache::increment($key, $value);
}
/**
* Decrement counter
*/
public function decrement(string $key, int $value = 1): int
{
return Cache::decrement($key, $value);
}
}
+38 -31
View File
@@ -8,6 +8,9 @@ use Illuminate\Database\Eloquent\Builder;
class JobSearchService
{
public function __construct(
private CacheService $cacheService
) {}
/**
* Search jobs with advanced filters
*/
@@ -188,36 +191,40 @@ class JobSearchService
*/
public function getFilterOptions(): array
{
return [
'job_types' => [
'full-time' => 'Full-time',
'part-time' => 'Part-time',
'contract' => 'Contract',
'temporary' => 'Temporary',
'internship' => 'Internship',
'freelance' => 'Freelance',
],
'experience_levels' => [
'entry' => 'Entry Level',
'mid' => 'Mid Level',
'senior' => 'Senior Level',
'lead' => 'Lead',
'executive' => 'Executive',
],
'posted_within' => [
1 => 'Last 24 hours',
7 => 'Last 7 days',
30 => 'Last 30 days',
90 => 'Last 3 months',
],
'sort_options' => [
'date' => 'Most Recent',
'date_asc' => 'Oldest First',
'salary_desc' => 'Highest Salary',
'salary_asc' => 'Lowest Salary',
'title' => 'Title A-Z',
'company' => 'Company A-Z',
],
];
$cacheKey = $this->cacheService->filterOptionsKey();
return $this->cacheService->remember($cacheKey, CacheService::CACHE_FILTER_OPTIONS, function () {
// Get actual distinct values from database for job types and experience levels
$jobTypes = Job::select('job_type')
->whereNotNull('job_type')
->distinct()
->pluck('job_type')
->toArray();
$experienceLevels = Job::select('experience_level')
->whereNotNull('experience_level')
->distinct()
->pluck('experience_level')
->toArray();
return [
'job_types' => $jobTypes,
'experience_levels' => $experienceLevels,
'posted_within' => [
1 => 'Last 24 hours',
7 => 'Last 7 days',
30 => 'Last 30 days',
90 => 'Last 3 months',
],
'sort_options' => [
'date' => 'Most Recent',
'date_asc' => 'Oldest First',
'salary_desc' => 'Highest Salary',
'salary_asc' => 'Lowest Salary',
'title' => 'Title A-Z',
'company' => 'Company A-Z',
],
];
});
}
}
+195
View File
@@ -0,0 +1,195 @@
<?php
namespace App\Services;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class QueryOptimizationService
{
/**
* Add eager loading constraints to prevent N+1 queries
*/
public function eagerLoadJobRelations(Builder $query): Builder
{
return $query->with([
'source:id,name',
'category:id,name,slug,icon',
'jobLocation:id,city,state,country',
]);
}
/**
* Optimize job listing query
*/
public function optimizeJobListingQuery(Builder $query): Builder
{
return $query
->select([
'id',
'title',
'company',
'location',
'job_type',
'experience_level',
'salary_min',
'salary_max',
'salary_currency',
'remote_allowed',
'posted_at',
'job_source_id',
'job_category_id',
'job_location_id',
'created_at',
])
->with([
'source:id,name',
'category:id,name,slug,icon',
'jobLocation:id,city,state,country',
]);
}
/**
* Analyze slow queries
*/
public function analyzeSlowQueries(int $threshold = 1000): array
{
// Enable query logging
DB::enableQueryLog();
// Get queries that took longer than threshold (in milliseconds)
$queries = DB::getQueryLog();
$slowQueries = array_filter($queries, function ($query) use ($threshold) {
return ($query['time'] ?? 0) > $threshold;
});
return array_map(function ($query) {
return [
'query' => $query['query'],
'bindings' => $query['bindings'],
'time' => $query['time'] . 'ms',
];
}, $slowQueries);
}
/**
* Get query explain plan
*/
public function explainQuery(string $sql, array $bindings = []): array
{
$explained = DB::select('EXPLAIN ' . $sql, $bindings);
return array_map(function ($row) {
return (array) $row;
}, $explained);
}
/**
* Optimize table (defragment and rebuild indexes)
*/
public function optimizeTable(string $table): void
{
DB::statement("OPTIMIZE TABLE {$table}");
}
/**
* Analyze table statistics for query optimizer
*/
public function analyzeTable(string $table): void
{
DB::statement("ANALYZE TABLE {$table}");
}
/**
* Get table size and index statistics
*/
public function getTableStats(string $table): array
{
$stats = DB::select("
SELECT
table_name,
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS size_mb,
table_rows,
ROUND((data_length / 1024 / 1024), 2) AS data_size_mb,
ROUND((index_length / 1024 / 1024), 2) AS index_size_mb
FROM information_schema.TABLES
WHERE table_schema = DATABASE()
AND table_name = ?
", [$table]);
return $stats ? (array) $stats[0] : [];
}
/**
* Get index usage statistics
*/
public function getIndexStats(string $table): array
{
$stats = DB::select("
SELECT
index_name,
column_name,
seq_in_index,
cardinality,
index_type
FROM information_schema.STATISTICS
WHERE table_schema = DATABASE()
AND table_name = ?
ORDER BY index_name, seq_in_index
", [$table]);
return array_map(function ($row) {
return (array) $row;
}, $stats);
}
/**
* Check for missing indexes based on slow queries
*/
public function suggestIndexes(string $table): array
{
$suggestions = [];
// Get columns that are frequently used in WHERE clauses without indexes
$unindexedColumns = DB::select("
SELECT DISTINCT column_name
FROM information_schema.COLUMNS
WHERE table_schema = DATABASE()
AND table_name = ?
AND column_name NOT IN (
SELECT column_name
FROM information_schema.STATISTICS
WHERE table_schema = DATABASE()
AND table_name = ?
)
", [$table, $table]);
foreach ($unindexedColumns as $column) {
$suggestions[] = [
'type' => 'missing_index',
'table' => $table,
'column' => $column->column_name,
'suggestion' => "Consider adding an index on {$column->column_name}",
];
}
return $suggestions;
}
/**
* Chunk large queries to reduce memory usage
*/
public function chunkQuery(Builder $query, int $chunkSize, callable $callback): void
{
$query->chunk($chunkSize, $callback);
}
/**
* Use cursor for memory-efficient iteration
*/
public function cursorQuery(Builder $query): \Illuminate\Support\LazyCollection
{
return $query->cursor();
}
}