Repository Pattern Nedir? Temiz Veri Katmanı

 



Repository Pattern, veritabanı işlemlerini (CRUD – Create, Read, Update, Delete) uygulama mantığından ayırmak için kullanılan bir tasarım desenidir.

Basitçe:

Kodun içinde DB::table() ya da Model::find() gibi veritabanı işlemlerini doğrudan yazmak yerine, tüm bu işlemleri ayrı bir sınıfta (repository) toplarız.


Neden Kullanılır?

  1. Kodun okunabilirliğini artırır.

  2. Veritabanı işlemlerini merkezileştirir.

  3. Test yazmayı kolaylaştırır (mock edilebilir).

  4. Bir ORM’den diğerine geçişte kolaylık sağlar.

  5. Controller'ları sade tutar.



Gerçek Hayat Örneği

Diyelim ki bir blog sistemimiz var ve Post veritabanı tablosuna erişmemiz gerekiyor.
Repository pattern ile veritabanı işlemlerini şu şekilde soyutlarız:


1. PostRepository Interface


<?php
//PostRepositoryInterface.php
interface PostRepositoryInterface {
public function getAll();
public function find($id);
public function create(array $data);
}



2.MySQLPostRepository (Uygulama sınıfı)

<?php
//MySQLPostRepository
class MySQLPostRepository implements PostRepositoryInterface {
protected $pdo;

public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}

public function getAll() {
$stmt = $this->pdo->query("SELECT * FROM posts");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function find($id) {
$stmt = $this->pdo->prepare("SELECT * FROM posts WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}

public function create(array $data) {
$stmt = $this->pdo->prepare("INSERT INTO posts (title, content) VALUES (?, ?)");
return $stmt->execute([$data['title'], $data['content']]);
}
}



3.Controller (Kullanım)

<?php
//PostController
class PostController {
protected $postRepo;

public function __construct(PostRepositoryInterface $postRepo) {
$this->postRepo = $postRepo;
}

public function index() {
$posts = $this->postRepo->getAll();
foreach ($posts as $post) {
echo $post['title'] . "<br>";
}
}
}



4.Uygulama başlatma (manual dependency injection)


<?php
//index.php
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
$postRepo = new MySQLPostRepository($pdo);
$controller = new PostController($postRepo);
$controller->index();


Gerçek Projelerde Kullanım Alanları

  • Laravel gibi frameworklerde Repository Pattern çok yaygındır.

  • Geniş ölçekli sistemlerde (e-ticaret, CRM, blog platformları)

  • Birden fazla veri kaynağının (MySQL, API, cache) kullanılacağı sistemlerde



Avantajları

  • Kod tekrarı azalır.

  • Daha test edilebilir hale gelir.

  • Kod mantıksal katmanlara ayrılır (Separation of Concerns).

  • Veritabanı değişiklikleri sistemin geneline yayılmaz.















Related Posts

Repository Pattern Nedir? Temiz Veri Katmanı
4/ 5
Oleh