如何在Laravel中实现自己的Faker提供程序 [英] How to implement your own Faker provider in Laravel
问题描述
我想为Laravel中的Faker创建一个自定义提供程序(例如,一个用于随机建筑物名称的提供程序).
I want to create a custom provider for Faker in Laravel (e.g. one for a random building name).
自定义提供程序应在哪里存储在我的应用程序中,以及如何使用它?
Where do I store the custom provider in my application and how do I use it?
推荐答案
您应使用php artisan
生成自定义提供程序...
You should use php artisan
to generate the custom provider...
在命令行上,导航至应用程序的根目录,然后输入...
On the command line, navigate to the root of your app and type...
php artisan make:provider FakerServiceProvider
那应该在app/Providers
文件夹中生成一个新的提供程序.这是我的注册函数看起来像伪造者文档中的示例.
That should generate a new provider in the app/Providers
folder. Here is what my register function looks like going off the example in the faker docs.
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('Faker', function($app) {
$faker = \Faker\Factory::create();
$newClass = new class($faker) extends \Faker\Provider\Base {
public function title($nbWords = 5)
{
$sentence = $this->generator->sentence($nbWords);
return substr($sentence, 0, strlen($sentence) - 1);
}
};
$faker->addProvider($newClass);
return $faker;
});
}
我在这里使用匿名类.如果您有php<如图7所示,您可能需要使用新的提供程序类创建一个新文件并将其传递.请确保还将这个新的提供程序也添加到app/config.php
中的providers
数组中.
I'm using an anonymous class here. If you have php < 7, you would likely need to create a new file with your new provider class and pass that in. Make sure you also add this new provider to your providers
array in app/config.php
.
现在,它已经注册,您可以使用以下方法来获取新的伪造者类...
Now that it's registered, you can grab your new faker class using the following...
$faker = app('Faker');
echo $faker->title;
此外,如果您浏览了 https://laravel.com/docs/5.2/facades上的文档, 您还应该能够轻松制作Faker
门面.完成所有繁重的工作,您只需创建新的Facade类,让getFacadeAccessor
返回'Faker'
,然后将其添加到app/config.php
中的facades
数组中即可.
Additionally, if you go through the docs at https://laravel.com/docs/5.2/facades you should also be able to make a Faker
facade quite easily. All the heavy lifting is done, you'd just have to create the new facade class, have getFacadeAccessor
return 'Faker'
, and add it to your facades
array in app/config.php
.
然后您可以像这样简单地使用它...
Then you can simply use it like so...
echo Faker::title;
这篇关于如何在Laravel中实现自己的Faker提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!