dbt / model-factory
10.0.1
2024-08-07 15:23 UTC
Requires
- php: ^8.1|^8.2
- fakerphp/faker: ^1.9.3
- illuminate/database: ^10.0
- illuminate/support: ^10.0
- laravel/legacy-factories: ^1.3
Requires (Dev)
- laravel/pint: ^1.17
- orchestra/testbench: ^8.0
- phpunit/phpunit: ^9.5
- rector/rector: ^1.2
- vimeo/psalm: ^4.0
README
基于类模型的Laravel模型工厂
本包是替代将模型工厂放在普通PHP文件中的方案。
入门指南
先决条件
本包需要PHP 7.1.3或更高版本,illuminate/support@^5.7
,以及illuminate/database@^5.7
。
安装
通过Composer
composer require dbt/model-factory
测试
运行
composer test
配置
使用php artisan vendor:publish
命令发布model-factory.php
配置文件,或者从本仓库复制该文件。Laravel应自动发现服务提供者。
模型工厂看起来像这样
use Dbt\ModelFactory\ModelFactory; class MyModelFactory extends ModelFactory { protected $model = MyModel::class; /** * This is the main factory definition. * @return array */ public function definition (): array { return [ 'my_string_column' => $this->faker->name, ]; } /** * This will happen after the model is created. * @return void */ public function after (MyModel $model): void { // Do some stuff to the model. } /** * This is a factory state. * @return array */ public function myState (): array { return [ 'my_int_column' => rand(1, 10), ]; } /** * This will happen after the model is created in the given state. * @return void */ public function afterMyState (MyModel $model): void { // Do some stuff to the model. } }
要注册您的模型工厂,将其包含在配置文件中
'classes' => [ // ... MyModelFactory::class, ];
用法
使用factory(...)
函数
您的模型工厂将像往常一样注册到Laravel中,因此可以使用Laravel的全局factory()
函数调用它们
// Factory without state. $model = factory(MyModel::class)->create(); // Factory with state. $modelWithState = factory(MyModel::class)->states('myState')->create();
使用Create
类
如果您更喜欢一种更表达式的创建测试模型的方式,请尝试使用Create
类
$model = Create::a(new MyModel, new Count(10), new States('myState'), new Overrides(['column' => 'value']));
方法定义需要一个模型,后跟任意数量的Param
参数,顺序和组合均可。
// Create a model with defaults. $model = Create::a(new MyModel); // The following are all equivalent: Create::a(new MyModel, new Count(...), new States(...), new Overrides(...)); Create::a(new MyModel, new States(...), new Count(...), new Overrides(...)); Create::a(new MyModel, new States(...), new Overrides(...), new Count(...)); // Etc.
许可证
MIT。随意使用。