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

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

charcoal/factory
================

Charcoal object creation (Factory, AbstractFactory, Builder, Class Resolver)

v5.0.0(2y ago)010310MITPHPPHP ^7.4 || ^8.0

Since Nov 26Pushed 2y ago2 watchersCompare

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

READMEChangelogDependencies (3)Versions (34)Used By (10)

Charcoal Factory
================

[](#charcoal-factory)

The Factory package provides abstract object factories to create objects.

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

[](#installation)

```
composer require charcoal/factory
```

Usage
-----

[](#usage)

Factories can resolve a *type* to a FQN and create instance of this class with an optional given set of arguments, while ensuring a default base class.

Factory options should be set directly from the constructor:

```
$factory = new Charcoal\Factory\GenericFactory([
    // Ensure the created object is a Charcoal Model
    'base_class' => '\Charcoal\Model\ModelInterface',

    // An associative array of class map (aliases)
    'map' => [
        'foo' => '\My\Foo',
        'bar' => '\My\Bar',
    ],

    // Constructor arguments
    'arguments' => [
        $dep1,
        $dep2,
    ],

    // Object callback
    'callback' => function ($obj) {
        $obj->do('foo');
    },
]);

// Create a "\My\Custom\Baz" object with the given arguments + callbck
$factory->create('\My\Custom\Baz');

// Create a "\My\Foo" object (using the map of aliases)
$factory->create('foo');

// Create a "\My\Custom\FooBar" object with the default resolver
$factory->create('my/custom/foo-bar');
```

Constructor options (class dependencies) are:

NameTypeDefaultDescription`base_class`*string*`''`Optional. A base class (or interface) to ensure a type of object.`default_class`*string*`''`Optional. A default class, as fallback when the requested object is not resolvable.`arguments`*array*`[]`Optional. Constructor arguments that will be passed along to created instances.`callback`*callable*`null`Optional. A callback function that will be called upon object creation.`resolver`*callable*`null`\[1\]Optional. A class resolver. If none is provided, a default will be used.`resolver_options`*array*`null`Optional. Resolver options (prefix, suffix, capitals and replacements). This is ignored / unused if `resolver` is provided.Notes:

- \[1\] If no resolver is provided, a default `\Charcoal\Factory\GenericResolver` will be used.

### Class resolver

[](#class-resolver)

The *type* (class identifier) sent to the `create()` method can be parsed / resolved with a custom `Callable` resolver.

If no `resolver` is passed to the constructor, a default `\Charcoal\Factory\GenericResolver` is used. This default resolver transforms, for example, `my/custom/foo-bar` into `\My\Custom\FooBar`.

### Class map and aliases

[](#class-map-and-aliases)

Class *aliases* can be added by setting them in the Factory constructor:

```
$factory = new GenericFactory([
    'map' => [
        'foo' => '\My\Foo',
        'bar' => '\My\Bar',
    ],
]);

// Create a `\My\Foo` instance
$obj = $factory->create('foo');
```

### Ensuring a type of object

[](#ensuring-a-type-of-object)

Ensuring a type of object can be done by setting the `base_class` property.

The recommended way of setting the base class is by setting it in the constructor:

```
$factory = new GenericFactory([
    'base_class' => '\My\Foo\BaseClassInterface',
]);
```

> 👉 Note that *Interfaces* can also be used as a factory's base class.

### Setting a default type of object

[](#setting-a-default-type-of-object)

It is possible to set a default type of object (default class) by setting the `default_class` property.

The recommended way of setting the default class is by setting it in the constructor:

```
$factory = new GenericFactory([
    'default_class' => '\My\Foo\DefaultClassInterface',
]);
```

> ⚠️ Setting a default class name changes the standard Factory behavior. When an invalid class name is used, instead of throwing an `Exception`, an object of the default class type will **always** be returned.

### Constructor arguments

[](#constructor-arguments)

It is possible to set "automatic" constructor arguments that will be passed to every created object.

The recommended way of setting constructor arguments is by passing an array of arguments to the constructor:

```
$factory = new GenericFactory([
    'arguments' => [
        [
            'logger' => $container['logger'],
        ],
        $secondArgument,
    ],
]);
```

### Executing an object callback

[](#executing-an-object-callback)

It is possible to execute an object callback upon object instanciation. A callback is any `Callable` that takes the newly created object by reference as its function parameter.

```
// $obj is the newly created object
function callback($obj): void;
```

The recommended way of adding an object callback is by passing a `Callable` to the constructor:

```
$factory = new GenericFactory([
    'arguments' => [[
        'logger' => $container['logger']
    ]],
    'callback' => function ($obj) {
        $obj->foo('bar');
        $obj->logger->debug('Objet instanciated from factory.');
    }
]);
```

Resources
---------

[](#resources)

- [Contributing](https://github.com/charcoalphp/.github/blob/main/CONTRIBUTING.md)
- [Report issues](https://github.com/charcoalphp/charcoal/issues) and [send pull requests](https://github.com/charcoalphp/charcoal/pulls)in the [main Charcoal repository](https://github.com/charcoalphp/charcoal)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community22

Small or concentrated contributor base

Maturity79

Established project with proven stability

 Bus Factor1

Top contributor holds 60.3% 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 ~98 days

Recently: every ~21 days

Total

32

Last Release

788d ago

Major Versions

0.4.2 → v2.1.22022-06-21

v2.2.3 → v3.1.02022-08-08

v3.1.8 → v4.0.02022-09-21

v4.1.0 → v5.0.02024-03-13

PHP version history (3 changes)0.1PHP &gt;=5.5.0

0.4.2PHP &gt;=5.6.0

v2.1.2PHP ^7.4 || ^8.0

### Community

Maintainers

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

![](https://www.gravatar.com/avatar/0a4f39523b4b2837562ba0848a0327b8d340118d1ba87cb0f5d59b1d5cb6beba?d=identicon)[mcaskill](/maintainers/mcaskill)

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

![](https://www.gravatar.com/avatar/4229f19eecd12c2b651b6502dcc5adfba48c5770db3d2dbea55fc92c7a246b2b?d=identicon)[BeneRoch](/maintainers/BeneRoch)

---

Top Contributors

[![mducharme](https://avatars.githubusercontent.com/u/12157?v=4)](https://github.com/mducharme "mducharme (38 commits)")[![mcaskill](https://avatars.githubusercontent.com/u/29353?v=4)](https://github.com/mcaskill "mcaskill (15 commits)")[![actions-user](https://avatars.githubusercontent.com/u/65916846?v=4)](https://github.com/actions-user "actions-user (10 commits)")

---

Tags

builder-patternfactoryfactory-patternphpread-only-repositorycharcoal

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[symfony/dependency-injection

Allows you to standardize and centralize the way objects are constructed in your application

4.2k431.1M7.5k](/packages/symfony-dependency-injection)[kenjis/codeigniter-composer-installer

Package to install CodeIgniter3 via Composer with secure folder structure.

37561.8k](/packages/kenjis-codeigniter-composer-installer)

PHPackages © 2026

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