PHPackages                             ekvedaras/class-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. ekvedaras/class-factory

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ekvedaras/class-factory
=======================

Factory for creating objects via constructor arguments

v1.2.1(1y ago)7878.6k↓43.2%1MITPHPPHP ^8.1CI passing

Since Aug 30Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/ekvedaras/class-factory)[ Packagist](https://packagist.org/packages/ekvedaras/class-factory)[ Docs](https://github.com/ekvedaras/class-factory)[ RSS](/packages/ekvedaras-class-factory/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (12)Used By (0)

Factory for creating objects via constructor arguments
======================================================

[](#factory-for-creating-objects-via-constructor-arguments)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6bbaab2e3a446b4bf0c9ee674309a63d80b99bc7a36e9da243c5e5153a23e6e0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656b766564617261732f636c6173732d666163746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ekvedaras/class-factory)[![Tests](https://github.com/ekvedaras/class-factory/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/ekvedaras/class-factory/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/f8748c3f895fab223a10ea0ffae75b46aa33af98a21e8672ca8b015efb5d9685/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656b766564617261732f636c6173732d666163746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ekvedaras/class-factory)

A factory class that passes each property directly to constructor. This way your class does not need to deal with received array to create itself from and there is no reflection magic involved. This is mostly useful for creating plain classes like value objects, entities, DTOs, etc.

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

[](#installation)

You can install the package via composer:

```
composer require --dev ekvedaras/class-factory
```

PhpStorm plugin
---------------

[](#phpstorm-plugin)

Provides autocomplete and refactoring capabillities for PhpStorm.

- Plugin: [ClassFactory](https://plugins.jetbrains.com/plugin/19824-classfactory)
- Repository: [class-factory-phpstorm](https://github.com/ekvedaras/class-factory-phpstorm)

Usage
-----

[](#usage)

```
use EKvedaras\ClassFactory\ClassFactory;
use EKvedaras\ClassFactory\ClosureValue;

class Account {
    public function __construct(
        public readonly int $id,
        public string $name,
        public array $orders,
        public \Closure $monitor,
    ) {
    }
}

/** @extends ClassFactory */
class AccountFactory extends ClassFactory {
    protected string $class = Account::class;

    protected function definition(): array
    {
        return [
            'id' => 1,
            'name' => 'John Doe',
            'orders' => [
                OrderFactory::new()->state(['id' => 1]),
                OrderFactory::new()->state(['id' => 2]),
            ],
            'monitor' => new ClosureValue(fn () => true),
        ];
    }

    public function johnSmith(): static
    {
        return $this->state([
            'id' => 2,
            'name' => 'John Smith',
        ]);
    }
}

$account = AccountFactory::new()
    ->johnSmith()                                                           // Can use predefiened states
    ->state(['name' => 'John Smitgh Jnr'])                                  // Can override factory state on the fly
    ->state(['name' => fn (array $attributes) => "{$attributes['name']}."]) // Can use closures and have access to already defined attributes
    ->state(function (array $attributes) {                                  // Can use closures and modify state of multiple attributes by returning an array
        $id = $attributes['id'] + 1;

        return ['id' => $id];
    })
    ->after(fn (Account $account) => sort($account->orders))                // Can modify constructed object after it was created
    ->state(['monitor' => new ClosureValue(fn () => false)])                // Can set state of closure type properties using `ClosureValue` wrapper
    ->make(['id' => 3])                                                     // Can provide final modifications and return the new object
```

### Customising class creation

[](#customising-class-creation)

If you don't want class to be created by directly passing attributes to constructor, you can override `newInstance` method in the factory and do change the behavior.

```
protected function newInstance(array $properties): object
{
    return Account::makeUsingProperties($properties);
}
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Ernestas Kvedaras](https://github.com/ekvedaras)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance60

Regular maintenance activity

Popularity43

Moderate usage in the ecosystem

Community13

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 63.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 ~85 days

Recently: every ~198 days

Total

11

Last Release

498d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/967a95775e4f15cc9f30962b5ed8b24c9a60dd96cf57b78993f74c35e1dc9272?d=identicon)[ekvedaras](/maintainers/ekvedaras)

---

Top Contributors

[![ekvedaras](https://avatars.githubusercontent.com/u/3586184?v=4)](https://github.com/ekvedaras "ekvedaras (55 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (19 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (11 commits)")[![erikgaal](https://avatars.githubusercontent.com/u/1234268?v=4)](https://github.com/erikgaal "erikgaal (2 commits)")

---

Tags

classentitiesfactoryphpvalue-objectsekvedarasclass-factory

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ekvedaras-class-factory/health.svg)

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

PHPackages © 2026

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