adamwathan/faktory

此包已被废弃,不再维护。未建议替代包。

尝试将 Ruby 的 FactoryGirl 的神奇之处带到 PHP

v0.4.1 2015-03-15 17:52 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:41:16 UTC


README

重要:此包不再积极维护。 对于错误修复和新功能,请进行分支。

Faktory

This Project Has Been Deprecated. Travis CI Code Climate Scrutinizer Code Quality Coverage Status

Faktory 是一个工具,用于轻松构建测试对象,类似于 FactoryGirl,但适用于 PHP。它还处于早期阶段,但如果您感兴趣,不妨试试,并为缺少的、您认为非常重要的功能提出问题。

使用 Composer 安装

您可以通过命令行从项目的根目录使用 Composer 安装此包

composer require adamwathan/faktory

Laravel 4

如果您正在使用 Laravel 4,可以通过注册包含的服务提供程序快速开始。

修改 providers 数组在 app/config/app.php 中以包含 FaktoryServiceProvider

'providers' => array(
        //...
        'AdamWathan\Faktory\FaktoryServiceProvider'
    ),

Faktory 门面添加到 app/config/app.php 中的 aliases 数组

'aliases' => array(
        //...
        'Faktory' => 'AdamWathan\Faktory\Facades\Faktory'
    ),

现在您可以通过调用 Faktory 门面上的方法来开始使用 Faktory

Faktory::define('User', function ($f) {
    $f->first_name = 'John';
    $f->last_name = 'Doe';
});

Laravel 4 之外

要在 Laravel 4 之外使用,只需创建一个新的 Faktory 实例。请确保将其注册为单例,因为您可能希望在哪里都使用相同的实例。

$faktory = new AdamWathan\Faktory\Faktory;

注意:在 Laravel 4 之外使用且无法访问 Faktory 门面时,您需要确保在任何需要生成其他对象的嵌套闭包中使用 use您的 $faktory 实例。这很糟糕,但这是 PHP。

使用 Faktory

定义工厂

您可以在任何地方定义工厂。

在 Laravel 4 中,我一直在测试目录中创建一个 factories.php 文件,并将其添加到 app/bootstrap/testing.php

// app/bootstrap/testing.php
require app_path().'/tests/factories.php';

基本定义

最基本的生产商定义需要类名和一个闭包,该闭包定义了工厂的默认属性。这将定义一个与该类同名且生成该类实例的工厂。

Faktory::define('Album', function ($f) {
    $f->name = 'Diary of a madman';
    $f->release_date = new DateTime('1981-11-07');
});

Faktory::define('Song', function ($f) {
    $f->name = 'Over the mountain';
    $f->length = 271;
});

使用工厂

一旦您定义了工厂,您就可以非常容易地为您测试生成对象。

可以使用两种不同的构建策略来生成对象。

  • build 仅在内存中创建对象,而不持久化它们。
  • create 创建对象并将其持久化到您在测试环境中设置的任何数据库。

注意:create 策略是为 Laravel 4 的 Eloquent ORM 设计的,但只要你的对象实现了 save() 方法和 getKey() 方法以获取对象的 ID,它应该在 Eloquent 之外也能工作。

要生成一个对象,只需调用 buildcreate,并传入你想要生成对象的工厂名称。

// Returns an Album object with the default attribute values
$album = Faktory::build('Album');
$album->name;
// 'Diary of a madman'
$album->release_date;
// '1981-11-07'


// Create a basic instance and persist it to
// the database
$album = Faktory::create('Album');
$album->id
// 1

覆盖属性

使用这些工厂的实际好处在于,当你编写需要满足某些预条件的测试,但你并不关心其余属性时。

你可以指定对于测试来说重要的属性值,让工厂用默认数据填充你不关心的属性,从而使对象处于有效状态。

如果你只需要将一些简单的属性更改为静态值,你只需作为第二个参数传递一个属性覆盖数组。

// Create an instance and override some properties
$album = Faktory::build('Album', ['name' => 'Bark at the moon']),
]);

$album->name;
// 'Bark at the moon'
$album->release_date;
// '1981-11-07'

如果你需要做更复杂的事情,你可以传入一个闭包,提供与实际定义工厂时相同的功能。这在与关系一起使用时最有用。

// Create an instance and override some properties
$album = Faktory::build('Album', function ($album) {
    $album->name => 'Bark at the moon';
    $album->songs->quantity(4)->attributes(['length' => 267]);
});

$album->name;
// 'Bark at the moon'
$album->songs->count();
// 4
$album->songs[0]->length;
// 267

命名工厂

工厂也可以被赋予一个名称,这样你就可以为同一个类定义多个工厂,以生成处于不同预定义状态的对象。

要定义一个命名工厂,将名称作为第二个参数传递,并将回调移动到第三个参数。

Faktory::define('Album', 'album_with_copies_sold', function ($f) {
    $f->name = 'Diary of a madman';
    $f->release_date = '1981-11-07';
    $f->copies_sold = 3200000;
});


$album = Faktory::build('album_with_copies_sold');

get_class($album);
// 'Album'
$album->name;
// 'Diary of a madman'
$album->release_date;
// '1981-11-07'
$album->copies_sold;
// 3200000

工厂继承

你可以通过嵌套定义创建继承现有工厂属性的工厂。这允许你定义一个基本工厂,以及在其下定义更具体的工厂,以生成特定状态的对象,而无需重新声明不需要更改的属性。

Faktory::define('User', 'basic_user', function ($f) {
    $f->first_name = 'John';
    $f->last_name = 'Doe';
    $f->is_admin = false;

    $f->define('admin', function ($f) {
        $f->is_admin = true;
    });
});


$user = Faktory::build('admin');

$user->first_name;
// 'John'
$user->last_name;
// 'Doe'
$user->is_admin;
// true

延迟属性

如果你不希望在尝试构建对象之前评估一个属性,你可以将该属性定义为闭包。

Faktory::define('User', function ($f) {
    $f->username = 'john.doe';

    $f->created_at = function () {
        return new DateTime;
    };
});


$user1 = Faktory::build('User');
$user1->created_at;
// '2014-04-22 14:10:05'

sleep(7);

$user2 = Faktory::build('User');
$user2->created_at;
// '2014-04-22 14:10:12'

依赖属性

你还可以使用延迟属性来定义依赖于工厂中其他属性的属性。

Faktory::define('User', function ($f) {
    $f->first_name = 'John';
    $f->last_name = 'Doe';
    $f->email = function ($f) {
        return "{$f->first_name}.{$f->last_name}@example.com";
    };
});


$user = Faktory::build('User');
$user->first_name;
// 'John'
$user->last_name;
// 'Doe'
$user->email;
// 'John.Doe@example.com'

$user = Faktory::build('User', ['first_name' => 'Bob']);
$user->first_name;
// 'Bob'
$user->last_name;
// 'Doe'
$user->email;
// 'Bob.Doe@example.com'

唯一属性

延迟属性再次救命。闭包还接受一个作为第二个参数的自动递增整数,这对于确保字段值唯一非常有用。

Faktory::define('User', function ($f) {
    $f->first_name = 'John';
    $f->last_name = 'Doe';
    $f->email = function ($f, $i) {
        return "example{$i}@example.com";
    };
});


$user1 = Faktory::build('User');
$user1->email;
// 'example1@example.com'

$user2 = Faktory::build('User');
$user2->email;
// 'example2@example.com'

定义关系

Faktory 允许你轻松地定义对象之间的关系。

目前,支持 belongsTohasOnehasMany 关系。

属于

通过将 belongsTo 调用分配给一个属性来定义一个 belongsTo 关系。

belongsTo() 接收用于生成相关对象的工厂名称作为第一个参数,外键列的名称作为第二个参数,以及一个可选的覆盖属性数组作为第三个参数。

$faktory->define('Song', 'song_with_album', function ($f) {
    $f->name = 'Concatenation';
    $f->length = 257;
    $f->album = $f->belongsTo('album', 'album_id', [
        'name' => 'Chaosphere',
    ]);
});

$faktory->define('Album', 'album', function ($f) {
    $f->name = 'Destroy Erase Improve';
});


// Build the objects in memory without persisting to the database
$song = Faktory::build('song_with_album');
$song->album;
// object(Album)(
//    'name' => 'Destroy Erase Improve'
// )
$song->album_id;
// NULL


// Save the objects to the database and set up the correct
// foreign key associations
$song = Faktory::create('song_with_album');
$song->album_id;
// 1

Album::find(1);
// object(Album)(
//    'name' => 'Destroy Erase Improve'
// )

有一个

通过将 hasOne 调用赋值给一个属性来定义一个 hasOne 关系。

hasOne() 函数接受三个参数:第一个参数是用于生成相关对象的工厂的名称,第二个参数是(相关对象上的)外键列的名称,第三个参数是可选的覆盖属性数组。

$faktory->define('User', 'user_with_profile', function ($f) {
    $f->username = 'johndoe';
    $f->password = 'top-secret';
    $f->profile = $f->hasOne('profile', 'user_id');
});

$faktory->define('Profile', 'profile', function ($f) {
    $f->email = 'johndoe@example.com';
});


// Build the objects in memory without persisting to the database
$user = Faktory::build('user_with_profile');
$user->profile;
// object(Profile)(
//    'email' => 'johndoe@example.com'
// )


// Save the objects to the database and set up the correct
// foreign key associations
$user = Faktory::create('user_with_profile');
$user->id;
// 1

Profile::first();
// object(Album)(
//    'user_id' => 1,
//    'email' => 'johndoe@example.com'
// )

多对一

通过将 hasMany 调用赋值给一个属性来定义一个 hasMany 关系。

hasMany() 函数接受四个参数:第一个参数是用于生成相关对象的工厂的名称,第二个参数是要生成的对象数量,第三个参数是(相关对象上的)外键列的名称,第四个参数是可选的覆盖属性数组。

$faktory->define('Album', 'album_with_songs', function ($f) {
    $f->name = 'Master of Puppets';
    $f->release_date = new DateTime('1986-02-24');
    $f->songs = $f->hasMany('song', 8, 'album_id');
});

$faktory->define('Song', 'song', function ($f) {
    $f->title = 'The Thing That Should Not Be';
    $f->length = 397;
});

关系和构建策略

不同的构建策略会以不同的方式处理关系。

当使用 build 策略时,相关对象将直接作为基对象上的属性可用。

当使用 create 策略时,相关对象将被持久化到数据库中,外键属性被设置为与基对象 ID 匹配,实际上不会在属性本身上设置任何内容,允许你通过在基对象类中定义的实际方法检索相关对象。

覆盖关系属性

如果你需要在构建或创建对象时覆盖关系属性,可以通过操作实际的关联属性本身来实现。

// Define the factories
$faktory->define('Song', 'song_with_album', function ($f) {
    $f->name = 'Concatenation';
    $f->length = 257;
    $f->album = $f->belongsTo('album', 'album_id');
});
$faktory->define('Album', 'album', function ($f) {
    $f->name = 'Destroy Erase Improve';
    $f->release_date = new DateTime('1995-07-25');
});


// Build a song but override the album name
$song = Faktory::build('song_with_album', function ($song) {
    $song->album->name = 'Chaosphere';
});
$song->album;
// object(Album)(
//    'name' => 'Chaosphere'
// )

// Build a song but override a couple attributes at once
$song = Faktory::build('song_with_album', function ($song) {
    $song->album->attributes([
        'name' => 'Chaosphere',
        'release_date' => new DateTime('1998-11-10'),
    ]);
});
$song->album;
// object(Album)(
//    'name' => 'Chaosphere'
// )
$song->album->release_date;
// '1998-11-10'

一次构建多个实例

你可以使用 buildManycreateMany 来同时生成多个对象。

// Create multiple instances
$albums = Faktory::buildMany('Album', 5);

// Create multiple instances with some overridden properties
$songs = Faktory::buildMany('Song', 5, [ 'length' => 100 ])
$songs[0]->length;
// 100
// ...
$songs[4]->length;
// 100

// Add a nested relationship where each item is different
$album = Faktory::build('Album', [
    'name' => 'Bark at the moon',
    'songs' => [
        Faktory::build('Song', [ 'length' => 143 ]),
        Faktory::build('Song', [ 'length' => 251 ]),
        Faktory::build('Song', [ 'length' => 167 ]),
        Faktory::build('Song', [ 'length' => 229 ]),
    ],
]);

// Add a nested relationship where each item shares the same
// properties
$album = Faktory::build('Album', [
    'name' => 'Bark at the moon',
    'songs' => Faktory::buildMany('Song', 5, [ 'length' => 100 ]
    ),
]);

// Add a nested relationship where each item is different,
// but using buildMany
$album = Faktory::build('Album', [
    'name' => 'Bark at the moon',
    'songs' => Faktory::buildMany('Song', 4, [
        'length' => [143, 251, 167, 229]
    ]),
]);

// Add a nested relationship using buildMany, but wrap
// it in a collection
$album = Faktory::build('Album', [
    'name' => 'Bark at the moon',
    'songs' => function () {
        return new Collection(Faktory::buildMany('Song', 4, [
            'length' => [143, 251, 167, 229]
        ]));
    }
]);