Factories 本文未发布 发布文章

未匹配的标注

Definition

Factories (are a short name for Models Factories).
Factories are used to generate some fake data with the help of Faker to be used for testing purposes.
Factories are mainly used from Tests.

Principles

  • Factories SHOULD be created in the Containers.

Rules

  • A Factory is just a plain PHP script. (No classes or namespaces required)

Folder Structure

 - app
    - Containers
        - {container-name}
             - Data
                - Factories
                    - UserFactory.php
                    - ...

Code Samples

A User Model Factory:

<?php

// User
$factory->define(App\Containers\User\Models\User::class, function (Faker\Generator $faker) {
    return [
        'name'     => $faker->name,
        'email'    => $faker->email,
        'password' => bcrypt(str_random(10)),
    ];
});

// ...

Usage from Tests or anywhere else:

<?php

// creating 4 users
factory(User::class, 4)->create();

Usage with relationships:

<?php

$countries = Country::all();

// creating 3 rewards and attaching country relation to them
$rewards = factory(Reward::class, 3)->make()->each(function ($reward) use ($countries) {
    $reward->save();
    $reward->countries()->attach([$countries->random(1)->id, $countries->random(1)->id]);
    $reward->save();
});

Use make instance of create and pass any data any way, then save after establishing the relations.
Usage while overriding some values:

<?php

// creating single Offer and setting a user id
$offer = factory(Offer::class)->make();
$offer->user_id = $user->id;
$offer->save();

// ANOTHER EXAMPLE:

// creating multiple Accounts
factory(Account::class, 3)->make()->each(function ($account) use ($user) {
    $account->user_id = $user->id;
    $account->save();
});

For more information about the Models Factories read this.

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 查看所有版本


暂无话题~