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

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

locomotivemtl/charcoal-factory
==============================

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

0.4.2(8y ago)023.6k12MITPHPPHP &gt;=5.6.0

Since Nov 26Pushed 7y ago13 watchersCompare

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

READMEChangelog (7)Dependencies (3)Versions (10)Used By (12)

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

[](#charcoal-factory)

Factories **create** (or build) dynamic PHP objects. 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.

[![Build Status](https://camo.githubusercontent.com/c251f17b53cb766ef5d51ff601fe5a9cba6895125f1c4d2846fafc157909e2dd/68747470733a2f2f7472617669732d63692e6f72672f6c6f636f6d6f746976656d746c2f63686172636f616c2d666163746f72792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/locomotivemtl/charcoal-factory)

Table of contents
=================

[](#table-of-contents)

- How to install
    - Dependencies
- Factories
    - Usage
    - The resolver
    - Class map / aliases
    - Ensuring a type of object
    - Setting a default type of object
    - Constructor arguments
    - Executing an object callback
- Development
    - Development dependencies
    - Continus integration
    - Coding style
    - Authors
    - Changelog
- License

How to install
==============

[](#how-to-install)

The preferred (and only supported) way of installing *charcoal-factory* is with **composer**:

```
★ composer require locomotivemtl/charcoal-factory
```

Dependencies
------------

[](#dependencies)

- [`PHP 5.5+`](http://php.net)
    - Older versions of PHP are deprecated, therefore not supported for charcoal-factory.

> 👉 Development dependencies, which are optional when using charcoal-factory, are described in the [Development](#development) section of this README file.

Factories
=========

[](#factories)

Usage
-----

[](#usage)

Factories have only one purpose: to **create** / instanciate new PHP objects. 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.\[1\] If no resolver is provided, a default `\Charcoal\Factory\GenericResolver` will be used.

The resolver
------------

[](#the-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 / aliases
-------------------

[](#class-map--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);
```

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.');
    }
]);
```

Development
===========

[](#development)

To install the development environment:

```
★ composer install --prefer-source
```

To run the scripts (phplint, phpcs and phpunit):

```
★ composer test
```

Development dependencies
------------------------

[](#development-dependencies)

- `phpunit/phpunit`
- `squizlabs/php_codesniffer`
- `satooshi/php-coveralls`

Continuous Integration
----------------------

[](#continuous-integration)

ServiceBadgeDescription[Travis](https://travis-ci.org/locomotivemtl/charcoal-factory)[![Build Status](https://camo.githubusercontent.com/c251f17b53cb766ef5d51ff601fe5a9cba6895125f1c4d2846fafc157909e2dd/68747470733a2f2f7472617669732d63692e6f72672f6c6f636f6d6f746976656d746c2f63686172636f616c2d666163746f72792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/locomotivemtl/charcoal-factory)Runs code sniff check and unit tests. Auto-generates API documentation.[Scrutinizer](https://scrutinizer-ci.com/g/locomotivemtl/charcoal-factory/)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/c72f3fd20440cf51db122183d50cbefd05d32df12c5cb1df603095592730e423/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c6f636f6d6f746976656d746c2f63686172636f616c2d666163746f72792f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/locomotivemtl/charcoal-factory/?branch=master)Code quality checker. Also validates API documentation quality.[Coveralls](https://coveralls.io/github/locomotivemtl/charcoal-factory)[![Coverage Status](https://camo.githubusercontent.com/3b2352f4e89b20cfc34cfade04e93af0b6eab4624bdeac4c8912d908d74b9d50/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6c6f636f6d6f746976656d746c2f63686172636f616c2d666163746f72792f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/locomotivemtl/charcoal-factory?branch=master)Unit Tests code coverage.[Sensiolabs](https://insight.sensiolabs.com/projects/0aec930b-d696-415a-b4ef-a15c1a56509e)[![SensioLabsInsight](https://camo.githubusercontent.com/b86ae497c71a1376e9484e7011418c12c210886dc472ab80d3f1a15a883ef5cb/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f30616563393330622d643639362d343135612d623465662d6131356331613536353039652f6d696e692e706e67)](https://insight.sensiolabs.com/projects/0aec930b-d696-415a-b4ef-a15c1a56509e)Another code quality checker, focused on PHP.Coding Style
------------

[](#coding-style)

All Charcoal modules follow the same coding style and `charcoal-factory` is no exception. For PHP:

- [*PSR-1*](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
- [*PSR-2*](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
- [*PSR-4*](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md), autoloading is therefore provided by *Composer*
- [*phpDocumentor*](http://phpdoc.org/)
- Read the [phpcs.xml](phpcs.xml) file for all the details on code style.

> Coding style validation / enforcement can be performed with `composer phpcs`. An auto-fixer is also available with `composer phpcbf`.

Authors
=======

[](#authors)

- Mathieu Ducharme

License
=======

[](#license)

Charcoal is licensed under the MIT license. See [LICENSE](LICENSE) for details.

Changelog
=========

[](#changelog)

### 0.3.2

[](#032)

- Split resolved classname "cache" by factory class.

### 0.3.1

[](#031)

*Released 2016-03-22*

- Keep resolved classname in memory. Can greatly speed things up if instancing many objects.

### 0.3

[](#03)

*Released 2016-01-28*

- Add the `setArguments()` method to factories.
- Add the `setCallback()` method to factories.
- Execute the callback when using the default class too.

### 0.2

[](#02)

*Released 2016-01-26*

Minor (but BC-breaking) changes to Charcoal-Factory

- Full PSR1 compliancy (All methods are now camel-case).
- Add a callback argument to the `create()` method.
- `create()` and `get()` are now `final` in the base abstract factory class.
- Internal code, docs and tool improvements.

### 0.1

[](#01)

*Released 2015-11-25*

- Initial release

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 71.7% 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 ~142 days

Total

8

Last Release

3133d ago

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

0.4.2PHP &gt;=5.6.0

### Community

Maintainers

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

---

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)")

---

Tags

charcoal

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[asgardcms/asgardcms-installer

AsgardCms application installer.

2842.6k](/packages/asgardcms-asgardcms-installer)[beholdr/filament-trilist

Filament plugin that adds components for working with tree data: treeselect and treeview

1120.6k](/packages/beholdr-filament-trilist)[avency/neos-vardump

Neos VarDump Package

147.1k](/packages/avency-neos-vardump)

PHPackages © 2026

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