kununu/data-fixtures

为任何存储加载数据固定值

v12.0.0 2024-09-18 08:27 UTC

README

在kununu,我们在测试以及开发与测试环境中都依赖于数据固定值。关于固定值的良好定义可以参考DoctrineFixturesBundle的文档,本包的设计与实现主要基于此。

固定值用于将“假”数据集加载到数据库中,这些数据可以用于测试或在你开发应用程序时提供一些有趣的数据。

kununu/data-fixtures是什么?

此包提供了一种简单的方法来管理和执行任何存储机制的数据固定值的加载。其设计与实现主要基于Doctrine数据固定值包。如果你对我们的创建此包的原因感兴趣,请查看Why kununu/data-fixtures?

固定值类型

目前,此包支持以下类型的固定值

还可以查看Directory Loader以了解如何从目录中的文件加载固定值。

如果你对了解包的概念感兴趣,或者需要创建一个新的固定值类型,请查看如何创建新的固定值类型

安装

1. 将kununu/data-fixtures添加到你的项目

在安装此包之前请注意

  • 你拥有你加载的固定值
  • 此包不应在生产模式下使用!
composer require --dev kununu/data-fixtures

2. 启用任何固定值类型

为了启用你感兴趣的固定值类型,请查看它们的文档

追加固定值

默认情况下,加载固定值时,数据存储将被清除。如果你想更改此行为并追加固定值,可以在任何执行器中将第二个参数传递为false

// By default, the data storage is purged
$executor->execute($loader->getFixtures());
// If you want you can `append` the fixtures instead of purging the database
$executor->execute($loader->getFixtures(), true);

加载固定值

为了加载固定值,默认的Loader提供了一些选项

  1. loadFromDirectory(string $dir)
  2. loadFromFile(string $fileName)
  3. loadFromClassName(string $className)
  4. addFixture(FixtureInterface $fixture)
<?php
declare(strict_types=1);

use Kununu\DataFixtures\Loader\ConnectionFixturesLoader;

$loader = new ConnectionFixturesLoader();
$loader->loadFromDirectory('/your/directory/');
$loader->loadFromFile('/your/file.php');
$loader->loadFromClassName(MyFixtureSql::class);
$loader->addFixture(new MyFixtureSql());

可初始化的固定值

如果您希望您的固定值类能够初始化,可以实现InitializableFixtureInterface

public function initializeFixture(mixed ...$args): void;

然后在加载固定值之前,您需要在Loader中注册它们

<?php
declare(strict_types=1);

use Kununu\DataFixtures\Loader\ConnectionFixturesLoader;

$loader = new ConnectionFixturesLoader();

$this->loader->registerInitializableFixture(
	YourFixtureClass::class,
	// 1st argument
	1, 
	// 2nd argument
	'This is an argument that will be passed to initializeFixture of YourFixtureClass',
	// 3rd argument
	[
		'field'    => 'field-name',
		'value' => 10,
	],
	// 4th argument
	$anInstanceOfOneOfYourOtherClasses
	// Pass as many arguments as you like...
);

$loader->addFixture(new YourFixtureClass());

贡献

如果您有兴趣贡献,请阅读我们的贡献指南

测试

如果还没有,首先安装composer依赖项

composer install

通过执行以下操作来运行测试

vendor/bin/phpunit

运行不带覆盖率报告的测试

composer install
composer test

运行带覆盖率报告的测试

composer install
composer test-coverage

Continuous Integration Quality Gate Status