Hướng dẫn dùng Faker để tạo dữ liệu cho môi trường phát triển

Chào các bạn, hôm nay tôi sẽ giới thiệu các bạn dùng một thư viện đó là Faker để tạo ra giữ liệu giả cho trang web của chúng ta. Như các bạn biết việc dùng dữ liệu thật  trong môi trường development là một ý tưởng rất là tệ.

Bạn có thể tạo dữ liệu trực tiếp thông qua database console hay GUI hoặc một đoạn mã script php nào đó, có thể đáp ứng nhu cầu của bạn nhưng dữ liệu được tao ra lúc này có thể không giống thực tế lắm. Với thư viện Faker bạn có  tạo ra dữ liệu giả nhưng không khác gì dữ liệu thật, để tôi sẽ cho bạn thấy trong bài viết này.

Cài Đặt

Chúng ta có nhiều cách cài đặt nó, bạn có thể tải nó về song sau đó copy vào thư mục project của bạn, nhưng tôi khuyên bạn nên dùng composer cho công việc này, để cài đặt nó bạn chỉ cần chạy lệnh này trong project của bạn:

composer require "fzaninotto/faker"

Sau đó chỉ cần nạp tập tin autoload.php thế là song, quá đơn giản phải không nầo ,is right ?

Cách Sử Dụng

Do chúng ta cài Faker thông qua commposer nên để sử dụng nó bạn chỉ cần nạp tập tin autoload trong thư mục mà bạn muốn dùng, thường là tập tin index.php

require_once '/path/to/vendor/autoload.php';

Mọi thứ cấu hình coi như đã xong, việc kế tiếp là bạn khởi tạo một class của nó, chúng ta hãy xem xét ví dụ dưới đây:

[...]
// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();

// generate data by accessing properties
echo $faker->name;
// 'Lucy Cechtelar';
echo $faker->address;
// "426 Jordy Lodge
// Cartwrightshire, SC 88120-6700"
echo $faker->text;
// Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
// beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
// amet quidem. Iusto deleniti cum autem ad quia aperiam.
// A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui
// quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur
// voluptatem sit aliquam. Dolores voluptatum est.

Nếu như bạn nhìn kỹ  đoạn code ở trên thì bạn hiểu nó làm gì phải không ?, như bạn biết dữ liệu có nhiều định dạng khác nhau chẳn hạn dữ liệu  dành cho thông tin user, company, address.. Faker cung cấp cho ta một dạng data đó là Formatters

Formatters

Dưới đây là các thành phần mà Formatters cung cấp cho chúng ta:

Faker\Provider\Base

randomDigit             // 7
randomDigitNotNull      // 5
randomNumber($nbDigits = NULL) // 79907610
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
numberBetween($min = 1000, $max = 9000) // 8567
randomLetter            // 'b'
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
randomElement($array = array ('a','b','c')) // 'b'
shuffle('hello, world') // 'rlo,h eoldlw'
shuffle(array(1, 2, 3)) // array(2, 1, 3)
numerify('Hello ###') // 'Hello 609'
lexify('Hello ???') // 'Hello wgt'
bothify('Hello ##??') // 'Hello 42jz'
asciify('Hello ***') // 'Hello R6+'
regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // [email protected]

Faker\Provider\Lorem

word                    // 'aut'
words($nb = 3)          // array('porro', 'sed', 'magni')
sentence($nbWords = 6)  // 'Sit vitae voluptas sint non voluptates.'
sentences($nb = 3)      // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.')
paragraph($nbSentences = 3) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.'
paragraphs($nb = 3)     // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.')
text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.'

Faker\Provider\en_US\Company and Faker\Provider\en_US\PhoneNumber

phoneNumber             // '132-149-0269x3767'
catchPhrase             // 'Monitored regional contingency'
bs                      // 'e-enable robust architectures'
company                 // 'Bogan-Treutel'
companySuffix           // 'and Sons'

Faker\Provider\DateTime

unixTime($max = 'now')                // 58781813
dateTime($max = 'now')                // DateTime('2008-04-25 08:37:17')
dateTimeAD($max = 'now')              // DateTime('1800-04-29 20:38:49')
iso8601($max = 'now')                 // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now') // DateTime('2003-03-15 02:00:49')
dateTimeThisCentury($max = 'now')     // DateTime('1915-05-30 19:28:21')
dateTimeThisDecade($max = 'now')      // DateTime('2007-05-29 22:30:48')
dateTimeThisYear($max = 'now')        // DateTime('2011-02-27 20:52:14')
dateTimeThisMonth($max = 'now')       // DateTime('2011-10-23 13:46:23')
amPm($max = 'now')                    // 'pm'
dayOfMonth($max = 'now')              // '04'
dayOfWeek($max = 'now')               // 'Friday'
month($max = 'now')                   // '06'
monthName($max = 'now')               // 'January'
year($max = 'now')                    // '1993'
century                               // 'VI'
timezone                              // 'Europe/Paris'

Faker\Provider\en_US\Text

email                   // '[email protected]'
safeEmail               // '[email protected]'
freeEmail               // '[email protected]'
companyEmail            // '[email protected]'
freeEmailDomain         // 'yahoo.com'
safeEmailDomain         // 'example.org'
userName                // 'wade55'
password                // 'k&|X+a45*2['
domainName              // 'wolffdeckow.net'
domainWord              // 'feeney'
tld                     // 'biz'
url                     // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html'
slug                    // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum'
ipv4                    // '109.133.32.252'
localIpv4               // '10.242.58.8'
ipv6                    // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c'
macAddress              // '43:85:B7:08:10:CA'

Faker\Provider\Internet

userAgent              // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350'
chrome                 // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312'
firefox                // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6'
safari                 // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3'
opera                  // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00'
internetExplorer       // 'Mozilla/5.0 (compatibl'

còn nhiều dạng dữ liệu nữa bạn có thể xem đầy đủ ở đây

Unique Và Optonal

Khi bạn cần dử liệu có dạng là duy nhất chẳng hạn như địa chỉ email hay số điện thoại thì Faker nó cung cấp cho ta phương thức unique bạn hãy xem ví dụ dưới đây để hiểu nó:

// unique() forces providers to return unique values
$values = array();
for ($i=0; $i < 10; $i++) {
// get a random digit, but always a new one, to avoid duplicates
$values []= $faker->unique()->randomDigit;
}
print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3

Localization

Đôi khi chúng ta muốn dữ liệu là của một quốc gia nào đó, chẳn hạn như tên của người quốc gia đó thì Faker nó cung cấp cho ta
một lớp để sử dụng đó là Faker\Factory  để trả lại dữ liệu địa phương. Nếu không có tham số của các quốc gia nào đó thì mặt định nó
lấy tham số là en_EN.

<?php
$faker = Faker\Factory::create('fr_FR'); // create a French faker
for ($i=0; $i < 10; $i++) {
echo $faker->name, "\n";
}
// Luce du Coulon
// Auguste Dupont
// Roger Le Voisin
// Alexandre Lacroix
// Jacques Humbert-Roy

Để xem Faker nó hỗ trợ các quốc gia nào bạn có thể xem tại đây

Dữ Liệu Tổng Quát Khi Seeding

Nếu như bạn muốn luôn luôn có dữ liệu tổng quát mỗi khi bạn sử dụng nó cho Unit test thì Faker nó cung cấp cho cho ta một phương thức
Seed để làm điều đó, chỉ cần gọi nó trước mỗi khi chaỵ Faker

<?php
$faker = Faker\Factory::create();
$faker->seed(1234);

echo $faker->name; // 'Jess Mraz I';

Provider Faker

Mặc định lớp Faker/Generator không thể hiểu được tất cả các các tùy chọn Faker do đó bạn cần phải cung cấp cho nó Faker/Provider để
nó có thể hiểu được, hãy xem ví dụ bên dưới để hiểu rõ hơn

<?php
$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Person($faker));
$faker->addProvider(new Faker\Provider\en_US\Address($faker));
$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker));
$faker->addProvider(new Faker\Provider\en_US\Company($faker));
$faker->addProvider(new Faker\Provider\Lorem($faker));
$faker->addProvider(new Faker\Provider\Internet($faker));

Nó có nghĩa là khi bạn truy cập một thuộc tính của Faker, nó sẽ truy cập một Provider tương ứng trong Faker chẳn hạn khi bạn gọi $faker->name
sẽ truy cập đến Faker\Provider\Person::name()

Ứng Dụng Faker Với Phalcon PHP

Cho tới bây giờ bạn đã hiểu Faker là gì rồi phải không nào, sau đây tôi sẽ sử dụng nó để tạo ra một số category , posts và users trong ứng dụng của tôi mà cụ thể là forum phalcontip.com của tôi, mã nguồn đầy đủ các bạn có thể xem trên Github.

require 'cli-bootstrap.php';

$faker = Faker\Factory::create();
$log   = new Phalcon\Logger\Adapter\Stream('php://stdout');

$log->info('Start');

/** @var Phalcon\Db\AdapterInterface $database */
$database = $di->getShared('db');

$database->begin();

for ($i = 0; $i <= 20; $i++) {
$title       = $faker->company;
$description = $faker->text;

$category               = new PhalconTip\Models\Categories();
$category->name         = $title;
$category->slug         = Phalcon\Tag::friendlyTitle($title);
$category->number_posts = 0;
$category->no_bounty    = 'N';
$category->no_digest    = 'N';
$category->description  = $description;

if (!$category->save()) {
var_dump($category->getMessages());
$database->rollback();
die;
}

$log->info('Category: ' . $category->name);
}

for ($i = 0; $i <= 50; $i++) {
$user           = new PhalconTip\Models\Users();
$user->name     = $faker->name;
$user->login    = $faker->userName;
$user->email    = $faker->email;
$user->timezone = $faker->timezone;

if (!$user->save()) {
var_dump($user->getMessages());
$database->rollback();
die;
}

$log->info('User: ' . $user->name);
}
$database->commit();

$categoryIds = PhalconTip\Models\Categories::find(['columns' => 'id)->toArray();
$userIds     = PhalconTip\Models\Users::find(['columns' => 'id)->toArray();

$database->begin();
for ($i = 0; $i <= 500; $i++) {
$title   = $faker->company;
$content = $faker->text();

$post          = new PhalconTip\Models\Posts();
$post->title   = $title;
$post->slug    = Phalcon\Tag::friendlyTitle($title);
$post->content = $content;


$userRandId     = array_rand($userIds);
$post->users_id = $userIds[$userRandId]['id;

$categoryRandId      = array_rand($categoryIds);
$post->categories_id = $categoryIds[$categoryRandId]['id;

if (!$post->save()) {
var_dump($post->getMessages());
$database->rollback();
die;
}

$log->info('Post: ' . $post->title);
}
$database->commit();

$postIds = PhalconTip\Models\Posts::find(['columns' => 'id)->toArray();

$database->begin();
for ($i = 0; $i <= 1000; $i++) {
$reply = new \PhalconTip\Models\PostsReplies();

$reply->content = $faker->paragraph();

$postRandId      = array_rand($postIds);
$reply->posts_id = $postIds[$postRandId]['id;

$userRandId      = array_rand($userIds);
$reply->users_id = $userIds[$userRandId]['id;

if (!$reply->save()) {
var_dump($reply->getMessages());
$database->rollback();
die;
}

$reply->post->number_replies++;
$reply->save();

$log->info('Reply to post: ' . $reply->posts_id);
}

$database->commit();

sau khi bạn clone mã nguồn về để chạy xem nó hoạt đông như thế nào chỉ cần chạy lệnh bên dưói đây:

php scripts/random-entries.php

Kết Luận

Việc dùng dữ liệu thật để cho môi trường phát triển  là một ý tưởng rất tồi, cũng như đôi khi ta cần có mẫu dữ liệu giả với số lượng lớn với nhưng thành phần nó gần giống dữ liệu thật thì việc làm thủ công cực kỳ khó khăn, do đó việc dùng Faker sẽ giúp chúng ta giải quyết các vấn đề trên khá dễ dàng.

Cảm ơn bạn đã đọc bài viết này, như mọi khi hãy chia sẽ cảm nhận của bạn về bài viết này:)!

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *