PHPackages                             insolita/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. insolita/yii2-muffin-factory

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

insolita/yii2-muffin-factory
============================

Port of laravel factory

2.0.0(5y ago)954.8k↑35.1%31MITPHPPHP &gt;=7.2CI failing

Since Nov 26Pushed 5y ago3 watchersCompare

[ Source](https://github.com/Insolita/yii2-muffin-factory)[ Packagist](https://packagist.org/packages/insolita/yii2-muffin-factory)[ RSS](/packages/insolita-yii2-muffin-factory/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (5)Versions (5)Used By (1)

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

[](#yii2-muffin-factory)

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

[![yii2-muffin-factory](https://github.com/Insolita/yii2-muffin-factory/workflows/yii2-muffin-factory/badge.svg)](https://github.com/Insolita/yii2-muffin-factory/workflows/yii2-muffin-factory/badge.svg)

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

[](#installation)

Either run

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

```

or add

```
"insolita/yii2-muffin-factory": "~2.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

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~574 days

Total

3

Last Release

1946d ago

Major Versions

0.0.3 → 1.0.02018-01-09

1.0.0 → 2.0.02021-01-18

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

1.0.0PHP &gt;=7.0.0

2.0.0PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/40f26825f8c130796e3151e6c076721cf5bb222c42148102bb31a341a1a5c789?d=identicon)[Insolita](/maintainers/Insolita)

---

Top Contributors

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

---

Tags

hacktoberfesttestingfixturesdatabaseyii2seed

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[orchestra/workbench

Workbench Companion for Laravel Packages Development

8217.0M43](/packages/orchestra-workbench)[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)

PHPackages © 2026

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