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 网站上。

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~