stephanecoinon/object-factory

使用Laravel模型工厂创建简单的PHP对象

v0.0.1 2017-10-02 21:10 UTC

This package is auto-updated.

Last update: 2024-09-11 14:48:30 UTC


README

您想使用Laravel 5模型工厂构建简单的PHP对象吗?

BuiltByFactory 特性使这变得非常简单...

步骤1:安装此包

composer require stephanecoinon/object-factory

步骤2:使用特性能定义您的简单模型

<?php

// /app/Popo.php

namespace App;

use StephaneCoinon\ObjectFactory\BuiltByFactory;

/**
 * This is a plain old PHP class, we do not extend Eloquent.
 */
class Popo
{
    use BuiltByFactory;

    /**
     * Objects built by model factory are constructed from an array of
     * attributes.
     *
     * Here's an example of implementation.
     *
     * @param  array  $attributes
     * @return static
     */
    public function __construct($attributes = [])
    {
        foreach ($attributes as $key => $value) {
            $this->$key = $value;
        }
    }
}

步骤3:定义工厂

<?php

// /database/factories/PopoFactory.php

use Faker\Generator as Faker;

$factory->define(App\Popo::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
    ];
});

步骤4:构建您的对象!

// A single instance
$object = factory(App\Popo::class)->make();

// Or a collection
$objects = factory(App\Popo::class, 3)->make();