Database Seeding là gì?

Database Seeding là gì?

Trong môi trường Developement mà thao tác với dữ liệu thực là chết người. Nên khi có 1 ứng dụng cần sử dụng API để xử lý hàng nghìn dữ liệu thì việc thực hiện test rất cần thiết và nếu tạo bằng tay data để test thì không ai rãnh vì thế tạo dữ liệu ảo là rất cần thiết.

Vậy việc đầu tiên sau khi có Database test thì chúng ta sẽ “Dummy Data” hay tạo dữ liệu ảo và tên gọi của việc này là Database seeding

Đối tượng dữ liệu nào nên sử dụng dữ liệu ảo?

Thường là mọi dữ liệu cần đúng kiểu và cấu trúc dữ liệu mà dữ liệu đó cần sự bảo mật thông tin.

Ví dụ:

  • Người dùng
  • Địa điểm
  • Số điện thoại
  • Email
  • Credit Card,…

Làm thế nào để tạo Seeder?

Công cụ Faker

Source code: Link Github

composer require fzaninotto/faker

Cách sử dụng

<?php
// Trỏ tới thư mục Autoload
require_once '/path/to/Faker/src/autoload.php';

// Tạo đối tượng Faker
$faker = Faker\Factory::create();
// Tạo dữ liệu ảo Tên người dùng
echo $faker->name;
 // Tạo dữ liệu ảo Địa chỉ
echo $faker->address;
  // Tạo dữ liệu ảo Đoạn văn
echo $faker->text;
// Nếu muốn tạo nhiều dữ liệu mẫu cùng lúc thì để trong vòng For nhé
for ($i=0; $i < 10; $i++) {
  echo $faker->name, "\n";
}

Sample code với Laravel Framework

<?php
use DB;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();
        foreach (range(1,10) as $index) {
            DB::table('users')->insert([
                'name' => $faker->name,
                'email' => $faker->email,
                'password' => bcrypt('secret'),
            ]);
        }
    }
}

Kết quả:

Faker gen?

Faker gen sẽ tạo sẵng những mẫu dữ liệu đã có format hoặc do chính bạn define cho nó. Xem thêm

<?php
$faker->randomDigit;
$faker->numberBetween(1,100);
$faker->word;
$faker->paragraph;
$faker->lastName;
$faker->city;
$faker->year;
$faker->domainName;
$faker->creditCardNumber;

Reference:

Nếu bạn cần Faker cho các ngôn ngữ khác thì có thể tham khảo bên dưới!

Sliding Sidebar

About Me

About Me

Hello, my name is Dũng (Johnny). Welcome to my blog.

As I’m a developer, I write about topics related to the field of programming, mainly from a technical point of view. On this blog you’ll find posts which encourage discussion, information about development trends, case studies, reviews, tutorials, tips on how to improve your effectiveness, and anything else that might be fascinating to people from the IT industry.
I love PHP, NodeJS, Java,... and Fullstack.