PHPackages                             wubinworks/php-di-code-generator - 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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. wubinworks/php-di-code-generator

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

wubinworks/php-di-code-generator
================================

Adds automatic code generation feature to PHP-DI. No need to write Factories for stateful objects anymore.

1.0.0(yesterday)02↑2900%OSL-3.0PHP

Since Jul 23Pushed yesterdayCompare

[ Source](https://github.com/wubinworks/php-di-code-generator)[ Packagist](https://packagist.org/packages/wubinworks/php-di-code-generator)[ Docs](https://www.wubinworks.com)[ RSS](/packages/wubinworks-php-di-code-generator/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

Code generator for PHP-DI
=========================

[](#code-generator-for-php-di)

Adds automatic code generation feature to [PHP-DI](https://php-di.org/).

Features
--------

[](#features)

- No need to write `Factories` for *stateful objects* anymore.

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

[](#requirements)

***(\*)Note this package is a feature extension for [PHP-DI](https://php-di.org/) and only works if the system makes use of the PHP-DI's container.***

- PHP &gt;= 7.2
- [php-di/php-di](https://github.com/PHP-DI/PHP-DI) &gt;= 6.3.5

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

[](#installation)

```
composer require wubinworks/php-di-code-generator
```

Container setup steps
---------------------

[](#container-setup-steps)

### 1. Add definition of the code generator to the container builder

[](#1-add-definition-of-the-code-generator-to-the-container-builder)

#### Parameters required for setting up the code generator

[](#parameters-required-for-setting-up-the-code-generator)

- `codeDirectory`

This directory will contain the generated PHP files and **should** reside inside the project root directory.

The recommended path is `'/generated/code'`.

- `logger`

This parameter([PSR-3: Logger Interface](https://www.php-fig.org/psr/psr-3/)) is ***optional*** and must be `null|\Psr\Log\LoggerInterface`.

#### Example setup

[](#example-setup)

```
...
// Definition for setting up the code generator's autoloader
/** @var \DI\ContainerBuilder $containerBuilder */
$containerBuilder->addDefinitions([
    'Wubinworks\PHPDICodeGenerator\Code\Generation\Generator\*Generator' => \DI\autowire()
        ->constructorParameter('codeDirectory', '/generated/code'),
    \Wubinworks\PHPDICodeGenerator\Code\Generation\Autoloader::class => \DI\autowire()
        ->constructorParameter('generators', [
            \DI\get(\Wubinworks\PHPDICodeGenerator\Code\Generation\Generator\FactoryGenerator::class)
        ])
        ->constructorParameter('logger', static function () {
            $logger = new \Monolog\Logger('code-generator');
            $logger->pushHandler(new \Monolog\Handler\StreamHandler('/var/log/code-generator.log'));

            return $logger;
        })
]);
...
/** @var \DI\Container|\Psr\Container\ContainerInterface $container */
$container = $containerBuilder->build();
```

### 2. Register the code generator's autoloader right after building the container

[](#2-register-the-code-generators-autoloader-right-after-building-the-container)

```
$container->get(\Wubinworks\PHPDICodeGenerator\Code\Generation\Autoloader::class)
    ->register();
```

### 3. Add autoload configuration to root `composer.json`

[](#3-add-autoload-configuration-to-root-composerjson)

***Note this step is optional, but is strongly recommended for performance improvement.***

```
...
{
    "autoload": {
        ...
        "psr-4": {
            "": [
                ...
                "generated/code/",
                ...
            ]
        }
        ...
    }
}
...
```

How it works
------------

[](#how-it-works)

When the container is looking for a class whose name ends with `Factory` and that class does not exist, the code generator's autoloader is triggered. Then the missing `Factory`'s PHP file will be generated and included.

Usage
-----

[](#usage)

### 1. Append `Factory` suffix

[](#1-append-factory-suffix)

Suppose you already have `\Vendor\Namespace\StatefulObject` class and it can be autoloaded (by composer's autoloader). Usually, you need to write a `Factory` class in order to create different instances of that stateful object.

With this code generator, you do not need to write those `Factory` classes anymore.

What you need to do is just to append the `Factory` suffix to `\Vendor\Namespace\StatefulObject`.

```
use Vendor\Namespace\StatefulObject;
use Vendor\Namespace\StatefulObjectFactory; // Appended the Factory suffix

// Confirm \Vendor\Namespace\StatefulObjectFactory class does NOT exist without autoloading
var_dump(class_exists(StatefulObjectFactory::class), false);
// false
```

### 2. Generate the `Factory` class

[](#2-generate-the-factory-class)

```
class Example
{
    /**
     * @var StatefulObjectFactory
     */
    private $statefulObjectFactory;

    /**
     * Constructor
     *
     * Use PHP-DI's dependency injection
     *
     * @param StatefulObjectFactory $statefulObjectFactory
     * ...
     */
    public function __construct(
        StatefulObjectFactory $statefulObjectFactory,
        ...
    ) {
        $this->statefulObjectFactory = $statefulObjectFactory;
        ...
        // Confirm now \Vendor\Namespace\StatefulObjectFactory exists without autoloading
        var_dump(class_exists(StatefulObjectFactory::class), false);
        // true
        // Because `\Vendor\Namespace\StatefulObjectFactory`'s PHP file has been generated and included
    }

    ...
}
```

***Note the following ways also work but are HIGHLY DEPRECATED. You should use the PHP-DI's constructor/property injection instead.***

```
$factory = new StatefulObjectFactory();
```

```
/** @var \Psr\Container\ContainerInterface $container */
$factory = $container->get(StatefulObjectFactory::class);
```

Then you can confirm file `/generated/code/Vendor/Namespace/StatefulObjectFactory.php` has been generated.

*Note `class_exists(StatefulObjectFactory::class, /** The second parameter is true */ true)` can also trigger the code generation.*

### 3. Use the generated `Factory` to create stateful objects

[](#3-use-the-generated-factory-to-create-stateful-objects)

The generated `Factory` always has a `create` method and this method takes an ***array*** of constructor parameters of the object it can create.

```
$statefulObject = $factory->create([...]); // [...] are constructor parameters of \Vendor\Namespace\StatefulObject
var_dump(get_class($statefulObject) === StatefulObject::class);
// true

// Same constructor parameters
var_dump($factory->create([...]) !== $factory->create([...]));
// true
// Factory created different instances
```

What `Factories` cannot be generated?
-------------------------------------

[](#what-factories-cannot-be-generated)

**`Factories` of the followings cannot be generated. If you attempt to do so, the code generator will not output anything nor will it throw an exception. Instead, this error will be logged if you [specified a logger](#parameters-required-for-setting-up-the-code-generator) for the code generator autoloader.**

- Non-exist class
- Abstract class
- Trait
- Enum
- Interface without definition (i.e., no preference)

Unit testing
------------

[](#unit-testing)

Install the `require-dev` dependencies and run the following command.

```
vendor/bin/phpunit
```

♥
-

[](#)

If you like this package or this package helped you, please ***share*** and ***give a ★☆star☆★***, it's NOT hard!

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance100

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7de965a6287fb784969afeb4b173521d3cb59c6b873b7248263abb9fc098eddd?d=identicon)[wubinworks](/maintainers/wubinworks)

---

Top Contributors

[![wubinworks](https://avatars.githubusercontent.com/u/127310257?v=4)](https://github.com/wubinworks "wubinworks (1 commits)")

---

Tags

autoloadcode-generationcode-generatorcontainerfactoryphp-diphp-di-containerpsr-11psr-4statefulcontainerPSR-11factoryautoloadcode generatorpsr11PSR-4code-generationphp-distateful

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/wubinworks-php-di-code-generator/health.svg)

```
[![Health](https://phpackages.com/badges/wubinworks-php-di-code-generator/health.svg)](https://phpackages.com/packages/wubinworks-php-di-code-generator)
```

###  Alternatives

[php-di/php-di

The dependency injection container for humans

2.8k55.5M1.3k](/packages/php-di-php-di)[elie29/zend-phpdi-config

PSR-11 PHP-DI autowire container configurator for Laminas, Mezzio, ZF2, ZF3 and Zend Expressive applications

19248.3k8](/packages/elie29-zend-phpdi-config)[phpwatch/simple-container

A fast and minimal PSR-11 compatible Dependency Injection Container with array-syntax and without auto-wiring

1811.8k2](/packages/phpwatch-simple-container)

PHPackages © 2026

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