faker php测试数据库生成2

时间:2023-03-09 02:13:42
faker php测试数据库生成2

因内容太长,被csdn截断了,只好把另外的内容写到这里。


//Biased
// 在10到20之间得到一个随机数字,有更大的几率接近20
echo $faker->biasedNumberBetween($min = 10, $max = 20, $function = 'sqrt'),'<br>';
echo '<hr>'; //HtmlLorem
//生成不超过2个级别的HTML文档,在任何级别上不超过3个元素。
echo $faker->randomHtml(2,3),'<br>';
echo '<hr>';

三个特别的修饰方法:

//提供了三个特殊的修饰方法,unique(),optional(),和valid(),被任何provider之前调用。
//unique()强制提供者返回唯一值,当没有新的唯一值可以生成时,抛出异常
//加入$reset = true,会自动加前缀,避免异常
$values = array();
for($i = 0; $i < 15; $i++){
$values [] = $faker -> unique($reset = true) -> randomDigit;
}
print_r($values); //optional()有时会绕过提供程序而返回默认值(默认为NULL)
$values = array();
for ($i=0; $i < 10; $i++) {
$values []= $faker->optional()->randomDigit;
}
var_dump($values); // [1, 4, null, 9, 5, null, null, 4, 6, null] // optional()接受权重参数以指定接收默认值的概率。
// 0将始终返回默认值; 1将始终返回提供者。默认权重为0.5(50%几率)。
$faker->optional($weight = 0.1)->randomDigit; // 90% 的可能性为 NULL
$faker->optional($weight = 0.9)->randomDigit; // 10% 的可能性为 NULL //optional()接受默认参数以指定要返回的默认值。
$faker->optional($weight = 0.5, $default = false)->randomDigit; // 50% 的可能性为 FALSE
$faker->optional($weight = 0.9, $default = 'abc')->word; // 10% 的可能性为 'abc' //passthrough()只返回指定的任何值。
$faker->optional()->passthrough(mt_rand(5, 15)); //valid()仅根据传递的验证函数接受有效值
$values = array();
$evenValidator = function($digit) {
return $digit % 2 === 0; //是偶数才返回
}; for($i=0; $i < 10; $i++) {
$values []= $faker->valid($evenValidator)->randomDigit;
}
print_r($values); // [0, 4, 8, 4, 2, 6, 0, 8, 8, 6] //就像unique(),valid()在无法生成有效值时抛出溢出异常
$values = array();
try {
//$faker->valid($evenValidator)->randomElement(1, 3, 5, 7, 9);
} catch (\OverflowException $e) {
echo "Can't pick an even number in that set!";
}

使用自己的数据

在faker->src->Faker->Provider->zh_CN文件夹下新建My.php

faker php测试数据库生成2

参考系统自带的数据格式编写,My.php内容如下:

<?php

namespace Faker\Provider\zh_CN;

class My extends \Faker\Provider\Base
{ protected static $mySite = array(
'www.aaa.com',
'www.bbb.com',
'www.ccc.com',
'www.ddd.com'
);
public function mySite()
{
return static::randomElement(static::$mySite);
} }

在项目中的使用:

//调用自定义的内容先要加入
$faker -> addProvider(new \Faker\provider\zh_CN\My($faker));
echo $faker->mySite;