2017 © Pedro Peláez
 

library factory-muffin

image

league/factory-muffin

  • Tuesday, July 31, 2018
  • by graham-campbell
  • Repository
  • 24 Watchers
  • 450 Stars
  • 670,128 Installations
  • PHP
  • 43 Dependents
  • 5 Suggesters
  • 62 Forks
  • 26 Open issues
  • 33 Versions
  • 8 % Grown

The README.md

Factory Muffin 3.3

StyleCI Status Build Status Software License Latest Version Total Downloads, (*1)

The goal of this package is to enable the rapid creation of objects for the purpose of testing., (*2)

It's basically a "factory_girl", simplified for use with PHP., (*3)

Installing

PHP 5.4+ and Composer are required., (*4)

In your composer.json, simply add "league/factory-muffin": "^3.3" to your "require-dev" section:, (*5)

{
    "require-dev": {
        "league/factory-muffin": "^3.3"
    }
}

Faker support is provided by Factory Muffin Faker. If you want to enable faker support, then you need to add "league/factory-muffin-faker": "^2.3" too:, (*6)

{
    "require-dev": {
        "league/factory-muffin": "^3.3",
        "league/factory-muffin-faker": "^2.3"
    }
}

Upgrading

It maybe be useful for existing users to check out the upgrade guide., (*7)

Usage

Introduction

This is the usage guide for Factory Muffin 3.0. Within this guide, you will see "the xyz function can be called". You should assume that these functions should be called on an instance of League\FactoryMuffin\FactoryMuffin; you should keep track of this instance yourself, and you can of course have multiple instances of this class for maximum flexibility. For simplicities sake, many of our examples include a $fm variable. This variable will actually be made available when files are required using the loadFactories function., (*8)

Model Definitions

You can define model factories using the define function. You may call it like this: $fm->define('Fully\Qualifed\ModelName')->addDefinitions('foo', 'bar'), where foo is the name of the attribute you want set on your model, and bar describes how you wish to generate the attribute. You may also define multiple attributes at once like this: $fm->define('Fully\Qualifed\ModelName')->setDefinitions('foo', 'bar'). Note that both functions append to the internal attributes definition array rather than replacing it. Please see the generators section for more information on how this works., (*9)

You can also define multiple different model definitions for your models. You can do this by prefixing the model class name with your "group" followed by a colon. This results in you defining your model like this: $fm->define('myGroup:Fully\Qualifed\ModelName')->addDefinitions('bar', 'baz'). You don't have to entirely define your model here because we will first look for a definition without the group prefix, then apply your group definition on top of that definition, overriding attribute definitions where required. Note that if you want to use group prefixes, you must also create a definition without the group prefix as well., (*10)

We have provided a nifty way for you to do this in your tests. PHPUnit provides a setupBeforeClass function. Within that function you can call $fm->loadFactories(__DIR__ . '/factories');, and it will include all files in the factories folder. Within those PHP files, you can put your definitions (all your code that calls the define function)., (*11)

The loadFactories function will recurse through all sub-folders of the path you specify when searching for factory files, except for hidden folders (i.e. starting with a .) which will be ignored. It will also throw a League\FactoryMuffin\Exceptions\DirectoryNotFoundException exception if the factories directory you specify is not found., (*12)

Creation/Instantiation Callbacks

You may optionally specify a callback to be executed on model creation/instantiation using the setCallback function, like this: $fm->define('MyModel')->setCallback(function ($object, $saved) {}). We will pass your model instance as the first parameter to the callback and a boolean as the second parameter. The boolean will be true if the model is being persisted to the database (the create function was used), and false if it's not being persisted (the instance function was used). We're using the isPendingOrSaved function under the hood here. Note that if you specify a callback and use the create function, we will try to save your model to the database both before and after we execute the callback., (*13)

Generators

Callable

The callable generator can be used if you want a more custom solution. Whatever you return from your closure, or valid callable, will be set as the attribute. The closure/callable will be called with the same parameters as creation/instantiation callbacks described above: an instance of your model as the first parameter (to give you even more flexibility to modify it as you wish) and a boolean indicating if the model is being persisted to the database. In the following examples, we will go through using a closure, or callable, and then how to use faker to generate attributes., (*14)

Example 1

As you can see from this example, the ability to use a closure to generate attributes can be so useful and flexible. Here we use it to generate a slug based on the initially randomly generated 5 word long title., (*15)

$fm->define('MyModel')->setDefinitions([
    'title' => Faker::sentence(5),
    'slug' => function ($object, $saved) {
        $slug = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $object->title);
        $slug = strtolower(trim($slug, '-'));
        $slug = preg_replace("/[\/_|+ -]+/", '-', $slug);

        return $slug;
    },
]);
Example 2

This will set the foo attribute to whatever calling MyModel::exampleMethod($object, $saved) returns., (*16)

$fm->define('MyModel')->setDefinitions([
    'foo' => 'MyModel::exampleMethod',
]);
Example 3

There is a simple example of setting a few different attributes using our faker wrapper., (*17)

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->setDefinitions([
    'foo'    => Faker::word(),          // Set the foo attribute to a random word
    'name'   => Faker::firstNameMale(), // Set the name attribute to a random male first name
    'email'  => Faker::email(),         // Set the email attribute to a random email address
    'body'   => Faker::text(),          // Set the body attribute to a random string of text
    'slogan' => Faker::sentence(),      // Set the slogan attribute to a random sentence
]);
Example 4

This will set the age attribute to a random number between 20 and 40., (*18)

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->setDefinitions([
    'age' => Faker::numberBetween(20, 40),
]);
Example 5

This will set the name attribute to a random female first name. Because we've called the unique method first, the attribute should be unique between all your generated models. Be careful with this if you're generating lots models because we might run out of unique items. Also, note that calling Faker::setLocale('whatever') will reset the internal unique list., (*19)

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->addDefinition('name', Faker::unique()->firstNameFemale());
Example 6

This will set the profile_pic attribute to a random image url of dimensions 400 by 400. Because we've called the optional method first, not all the generated models will have an image url set; sometimes we will return null., (*20)

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('MyModel')->addDefinition('profile_pic', Faker::optional()->imageUrl(400, 400));
More

Check out the faker library itself to see all the available methods. There are far too many to cover in the documentation here, and far too many for them to cover in their documentation too. Note that you can fiddle with the underlying faker instance through the public methods on our faker class if you want., (*21)

Factory

The factory generator can be useful for setting up relationships between models. The factory generator will return the model id of the model you ask it to generate., (*22)

Example 1

When we create a Foo object, we will find that the Bar object will been generated and saved too, and it's id will be assigned to the bar_id attribute of the Foo model., (*23)

$fm->define('Foo')->addDefinition('bar_id', 'factory|Bar');

$fm->define('Bar')->addDefinition('baz', Faker::date('Y-m-d'));

Creating And Seeding

The create function will create and save your model, and will also save anything you generate with the Factory generator too. If you want to create multiple instances, check out the seed seed function, which accepts an additional argument at the start which is the number of models to generate in the process. The seed function will effectively be calling the create function over and over., (*24)

For example, let's create a user model and associate multiple location and email models to each one. Each email will also have multiple token models., (*25)

$user = $fm->create('User');
$profiles = $fm->seed(5, 'Location', ['user_id' => $user->id]);
$emails = $fm->seed(100, 'Email', ['user_id' => $user->id]);

foreach ($emails as $email) {
    $tokens = $fm->seed(50, 'Token', ['email_id' => $email->id]);
}

You may encounter the following exceptions: * League\FactoryMuffin\Exceptions\ModelNotFoundException will be thrown if the model class defined is not found. * League\FactoryMuffin\Exceptions\DefinitionNotFoundException will be thrown if you try to create a model and you haven't defined a model definition for it earlier. * League\FactoryMuffin\Exceptions\SaveFailedException will be thrown if the save function on your model returns false. * League\FactoryMuffin\Exceptions\SaveMethodNotFoundException will be thrown if the save function on your model does not exist. * Any other exception thrown by your model while trying to create or save it., (*26)

There are 5 other helper functions available: * You may call pending to return an array of all the objects waiting to be saved. * You may call isPending with an instance of a model to check if will be saved. * You may call saved to return an array of all the saved objects. * You may call isSaved with an instance of a model to check if it's saved. * You may call isPendingOrSaved with an instance of a model to check if it will be saved, or is already saved., (*27)

Also, a reminder that the instance function is still available if you don't want database persistence., (*28)

Deleting

You can delete all your saved models with the deleteSaved function. Please note that your saved models will be deleted in the reverse order they were saved to ensure relationships behave correctly., (*29)

If one or more models cannot be deleted, a League\FactoryMuffin\Exceptions\DeletingFailedException will be raised after we have attempted to delete all the saved models. You may access each underlying exception, in the order they were thrown during the whole process, with the getExceptions function which will return an array of exceptions. You may encounter the following exceptions: * League\FactoryMuffin\Exceptions\DeleteFailedException will be thrown if the delete function on your model returns false. * League\FactoryMuffin\Exceptions\DeleteMethodNotFoundException will be thrown if the delete function on your model does not exist. * Any other exception thrown by your model while trying to delete it., (*30)

It's recommended that you call the deleteSaved function from PHPUnit's tearDownAfterClass function, however, if you are writing tests using Laravel's TestCase, you should call the deleteSaved function from the tearDown method before calling parent::tearDown. This method flushes the application instance's bindings and Factory Muffin would not unable to execute its deletes. Further more, this unbinds the assigned exception handler and you will not be able to troubleshoot your tests due to binding resolution exceptions obfuscating the true exceptions., (*31)

Real Examples

To start with, we need to create some definitions:, (*32)

# tests/factories/all.php

use League\FactoryMuffin\Faker\Facade as Faker;

$fm->define('Message')->setDefinitions([
    'user_id'      => 'factory|User',
    'subject'      => Faker::sentence(),
    'message'      => Faker::text(),
    'phone_number' => Faker::randomNumber(8),
    'created'      => Faker::date('Ymd h:s'),
    'slug'         => 'Message::makeSlug',
])->setCallback(function ($object, $saved) {
    // we're taking advantage of the callback functionality here
    $object->message .= '!';
});

$fm->define('User')->setDefinitions([
    'username' => Faker::firstNameMale(),
    'email'    => Faker::email(),
    'avatar'   => Faker::imageUrl(400, 600),
    'greeting' => 'RandomGreeting::get',
    'four'     => function() {
        return 2 + 2;
    },
]);

You can then use these factories in your tests:, (*33)

# tests/TestUserModel.php

use League\FactoryMuffin\Faker\Facade as Faker;

class TestUserModel extends PHPUnit_Framework_TestCase
{
    protected static $fm;

    public static function setupBeforeClass()
    {
        // create a new factory muffin instance
        static::$fm = new FactoryMuffin();

        // you can customize the save/delete methods
        // new FactoryMuffin(new ModelStore('save', 'delete'));

        // load your model definitions
        static::$fm->loadFactories(__DIR__.'/factories');

        // you can optionally set the faker locale
        Faker::setLocale('en_EN');
    }

    public function testSampleFactory()
    {
        $message = static::$fm->create('Message');
        $this->assertInstanceOf('Message', $message);
        $this->assertInstanceOf('User', $message->user);
    }

    public static function tearDownAfterClass()
    {
        static::$fm->deleteSaved();
    }
}

Further Information

If you want more information, the following resources are available to you: * Generated api docs are available here. * Philip Brown's article is available here. * Our test suite may also be useful to you., (*34)

Integrations

Contributing

Please check out our contribution guidelines for details., (*35)

Credits

Factory Muffin is based on Zizaco Zizuini's original work on "Factory Muff", and is currently maintained by Graham Campbell. Scott Robertson was also a co-maintainer before the 3.0 release. Thank you to all our wonderful contributors too., (*36)

Security

If you discover a security vulnerability within this package, please send an email to Graham Campbell at graham@alt-three.com. All security vulnerabilities will be promptly addressed. You may view our full security policy here., (*37)

License

Factory Muffin is licensed under The MIT License (MIT)., (*38)

For Enterprise

Available as part of the Tidelift Subscription, (*39)

The maintainers of league/factory-muffin and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more., (*40)

The Versions

31/07 2018

dev-gh-pages-sculpin

dev-gh-pages-sculpin

  Sources   Download

12/08 2017

dev-master

9999999-dev http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Graham Campbell

testing factory

18/11 2016

dev-seed

dev-seed http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Graham Campbell

testing factory

13/05 2016

v3.0.1

3.0.1.0 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Graham Campbell

testing factory

14/02 2016

v3.0.0

3.0.0.0 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Graham Campbell

testing factory

20/07 2015

v3.0.0-RC1

3.0.0.0-RC1 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Graham Campbell

testing factory

24/12 2014

2.1.x-dev

2.1.9999999.9999999-dev http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

22/12 2014

v3.0.0-beta1

3.0.0.0-beta1 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.4.0

 

The Development Requires

by Graham Campbell

laravel testing factory

18/09 2014

v2.1.1

2.1.1.0 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

28/08 2014

v2.1.0

2.1.0.0 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

27/08 2014

v2.0.2

2.0.2.0 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

20/08 2014

v2.1.0-RC1

2.1.0.0-RC1 http://factory-muffin.thephpleague.com/

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

08/08 2014

v2.0.1

2.0.1.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

07/08 2014

v2.0.0

2.0.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

04/08 2014

v2.0.0-RC4

2.0.0.0-RC4

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

31/07 2014

v2.0.0-RC3

2.0.0.0-RC3

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

30/07 2014

v2.0.0-RC2

2.0.0.0-RC2

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

by Graham Campbell

laravel testing factory

21/07 2014

v2.0.0-RC1

2.0.0.0-RC1

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

The Development Requires

laravel testing factory

06/07 2014

v1.6.4

1.6.4.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

laravel testing factory

06/07 2014

v1.6.3

1.6.3.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

laravel testing factory

04/07 2014

v1.6.2

1.6.2.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

laravel testing factory

04/07 2014

v1.6.1

1.6.1.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

laravel testing factory

05/06 2014

v1.6.0

1.6.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

 

laravel testing factory

28/04 2014

v1.5.2

1.5.2.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

25/04 2014

v1.5.1

1.5.1.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

10/12 2013

v1.5.0

1.5.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

26/03 2013

v1.4.2

1.4.2.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

18/02 2013

v1.4.1

1.4.1.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

18/02 2013

v1.4.0

1.4.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

17/02 2013

v1.3.0

1.3.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

17/02 2013

v1.2.0

1.2.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

31/01 2013

v1.1.0

1.1.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory

31/01 2013

v1.0.0

1.0.0.0

The goal of this Package is to enable the rapid creation of objects for the purpose of testing.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

laravel testing factory