PHPackages                             saschati/yii2-muffin-factory - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. saschati/yii2-muffin-factory

ActiveYii2-extension[Testing &amp; Quality](/categories/testing)

saschati/yii2-muffin-factory
============================

Port of laravel factory

1.0.5(5y ago)03MITPHPPHP ^7.0 || ^8.0

Since Nov 26Pushed 5y agoCompare

[ Source](https://github.com/saschati/yii2-muffin-factory)[ Packagist](https://packagist.org/packages/saschati/yii2-muffin-factory)[ RSS](/packages/saschati-yii2-muffin-factory/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (5)Versions (8)Used By (0)

Yii2 Muffin Factory
===================

[](#yii2-muffin-factory)

A Port of laravel factory for generate fixtures on fly and database seeding

[![Build Status](https://camo.githubusercontent.com/8e211f53168b2a9bbc832fd24088f110fb04182b0aea37fb871395873dd4f708/68747470733a2f2f7472617669732d63692e6f72672f496e736f6c6974612f796969322d6d756666696e2d666163746f72792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Insolita/yii2-muffin-factory)

Installation
============

[](#installation)

Either run

```
composer require -dev insolita/yii2-muffin-factory:~1.0.0

```

or add

```
"insolita/yii2-muffin-factory": "~1.0.0"

```

in require-dev section of your `composer.json` file.

Configure
---------

[](#configure)

Add in bootstrap for test suite (or in every app, where it can be used)

```
//with default factory path by alias @tests/factories
Yii::$container->setSingleton(
     \insolita\muffin\Factory::class,
      [],
     [\Faker\Factory::create('en_EN')]
  );

//with custom factory path
Yii::$container->setSingleton(
     \insolita\muffin\Factory::class,
     [],
     [
         \Faker\Factory::create('ru_RU'),  //Faker language
          '@common/data/factories'         // Custom directory for factories
     ]
 );
```

Create Factories
================

[](#create-factories)

You can create all factories in single file, or in individual files in directory defined in factory configuration

example UserFactory.php

```
/**
 * @var \insolita\muffin\Factory $factory
 **/

 $factory->define(User::class, function (\Faker\Generator $faker) {
     static $password;
     return [
         'name' => $faker->name,
         'lastName' => $faker->name,
         'email' => $faker->unique()->safeEmail,
         'status'=>'default',
         'passwordHash' => $password ?: $password = Yii::$app->security->generatePasswordHash('secret'),
         'authKey' => Yii::$app->security->generateRandomString(),
         'accessToken' => Yii::$app->security->generateRandomString(64),
         'birthday' => $faker->date('Y-m-d', '-15 years'),
         'registered' => $faker->dateTimeThisMonth()->format('Y-m-d H:i:s'),
     ];
 });
$factory->state(User::class, 'developer', [
        'status' => 'developer',
]);
$factory->state(User::class, 'client', [
    'status' => 'client',
]);
```

Use Factories
=============

[](#use-factories)

*Populate new record without saving*

```
 /**@var User $user **/
$user = factory(User::class)->make();
$user = factory(User::class)->states('client')->make();
 /**@var User[] $user **/
$users = factory(User::class, 5)->make();
$users = factory(User::class, 5)->states(['client', 'developer'])->make();
```

*Populate and persist records*

```
 /**@var User $user * */
$user = factory(User::class)->create();
 /**@var User[] $user **/
$users = factory(User::class, 10)->states(['client'])->create(['registered'=>Carbon::now()]);
```

See more examples in [FactoryTest](tests/unit/FactoryTest.php)

Use with ActiveFixtures
=======================

[](#use-with-activefixtures)

Create ActiveFixture extended classed in configured directory as usual

```
class UserFixture extends ActiveFixture
{
    public $modelClass = User::class;

    protected function getData()
    {
        return array_merge(
            factory(User::class, 1)->states('developer')->raw(),
            factory(User::class, 10)->states('client')->raw()
        );
    }
}
```

*Fixtures with relation dependency*

```
class PostFixture extends ActiveFixture
{
    public $modelClass = Post::class;
    public $depends = [UserFixture::class];

    public function load()
    {
        $this->data = [];
        $users = User::find()->select(['id'])->column();
        foreach ($users as $userId) {
            $posts = factory(Post::class, 5)->create(['createdBy' => $userId]);
            foreach ($posts as $post) {
                $this->data[$post->id] = $post->getAttributes();
            }
        }
        return $this->data;
    }
}

class SomeFixture extends ActiveFixture
{
    public $modelClass = Some::class;
    public $depends = [UserFixture::class];

    protected function getData()
    {
        $users = User::find()->select(['id'])->where(['status'=>'client'])->column();
        $developer = User::find()->where(['status'=>'developer'])->limit(1)->one();
        $data =  array_merge(
            factory(Some::class, 5)->raw(['user_id'=>ArrayHelper::random($users)]),
            factory(Some::class, 20)->states('one')->raw(['user_id'=>function() use(&$users){ return ArrayHelper::random($users);}]),
            factory(Some::class, 11)->states('two')->raw(['user_id'=>$developer->id])
        );
        return $data;
    }
}
```

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 79.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~191 days

Recently: every ~0 days

Total

7

Last Release

1944d ago

Major Versions

0.0.3 → 1.0.02018-01-09

PHP version history (3 changes)0.0.3PHP &gt;=7.0

1.0.0PHP &gt;=7.0.0

1.0.1PHP ^7.0 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/10222441ddb5c9629e66921fe42830eddbb27de3e68597e2df890211641a1c83?d=identicon)[Olexandr Grigorchyk](/maintainers/Olexandr%20Grigorchyk)

---

Top Contributors

[![Insolita](https://avatars.githubusercontent.com/u/1847402?v=4)](https://github.com/Insolita "Insolita (19 commits)")[![saschati](https://avatars.githubusercontent.com/u/36109878?v=4)](https://github.com/saschati "saschati (5 commits)")

---

Tags

testingfixturesdatabaseyii2seed

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/saschati-yii2-muffin-factory/health.svg)

```
[![Health](https://phpackages.com/badges/saschati-yii2-muffin-factory/health.svg)](https://phpackages.com/packages/saschati-yii2-muffin-factory)
```

###  Alternatives

[fakerino/fakerino

Faker framework, for generate every kind of fake data for test, database seed, mock responses, other

12214.8k5](/packages/fakerino-fakerino)[misantron/dbunit

DbUnit fork supporting PHPUnit 10/11/12

121.2M6](/packages/misantron-dbunit)[saada/yii2-factory-muffin

A Yii2 wrapper for league/factory-muffin with Gii generators.

1554.6k](/packages/saada-yii2-factory-muffin)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
