thephpleague / factory-muffin

Enables the rapid creation of objects for testing
https://factory-muffin.thephpleague.com/
MIT License
531 stars 72 forks source link

[3.0] Added Custom Makers Per Definition #357

Closed GrahamCampbell closed 9 years ago

GrahamCampbell commented 9 years ago

In Factory Muffin 3.0, the ability to register custom makers/setters/deleters on the factory muffin class has been removed because it was quite poorly designed, and the model definition registration has been improved massively fixing a few design problems we had before, and improving the definition group functionality.

I now propose that we allow people to register custom makers during this definition registration process, so in the same way you can define attribute definitions and callback for your models, you will also be able to register a custom maker closure.

Ok, so what does this mean for my code then?

Factory Muffin 2.1:

FactoryMuffin::define('Foo', []);
FactoryMuffin::define('extra:Foo', ['user' => 'firstNameMale']);
FactoryMuffin::define('Bar', []);
FactoryMuffin::define('Baz', []);

// no way to handle makers custom to groups
// we have to do this all at once - not very flexible
FactoryMuffin::setCustomMaker(function($class) {
    if ($class === 'Foo') {
        return new $class('bar');
    } elseif ($class === 'Bar') {
        return new $class('baz');
    } else {
        return new $class();
    }
});

Factory Muffin 3.0:

$fm = new FactoryMuffin();

$fm->define('Foo')
    ->setMaker(function ($class) {
        return new $class('bar');
});

$fm->define('extra:Foo')
    ->addDefinition('user', Faker::firstNameMale())
    ->setMaker(function ($class) {
        return new $class('hello');
});

$fm->define('Bar')
    ->setMaker(function ($class) {
        return new $class('baz');
});

$fm->define('Baz');
GrahamCampbell commented 9 years ago

Ping @scottrobertson, @benglass.

GrahamCampbell commented 9 years ago

Going to push ahead with this. Feel free to review this even after it's been merged.