PHP code example of chustilla / cakephp-model-factory

1. Go to this page and download the library: Download chustilla/cakephp-model-factory 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/ */

    

chustilla / cakephp-model-factory example snippets


# database/factories/BarFactory.php



use App\Model\Entity\Bar;

$factory->define(Bar::class, [
    'id' => 123,
    'name' => 'Guybrush Threepwood',
]);



use App\Model\Entity\Bar;
use Faker\Generator as Faker;

$factory->define(Bar::class, function (Faker $faker) {
    return [
        'id' =>  $faker->numberBetween(1, 1000),
        'name' => $faker->name,
    ];
});

# tests/bootstrap.php



use Chustilla\ModelFactory\Factory;

Factory::getInstance()->loadFactories('absolute/or/relative/path/to/models/definitions/directory');

# tests/TestCase/Unit/Service/FooServiceTest.php



use Cake\TestSuite\TestCase;

class FooServiceTest extends TestCase
{
    public function testMethod()
    {
        // Arrange
        $bar = factory(Bar::class)->create();
        ...
    }
}

$bar = factory(Bar::class)->make();

$bar = factory(Bar::class, 3)->create();

$bar = factory(Bar::class)->make(['id' => 1, 'name' => 'LeChuck']);



use App\Model\Entity\Bar;
use App\Model\Entity\Foo;
use Faker\Generator as Faker;

$factory->define(Bar::class, function (Faker $faker) {
    return [
        'id' =>  $faker->numberBetween(1, 1000),
        'name' => $faker->name,
    ];
});

$factory->state(Bar::class, 'withFoo', function () {
    return [
        foo => factory(Foo::class)->create(),
    ];
});

$bar = factory(Bar::class)->states['withFoo', 'active']->create();

# tests/TestCase/Unit/Service/FooServiceTest.php



use Cake\TestSuite\TestCase;
use Chustilla\ModelFactory\DatabaseCleanUp;

class FooServiceTest extends TestCase
{
    use DatabaseCleanUp;

    public function testMethod()
    {
        // Arrange
        $bar = factory(Bar::class)->create();
        ...
    }
}