Fixture & Faker di API Platform
Untuk mengisi data dummy dalam pengembangan API Platform, kita dapat menggunakan Doctrine Fixtures dan Faker. Ini sangat membantu saat ingin menguji API dengan data realistis tanpa harus memasukkan data manual.
1. Instalasi Package
Pertama, install dependency yang diperlukan:
composer require --dev doctrine/doctrine-fixtures-bundle fakerphp/faker
Kemudian aktifkan DoctrineFixturesBundle di config/bundles.php (otomatis jika menggunakan Flex):
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
2. Membuat Class Fixture
Buat file fixture di src/DataFixtures/:
mkdir -p src/DataFixtures
touch src/DataFixtures/AppFixtures.php
Isi contoh AppFixtures.php
:
<?php
namespace App\DataFixtures;
use App\Entity\Author;
use App\Entity\Book;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
$faker = Factory::create();
// Buat beberapa Author
$authors = [];
for ($i = 0; $i < 10; $i++) {
$author = new Author();
$author->setName($faker->name());
$manager->persist($author);
$authors[] = $author;
}
// Buat beberapa Book terkait Author
for ($i = 0; $i < 30; $i++) {
$book = new Book();
$book->setTitle($faker->sentence(3));
$book->setAuthor($faker->randomElement($authors));
$manager->persist($book);
}
$manager->flush();
}
}
3. Menjalankan Fixture
Setelah membuat class fixture, jalankan command berikut:
php bin/console doctrine:fixtures:load
⚠️ Perhatian: Command ini akan menghapus semua data lama di database (purge).
Jika ingin mengkonfirmasi sebelum menghapus data, gunakan:
php bin/console doctrine:fixtures:load --no-interaction
4. Struktur Data Setelah Fixture
Endpoint GET /api/books
sekarang akan memiliki data seperti:
[
{
"id": 1,
"title": "Misteri Dunia",
"author": "/api/authors/5"
},
{
"id": 2,
"title": "Rahasia Masa Depan",
"author": "/api/authors/3"
},
...
]
5. Tips Praktis
-
Buat banyak fixture kecil: misalnya AuthorFixtures.php, BookFixtures.php, agar lebih modular.
-
Gunakan Faker\Factory::create('id_ID') untuk data berbahasa Indonesia.
-
Untuk environment tertentu (contoh: hanya dev), bungkus dengan pengecekan:
if ($_ENV['APP_ENV'] !== 'dev') {
return;
}
- Gunakan
Doctrine\Common\DataFixtures\DependentFixtureInterface
jika fixture Anda saling bergantung.
6. Contoh Menggunakan Dependent Fixture
Jika ingin fixture Book tergantung pada Author:
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
class BookFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager)
{
// ambil referensi author yang dibuat di AuthorFixtures
}
public function getDependencies()
{
return [
AuthorFixtures::class,
];
}
}