PHPackages                             adlacruzes/php-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. adlacruzes/php-factory

ActiveLibrary[Testing &amp; Quality](/categories/testing)

adlacruzes/php-factory
======================

Factories to generate classes and arrays with default values

1.4.0(4y ago)032.2k↑33.3%MITPHPPHP ^7.2 || ^8.0

Since Jul 26Pushed 4y agoCompare

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

READMEChangelog (5)Dependencies (7)Versions (6)Used By (0)

PHP Factory
===========

[](#php-factory)

[![Minimum PHP Version](https://camo.githubusercontent.com/4f9eddea3b5f90bdf4c2f6feafb71962a03512fd923888e4aef358cf6334daf7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230372e322d3838393242462e7376673f7374796c653d666c61742d737175617265)](https://php.net/)[![Packagist](https://camo.githubusercontent.com/67a65726b7518610f585a53f518d7f60ac2c0dc3777cc63919ae8c54efed4d95/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61646c616372757a65732f7068702d666163746f72793f7374796c653d666c61742d737175617265)](https://packagist.org/packages/adlacruzes/php-factory)[![Github actions](https://github.com/adlacruzes/php-factory/workflows/Continuous%20Integration/badge.svg?branch=master)](https://github.com/adlacruzes/php-factory/workflows/Continuous%20Integration/badge.svg?branch=master)

PHP Factory allows generating classes and arrays with default values and reduce test bloatware.

The main purpose of this library is help with the creation of tests and fixtures.

Table of Contents
=================

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Factories](#factories)
    - [Array factory](#array-factory)
    - [Class factory](#class-factory)
- [Methods](#methods)
    - [create](#create)
    - [createArray](#create-array)
    - [createNullable](#create-nullable)
- [Exceptions](#exceptions)

Requirements
------------

[](#requirements)

PHP needs to be a minimum version of PHP 7.2.

Installation
------------

[](#installation)

The recommended way to install is through [Composer](http://getcomposer.org).

```
composer require adlacruzes/php-factory
```

Factories
---------

[](#factories)

Every factory has to extend `Adlacruzes\Factory\Factory` to obtain the required methods.

### Array factory

[](#array-factory)

The array factory allows generating an array with predefined values.

```
use Adlacruzes\Factory\Factory;
use Adlacruzes\Factory\Factories\ArrayFactory;
use Adlacruzes\Factory\Factories\FactoryInterface;

class ArraysFactory extends Factory
{
    protected static function setFactory(): FactoryInterface
    {
        return new ArrayFactory(
            [
                'one' => 'one',
                'two' => 'two',
                'three' => 'three',
                'four' => 'four',
            ]
        );
    }
}
```

You can call `ArraysFactory::create()` and obtain the defined array:

```
[
    'one' => 'one',
    'two' => 'two',
    'three' => 'three',
    'four' => 'four',
]
```

If you want to change some information, you can override the values with a new partial array:

```
ArraysFactory::create(
    [
        'four' => 'another number'
    ]
);
```

The returned array will be:

```
[
    'one' => 'one',
    'two' => 'two',
    'three' => 'three',
    'four' => 'another number',
]
```

### Class factory

[](#class-factory)

The class factory allows generating a concrete class with default constructor parameters.

```
class ValidClass
{
    private $id;

    private $name;

    private $isEnabled;

    private $createdAt;

    public function __construct($id, $name, $isEnabled, \DateTime $createdAt)
    {
        $this->id = $id;
        $this->name = $name;
        $this->isEnabled = $isEnabled;
        $this->createdAt = $createdAt;
    }
```

Create a class that extends from Factory.

```
use Adlacruzes\Factory\Factories\ClassFactory;
use Adlacruzes\Factory\Factories\FactoryInterface;
use Adlacruzes\Factory\Factory;

class ValidClassFactory extends Factory
{
    protected static function setFactory(): FactoryInterface
    {
        return new ClassFactory(
            ValidClass::class,
            [
                'id' => 1,
                'name' => 'name',
                'isEnabled' => true,
                'createdAt' => new \DateTime(),
            ]
        );
    }
}
```

You can call `ValidClassFactory::create()` and obtain the defined class:

```
class ValidClass (4) {
  private $id =>
  int(1)
  private $name =>
  string(4) "name"
  private $isEnabled =>
  bool(true)
  private $createdAt =>
  class DateTime (3) {
    public $date =>
    string(26) "2019-01-01 00:00:00.000000"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
}
```

If you want to change some information, you can override default values with a new partial array:

```
ValidClassFactory::create(
    [
        'name' => 'other',
        'isEnabled' => false
    ]
);
```

The returned class will be:

```
class ValidClass (4) {
  private $id =>
  int(1)
  private $name =>
  string(4) "other"
  private $isEnabled =>
  bool(false)
  private $createdAt =>
  class DateTime (3) {
    public $date =>
    string(26) "2019-01-01 00:00:00.000000"
    public $timezone_type =>
    int(3)
    public $timezone =>
    string(3) "UTC"
  }
}
```

Methods
-------

[](#methods)

There are three methods for every factory. They can be called with no arguments or can receive an array of values to override the defaults parameters.

### create

[](#create)

Create returns an instance of the factory.

#### `create()`

[](#create-1)

Returns the predefined factory.

```
SampleFactory::create();
```

#### `create(array)`

[](#createarray)

Returns the predefined factory with the new specified values.

```
SampleFactory::create(
    [
        'field' => 'value'
    ]
);
```

### create array

[](#create-array)

CreateArray returns an array of instances of the factory. The number of instances can be specified as first argument. The default number is one.

#### `createArray()`

[](#createarray-1)

Returns an array of one predefined factory.

```
SampleFactory::createArray();
```

#### `createArray(n)`

[](#createarrayn)

Returns an array of `n` predefined factories.

```
SampleFactory::createArray(n);
```

#### `createArray(n, array)`

[](#createarrayn-array)

Returns an array of `n` predefined factories with the new specified values.

```
SampleFactory::create(
    n,
    [
        'field' => 'value'
    ]
);
```

### create nullable

[](#create-nullable)

CreateNullable returns an instance of the factory with all possibly null values.

#### `createNullable()`

[](#createnullable)

Returns the predefined factory with nulls.

```
SampleFactory::createNullable();
```

#### `createNullable(array)`

[](#createnullablearray)

Returns the predefined factory with all possibly null values except the new specified ones.

```
SampleFactory::createNullable(
    [
        'field' => 'value'
    ]
);
```

Exceptions
----------

[](#exceptions)

An `FactoryException` is thrown when the parameters to override the default values are not part of the original factory.

For example:

```
class ArraysFactory extends Factory
{
    protected static function setFactory(): FactoryInterface
    {
        return new ArrayFactory(
            [
                'one' => 'one',
                'two' => 'two',
                'three' => 'three',
                'four' => 'four',
            ]
        );
    }
}

ArraysFactory::create(
    [
        'five' => 'five'
    ]
);
```

```
Factory: invalid fields: five
```

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity67

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 ~208 days

Total

5

Last Release

1647d ago

PHP version history (2 changes)1.0.0PHP ^7.2

1.1.0PHP ^7.2 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/ae206f49d348a5b75a51accb50e1d1ffb4524fdd6dbfcd4827ad8d5654b5087d?d=identicon)[adlacruzes](/maintainers/adlacruzes)

---

Top Contributors

[![adlacruzes](https://avatars.githubusercontent.com/u/31167513?v=4)](https://github.com/adlacruzes "adlacruzes (65 commits)")

---

Tags

testfactorygeneratedefault

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/adlacruzes-php-factory/health.svg)

```
[![Health](https://phpackages.com/badges/adlacruzes-php-factory/health.svg)](https://phpackages.com/packages/adlacruzes-php-factory)
```

###  Alternatives

[mockery/mockery

Mockery is a simple yet flexible PHP mock object framework

10.7k497.0M23.5k](/packages/mockery-mockery)[hamcrest/hamcrest-php

This is the PHP port of Hamcrest Matchers

7.1k484.1M109](/packages/hamcrest-hamcrest-php)[zenstruck/foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.

78311.9M97](/packages/zenstruck-foundry)[nelmio/alice

Expressive fixtures generator

2.5k43.4M133](/packages/nelmio-alice)[php-mock/php-mock

PHP-Mock can mock built-in PHP functions (e.g. time()). PHP-Mock relies on PHP's namespace fallback policy. No further extension is needed.

36918.1M98](/packages/php-mock-php-mock)[brain/monkey

Mocking utility for PHP functions and WordPress plugin API

33412.5M346](/packages/brain-monkey)

PHPackages © 2026

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