Lesson 6 of 6
Mini Project: Blog System - Part 11 (CLI Tools, Cache Layer, PHPStan)
Add three production-ready features to the Blog System: (1) a CLI command runner for maintenance tasks, (2) a Redis cache layer in PostService, and (3) PHPStan + PHPUnit integration with a complete CI-ready quality pipeline.
Blog Part 11 - CLI, Cache & Quality
#!/usr/bin/env php
<?php
// cli/blog - single entry point for all CLI commands
declare(strict_types=1);
if (PHP_SAPI !== "cli") { die("CLI only.
"); }
require __DIR__ . "/../vendor/autoload.php";
use DotenvDotenv;
Dotenv::createImmutable(__DIR__ . "/../")->load();
// ── Command registry ──────────────────────────────────────────
$commands = [
"publish:scheduled" => PublishScheduledCommand::class,
"cache:clear" => CacheClearCommand::class,
"posts:export" => ExportPostsCsvCommand::class,
"db:seed" => SeedDatabaseCommand::class,
];
$commandName = $argv[1] ?? null;
if ($commandName === null || !isset($commands[$commandName])) {
echo "Available commands:
";
foreach (array_keys($commands) as $name) echo " php cli/blog $name
";
exit(1);
}
// ── Bootstrap container ───────────────────────────────────────
$container = new Container();
// ... (register bindings as in Module 10)
$options = getopt("", ["limit:", "dry-run", "force"]);
/** @var Command $command */
$command = $container->get($commands[$commandName]);
$exitCode = $command->handle($options);
exit($exitCode);
// Usage:
// php cli/blog publish:scheduled --limit=20
// php cli/blog cache:clear --force
// php cli/blog posts:export
// ── CacheClearCommand ────────────────────────────────────────
class CacheClearCommand extends Command {
public function __construct(private readonly CacheInterface $cache) {}
public function handle(array $options): int {
$force = isset($options["force"]);
if (!$force) {
$this->error("Use --force to confirm cache clearing.");
return 1;
}
$this->info("Clearing application cache...");
$this->cache->clear();
opcache_reset();
$this->info("Done. Cache cleared and Opcache reset.");
return 0;
}
}
// ── PostService with Redis cache + stampede protection ────────
class PostService {
public function __construct(
private readonly PostRepositoryInterface $repo,
private readonly CacheInterface $cache,
private readonly EventDispatcher $events,
) {}
public function getPost(int $id): Post {
return $this->cache->remember("post:$id", 3600, fn() =>
$this->repo->findById($id) ?? throw new NotFoundException("Post #$id not found.")
);
}
public function listPublished(int $page = 1, int $perPage = 10): array {
$key = "feed:p{$page}:pp{$perPage}";
return $this->cache->remember($key, 300, fn() =>
$this->repo->findAllPublished($perPage, ($page - 1) * $perPage)
);
}
public function publishPost(int $id): Post {
$post = $this->repo->findById($id) ?? throw new NotFoundException("Post #$id not found.");
$published = $post->publish();
$this->repo->save($published);
// Invalidate
$this->cache->delete("post:$id");
for ($i = 1; $i <= 20; $i++) {
$this->cache->delete("feed:p{$i}:pp10");
}
$this->events->dispatch(new PostPublished($published));
return $published;
}
}
// ── composer.json scripts (from Module 10 + test) ─────────────
// "scripts": {
// "test": "phpunit tests --colors=always",
// "analyse": "phpstan analyse src tests --level=8",
// "cs": "phpcs src --standard=PSR12",
// "cs-fix": "phpcbf src --standard=PSR12",
// "qa": ["@test", "@analyse", "@cs"]
// }
// composer qa → runs all three in sequenceQuick Quiz
Module Quiz
What is the difference between APCu and Redis for PHP caching?
Tip
Tip
Practice Mini Project Blog System Part 11 CLI Tools Cache Layer PHPStan in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Mini Project: Blog System - Part 11 (CLI Tools, Cache Layer, PHPStan)
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Blog System Part 11 CLI Tools Cache Layer PHPStan from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project Blog System Part 11 CLI Tools Cache Layer PHPStan is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?