Faker 是一個用來生成數(shù)據(jù)庫實例數(shù)據(jù)的工具。Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
installation
composer require fzaninotto/faker
basic usage
Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.
<?php
require_once '/path/to/Faker/src/autoload.php';
$faker = Faker\Factory::create();
echo $faker->name;
echo $faker->address;
echo $faker->text;
echo $faker->email;
在src/Faker/Generator.php 中狠多種類型可以參考,包括file,image,uuid 各種數(shù)據(jù)類型。
在laravel 中的使用
Laravel artisan 的 tinker 是一個 REPL (read-eval-print-loop) ,REPL 是指 交互式命令行界面,它可以讓你輸入一段代碼去執(zhí)行,并把執(zhí)行結果直接打印到命令行界面里。通過php artisan tinker 和faker結合之后,可以直接用來測試。Tinker 是 Laravel 自帶的 REPL,基于 PsySH 構建而來。同樣需要psysh的支持。
使用示例如下:
php artisan tinker
//這是是使用faker的工廠模式生成數(shù)據(jù),其中App\User需要在database\factories\ModelFactories 文件中提前寫好需要設置的數(shù)據(jù)類型和字段
factory("App\User::class",10)->create();
//查詢
APP\User::all();
App\User::count();
//增加數(shù)據(jù)
$user = new App\User;
$user->name = "Wruce Bayne";
$user->email = "iambatman@savegotham.com";
$user->save();
// 刪除數(shù)據(jù)
$user = App\User::find(1);
$user->delete();
// 還可以查看doc幫助
doc dd
doc app
// 顯示源代碼
show <functionName>