PSR (PHP Standards Recommendations), PHP topluluğunun ortak kod yazım kurallarıdır. Farklı ekiplerin kodunun birbirini anlamasını sağlar.
PSR-12 — Kod Biçimlendirme
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Blog;
use PDO;
final class BlogService
{
public function __construct(
private readonly PDO $pdo,
) {}
public function findBySlug(string $slug): ?Blog
{
$stmt = $this->pdo->prepare(
'SELECT * FROM blogs WHERE slug = ? LIMIT 1'
);
$stmt->execute([$slug]);
$row = $stmt->fetch();
return $row ? Blog::fromRow($row) : null;
}
}
PSR-4 — Otomatik Yükleme
App\Services\BlogService
→ app/Services/BlogService.php
Namespace, dizin yoluna birebir karşılık gelir. Bu, Composer'ın PSR-4 autoloader'ının çalışma prensibidir.
PSR-3 — Günlükleme
<?php
$logger->info('Siparis olusturuldu', [
'siparis_id' => $id,
'tutar' => $tutar,
]);
$logger->error('Odeme basarisiz', ['hata' => $e->getMessage()]);
PSR-7 — HTTP Mesaj Soyutlaması
PSR-7, HTTP istek ve yanıt nesneleri için standart arayüz tanımlar. PSR-15 (middleware) ve PSR-11 (container) bunun üzerine kurulur.
<?php
// PSR-15 ara katman ornegi
final class OturumKontrolMiddleware implements MiddlewareInterface
{
public function process(Request $request, RequestHandlerInterface $handler): ResponseInterface
{
if (!$this->oturum->girisYapildiMi()) {
return $this->redirectYaniti('/giris');
}
return $handler->handle($request);
}
}
Sık yapılan biçim hataları
<?php
// PSR-12 ihlalleri
if ($a) { echo $a; } // tek satirda blok gerekmez
$x = array(1, 2); // PSR-12: array() degil []
class foo{} // sinif adi PascalCase
function Foo(){} // fonksiyon adi camelCase
$varname = 1; // degisken adi snake_case
PHP-CS-Fixer ile otomatik düzeltme
# Kurulum
composer require --dev friendsofphp/php-cs-fixer
# .php-cs-fixer.php
# Kaldirilacak kurallar
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude(['vendor', 'node_modules']);
return (new PhpCsFixer\Config())
->setRules([
'@PSR12' => true,
'@Symfony' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sort_algorithm' => 'alpha'],
'no_unused_imports' => true,
])
->setFinder($finder);
# Uygula
vendor/bin/php-cs-fixer fix
# Git hook olarak calistir
# .git/hooks/pre-commit
vendor/bin/php-cs-fixer fix --dry-run --diff
Statik analiz
composer require --dev phpstan/phpstan
vendor/bin/phpstan analyse app/ --level=5
# Level 0 → yazim hatalari
# Level 5 → tip ve mantik hatalari
# Level 9 → en katı (proje yavaslar)
Sonuç
PSR uyumlu kod, araçların (statik analiz, otomatik düzeltme, dokümantasyon) çalışmasını sağlar. Biçim tartışmalarını araçlara bırakmak, ekip enerjisini gerçek sorunlara ayırır.
Arivo'da PHP scriptler, temalar ve eklentiler bulun. Kurulum desteği dahil.
Mağazaya Git