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

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

roke22/php-dynamic-factory
==========================

Dynamic factory to create objects reading the parameters of the construct method

v1.0.3(10mo ago)319MITPHPPHP ^7.4||^8.0CI passing

Since Mar 8Pushed 10mo ago1 watchersCompare

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

READMEChangelog (4)Dependencies (2)Versions (5)Used By (0)

PHP Dynamic Factory
===================

[](#php-dynamic-factory)

[![PHP Tests](https://github.com/roke22/php-dynamic-factory/actions/workflows/php.yml/badge.svg)](https://github.com/roke22/php-dynamic-factory/actions/workflows/php.yml)

A simple and powerful PHP library to dynamically create objects from arrays. It intelligently maps array keys to your class constructor parameters, saving you from writing repetitive boilerplate code.

Its main strengths are:

- Automatic `snake_case` to `camelCase` conversion, ideal for creating objects from database records or API responses.
- Recursive creation of nested objects and arrays of objects.
- A `DynamicFactory` capable of generating objects with random data for testing (using Faker).

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

[](#installation)

Install the library via Composer:

```
composer require roke22/php-dynamic-factory
```

`ArrayToObject`: Creating Objects from Arrays
---------------------------------------------

[](#arraytoobject-creating-objects-from-arrays)

This is the core of the library. It allows you to build an object by providing its class name and an array of data.

### Basic Usage (Default `snake_case`)

[](#basic-usage-default-snake_case)

By default, the library assumes your input array keys are in `snake_case` and converts them to the `camelCase` expected by your constructor parameters. This is the most common use case.

**Example:**

Let's say you have a `User` class:

```
class User
{
    public string $userName;
    public string $userEmail;

    public function __construct(string $userName, string $userEmail)
    {
        $this->userName = $userName;
        $this->userEmail = $userEmail;
    }
}
```

And you have data from a database or an API:

```
$userData = [
    'user_name' => 'John Doe',
    'user_email' => 'john.doe@example.com'
];
```

You can create the `User` object with a single line:

```
use Roke\PhpFactory\ArrayToObject;

$user = ArrayToObject::make($userData, User::class);

// $user is now a User object with properties:
// $user->userName = 'John Doe';
// $user->userEmail = 'john.doe@example.com';
```

### Handling `camelCase` Input

[](#handling-camelcase-input)

If your input data is already in `camelCase`, you must specify it explicitly.

```
use Roke\PhpFactory\ArrayToObject;

$userData = [
    'userName' => 'Jane Doe',
    'userEmail' => 'jane.doe@example.com'
];

// Explicitly state the input format
$user = ArrayToObject::make($userData, User::class, ArrayToObject::CAMEL);
```

### Advanced Usage: Nested Objects

[](#advanced-usage-nested-objects)

The library automatically handles complex, nested objects and even arrays of objects. It reads your constructor's type hints and `@param` annotations to resolve dependencies.

**Example:**

Consider this complex structure:

```
// Garage.php
class Garage {
    public function __construct(string $location, Car $mainCar) { /* ... */ }
}

// Car.php
class Car {
    /** @param Wheel[] $wheels */
    public function __construct(string $modelName, Engine $engine, array $wheels) { /* ... */ }
}

// Engine.php
class Engine {
    public function __construct(float $liters, int $cylinders) { /* ... */ }
}

// Wheel.php
class Wheel {
    public function __construct(int $size, string $brand) { /* ... */ }
}
```

*Note: For arrays of objects, you must use the fully qualified class name in the `@param` annotation, e.g., `@param array $wheels`.*

You can build the entire `Garage` object from a single nested array:

```
$garageData = [
    'location' => 'Main Base',
    'main_car' => [
        'model_name' => 'Z-2000',
        'engine' => [
            'liters' => 6.2,
            'cylinders' => 8,
        ],
        'wheels' => [
            ['size' => 18, 'brand' => 'BrandA'],
            ['size' => 18, 'brand' => 'BrandB'],
        ],
    ],
];

$garage = ArrayToObject::make($garageData, Garage::class);

// $garage is now a fully hydrated object with a Car, which has an Engine and an array of Wheels.
```

`DynamicFactory`: Generating Test Data
--------------------------------------

[](#dynamicfactory-generating-test-data)

For testing, you can instantly create objects with random data powered by [Faker](https://github.com/fakerphp/faker).

### Basic Usage

[](#basic-usage)

```
use Roke\PhpFactory\DynamicFactory;

// Creates a User object with random name and email
$randomUser = DynamicFactory::create(User::class);
```

### Overriding Attributes

[](#overriding-attributes)

You can provide specific values for some fields while letting the factory generate the rest.

```
$userWithSpecificName = DynamicFactory::create(User::class, [
    'userName' => 'A specific name'
]);

// $userWithSpecificName->userName will be 'A specific name'
// $userWithSpecificName->userEmail will be a random email
```

### Advanced Faker and Value Annotations

[](#advanced-faker-and-value-annotations)

You can control the data generation process using `@faker` and `@value` annotations in your class constructor's DocComment.

```
class Product
{
    public string $name;
    public string $category;
    public int $price;

    /**
     * @value $category ["electronics", "books", "home"]
     * @faker $price $faker->numberBetween(100, 1000)
     */
    public function __construct(string $name, string $category, int $price)
    {
        // ...
    }
}

$product = DynamicFactory::create(Product::class);

// $product->category will be one of the specified values.
// $product->price will be a random number between 100 and 1000.
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance54

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

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

Total

4

Last Release

304d ago

### Community

Maintainers

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

---

Top Contributors

[![roke22](https://avatars.githubusercontent.com/u/5707837?v=4)](https://github.com/roke22 "roke22 (11 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[verbb/formie

The most user-friendly forms plugin for Craft.

101372.9k40](/packages/verbb-formie)[blair2004/nexopos

The Free Modern Point Of Sale System build with Laravel, TailwindCSS and Vue.js.

1.2k2.3k](/packages/blair2004-nexopos)[solspace/craft-freeform

The most flexible and user-friendly form building plugin!

52664.9k12](/packages/solspace-craft-freeform)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[pablorsk/argentina-data-generator

Argentina data generator for CUIT and CBU numbers

1323.7k](/packages/pablorsk-argentina-data-generator)

PHPackages © 2026

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