PHP code example of aaronbullard / factory-biscuit

1. Go to this page and download the library: Download aaronbullard/factory-biscuit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aaronbullard / factory-biscuit example snippets


// Factories.php

use Faker\Generator;
use FactoryBiscuit\Factory;
use FactoryBiscuit\Tests\Mocks\Entity\Foo;
use FactoryBiscuit\Tests\Mocks\Entity\Bar;

$factory->define(Foo::class, function(Generator $faker, Factory $factory){
    return [
        'bar' => function() use ($factory){
            return $factory->of(Bar::class)->make();
        },
        'baz' => $faker->word,
        'qux' => $faker->word
    ];
});

$factory->define(Bar::class, function(Generator $faker, Factory $factory){
    return [
        'bar' => $faker->word
    ];
});

use FactoryBiscuit\Factory;

$factory = new Factory();

$factory->load(__DIR__ . '/Factories.php');

$foo = $factory->of(Foo::class)->make();

$this->assertInstanceOf(Foo::class, $foo);

$foos = $factory->of(Foo::class)->times(3)->make();

$this->assertInstanceOf(Foo::class, $foos[0]);
$this->assertCount(3, $foos);

$foo = $factory->of(Foo::class)->make([
    'baz' => 'newBaz'
]);

$this->assertEquals('newBaz', $foo->baz());

// Create a factory of class Foo with settings of 'colors'
$factory->defineAs(Foo::class, 'colors', function($faker, $factory){
    return [
        'bar' => 'red',
        'baz' => 'green',
        'qux' => 'blue'
    ];
});

$foo = $factory->of(Foo::class, 'colors')->make();

$this->assertInstanceOf(Foo::class, $foo);
$this->assertEquals('red', $foo->bar());
$this->assertEquals('green', $foo->baz());

$factory = new Factory(Faker::create(), $managerRegistry);

// call the 'create' method to create a persisted instance
$user = $factory->of(User::class)->create();

$this->assertInstanceOf(User::class, $user);
$this->assertTrue(
    DB::table('users')->where('id', '=', $user->id)->exists()
);