PHPackages                             thecodingmachine/funky - 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. thecodingmachine/funky

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

thecodingmachine/funky
======================

Write service providers easily using annotations

v1.0.0(7y ago)712.1k116MITPHPPHP &gt;=7.1

Since Aug 23Pushed 3y ago6 watchersCompare

[ Source](https://github.com/thecodingmachine/funky)[ Packagist](https://packagist.org/packages/thecodingmachine/funky)[ RSS](/packages/thecodingmachine-funky/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (1)Dependencies (10)Versions (2)Used By (16)

[![Latest Stable Version](https://camo.githubusercontent.com/97283530e4af7099ce5ddb56cb35349a470aa0853a7ae1284232f1b7989c4df7/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f66756e6b792f762f737461626c65)](https://packagist.org/packages/thecodingmachine/funky)[![Total Downloads](https://camo.githubusercontent.com/b778a21158f3ade7641fcc8e14c04d919b263389283c7559dba2fd4c92907a84/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f66756e6b792f646f776e6c6f616473)](https://packagist.org/packages/thecodingmachine/funky)[![Latest Unstable Version](https://camo.githubusercontent.com/d565812938a02cdc26e59cc6e8ef03569ff2e0c18b778acdcf39d8ef13e9ba8c/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f66756e6b792f762f756e737461626c65)](https://packagist.org/packages/thecodingmachine/funky)[![License](https://camo.githubusercontent.com/739605ad7a07c5b14fc10bf761c3adeb6232306502950342a3650f1cb42fd89b/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f66756e6b792f6c6963656e7365)](https://packagist.org/packages/thecodingmachine/funky)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/33b45fdd21270e6924ab0d73ee41ad93e448fa53184101e809264d3e80095d2a/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f746865636f64696e676d616368696e652f66756e6b792f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/thecodingmachine/funky/?branch=master)[![Build Status](https://camo.githubusercontent.com/3a669dbb1c426d05926ee51c6c70bcb07ab1b2730edc4436202b1a18fa74ff1d/68747470733a2f2f7472617669732d63692e6f72672f746865636f64696e676d616368696e652f66756e6b792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/thecodingmachine/funky)[![Coverage Status](https://camo.githubusercontent.com/433c55396193949bebe32aecfc288ea0b2d09d2babb3bd66b2c59d9a6966afc6/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f746865636f64696e676d616368696e652f66756e6b792f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/thecodingmachine/funky?branch=master)

**Work in progress, no stable version yet**

thecodingmachine/funky
======================

[](#thecodingmachinefunky)

Funky is tool to help you write service providers compatible with [container-interop/service-provider](https://github.com/container-interop/service-provider/).

### Without Funky:

[](#without-funky)

The current trend is to directly implement the `ServiceProviderInterface` when writing service providers.

For instance:

```
class WhoopsMiddlewareServiceProvider implements ServiceProviderInterface
{

    public function getFactories()
    {
        return [
            Middleware::class => [self::class,'createMiddleware'],
        ];
    }

    public function getExtensions()
    {
        return [
            MiddlewareListServiceProvider::MIDDLEWARES_QUEUE => [self::class,'updatePriorityQueue']
        ]
    }

    public static function createMiddleware() : WhoopsMiddleware
    {
        return new WhoopsMiddleware();
    }

    public static function updatePriorityQueue(ContainerInterface $container, \SplPriorityQueue $queue) : \SplPriorityQueue
    {
        $queue->insert($container->get(Middleware::class), MiddlewareOrder::EXCEPTION_EARLY);
        return $queue;
    }
}
```

### With Funky:

[](#with-funky)

```
class WhoopsMiddlewareServiceProvider extends Funky\ServiceProvider
{
    /**
     * @Factory(
     *   tags={@Tag(name="middlewares.queue", priority=MiddlewareOrder::EXCEPTION_EARLY)}
     * )
     */
    public static function createMiddleware() : WhoopsMiddleware
    {
        return new WhoopsMiddleware();
    }
}
```

Funky implements the `getFactories` and `getExtensions` methods.

Your class simply extends `TheCodingMachine\Funky\ServiceProvider`. Funky will scan your class for `@Factory` and `@Extension` annotations.

Install
-------

[](#install)

Simply require `thecodingmachine/funky` from your service provider package.

```
$ composer require thecodingmachine/funky
```

Usage
-----

[](#usage)

Instead of creating a class that implements `Interop\Container\ServiceProviderInterface`, you extend the `TheCodingMachine\Funky\ServiceProvider` class.

The @Factory annotation
-----------------------

[](#the-factory-annotation)

### Default naming

[](#default-naming)

By default, the `@Factory` is using the return type as the name of the container entry

```
/**
 * @Factory
 */
public static function createMiddleware() : WhoopsMiddleware
{
    return new WhoopsMiddleware();
}
```

```
$container->get(WhoopsMiddleware::class) // will return the service
```

### Specifying a name

[](#specifying-a-name)

You can use the "name" attribute of the `@Factory` annotation to specify a name:

```
/**
 * @Factory(name="whoops")
 */
public static function createMiddleware() : WhoopsMiddleware
{
    return new WhoopsMiddleware();
}
```

```
$container->get('whoops') // will return the service
```

### Using the method name

[](#using-the-method-name)

You can use the "nameFromMethodName" attribute of the `@Factory` annotation to tell Funky to use the method name as an identifier:

```
/**
 * @Factory(nameFromMethodName=true)
 */
public static function whoopsMiddleware() : WhoopsMiddleware
{
    return new WhoopsMiddleware();
}
```

```
$container->get('whoopsMiddleware') // will return the service
```

Auto-wiring
-----------

[](#auto-wiring)

Funky supports auto-wiring! You can simply add parameters with the appropriate type-hint in your factories and Funky will look for this dependencies in the container.

```
/**
 * @Factory()
 */
public static function myService(LoggerInterface $logger) : MyService
{
    // $logger is fetched from the container using "$container->get(LoggerInterface::class)"
    return new MyService($logger);
}
```

If you do not add type-hints (or use a scalar type-hint), Funky will try to fetch the dependency using the parameter name.

```
/**
 * @Factory()
 */
public static function myService(string $ROOT_PATH) : MyService
{
    // $ROOT_PATH is fetched from the container using "$container->get('ROOT_PATH')"
    return new MyService(string $ROOT_PATH);
}
```

Finally, at any point, you can also inject the whole container to fetch any dependency from it:

```
/**
 * @Factory()
 */
public static function myService(ContainerInterface $container) : MyService
{
    return new MyService($container->get('ROOT_PATH'));
}
```

Extending entries
-----------------

[](#extending-entries)

You can extend entries from the container using the `Extension` annotation.

You should pass the entry to be extended as the first argument. The remaining arguments can be auto-wired just like you do with the factories.

```
/**
 * @Extension()
 */
public static function registerTwigExtension(\Twig_Environment $twig, MyTwigExtension $extension) : \Twig_Environment
{
    $twig->register($extension);
    return $twig;
}
```

### Specifying a name

[](#specifying-a-name-1)

You can use the "name" or "nameFromMethodName" attribute of the `@Extension` annotation to specify the name of the entry to be extended:

```
@Extension(name="twig") // The extended entry is named "twig"

```

```
/**
 * The extended entry is named twig because the method name is "twig"
 * @Extension(name="twig")
 */
public static function registerExtension(\Twig_Environment $twig, MyTwigExtension $extension) : \Twig_Environment
{
    // ...
}
```

```
/**
 * The extended entry is named "twig" because the method name is "twig"
 * @Extension(nameFromMethodName=true)
 */
public static function twig(\Twig_Environment $twig, MyTwigExtension $extension) : \Twig_Environment
{
    // ...
}
```

Tags
----

[](#tags)

Out of the box, the [container-interop/service-provider](https://github.com/container-interop/service-provider/) does not have a notion of tags. However, you can build entries in your container that are actually an array of services. Those arrays can be regarded as "tags".

Funky offers you an easy way to tag services, using the `@Tag` annotation. This is a great way to remove a lot of boilerplate code!

Here is an example:

```
/**
 * @Factory(
 *     tags={@Tag(name="twigExtensions")}
 * )
 */
public static function myTwigExtension(\Twig_Environment $twig, MyTwigExtension $extension) : \MyTwigExtension
{
    // ...
}
```

This piece of code declares a `\MyTwigExtension` entry, and adds this entry to the `twigExtensions` tag.

Thereafter, you can fetch the tagged services from the container easily.

For instance:

```
/**
 * Here, the tag "twigExtensions" used in the function above is injected using auto-wiring.
 * @Factory()
 */
public static function twig(iterable $twigExtensions) : \Twig_Environment
{
    // ...
    $twig = new Twig_Environement(...);
    foreach ($twigExtensions as $twigExtension) {
        $twig->register($twigExtension);
    }
}
```

You can specify an optional priority level for each tagged service:

```
/**
 * @Factory(
 *     tags={@Tag(name="my.tag", priority=42.1)}
 * )
 */
```

Low priority items will appear first. High priority items will appear last.

Note: under the hood, the tagged services are actually `\SplPriorityQueue` objects. Those are iterables, but are not PHP arrays. If you need arrays, you can use the `iterator_to_array` PHP function to cast those in arrays.

FAQ
---

[](#faq)

### Why the name?

[](#why-the-name)

Because the PHP ecosystem loves music (did you notice? Composer, Symfony, ...) And because Funky takes its roots and inspiration from [bitexpert/disco](https://github.com/bitExpert/disco), a PSR-11 compliant container that also relies on annotations!

### Why do factories need to be *static*?

[](#why-do-factories-need-to-be-static)

In the context of service providers, a factory is a function that builds a service based on the parameters it is passed. If you have done some functional programming, you should consider a factory is a **pure function**.

Given a set of parameters, it will always generate the same result. Therefore, a factory have no need of any object state (the state is contained in the container that is passed in parameter).

Furthermore, compiled containers (like Symfony or PHP-DI) can use the fact that a factory is *public static* to greatly optimize the way they work with the service provider. By caching the results given by the `getFactories` and `getExtensions` methods, a compiled container can make the overhead of using Funky to nearly 0.

Troubleshooting
---------------

[](#troubleshooting)

### It says some file cannot be created

[](#it-says-some-file-cannot-be-created)

Funky needs to generate some PHP files to be fast. Those files will be written in the Funky 'generated' directory (so most of the time, in `vendor/thecodingmachine/funky/generated`). If Funky is called from Apache, Apache might not have the right to write files in this directory. You will have to change the rights of this directory to let Apache write in it.

### Some xxxHelper class cannot be autoloaded

[](#some-xxxhelper-class-cannot-be-autoloaded)

As explained above, Funky needs to generate some PHP files to be fast. Those classes are written in the Funky 'generated' directory. If you used [Composer's autoritative classmap](https://getcomposer.org/doc/articles/autoloader-optimization.md#optimization-level-2-a-authoritative-class-maps)(for instance with the `--classmap-authoritative` option), Composer will scan all classes of your project to build the classmap. Problem: Funky's classes are not yet written! So Composer classmap will miss those classes. Therefore, when using Funky, you should not use the `--classmap-authoritative` option.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity57

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

Unknown

Total

1

Last Release

2860d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1104771?v=4)[mouf](/maintainers/mouf)[@Mouf](https://github.com/Mouf)

![](https://avatars.githubusercontent.com/u/1847918?v=4)[TheCodingMachine](/maintainers/thecodingmachine)[@thecodingmachine](https://github.com/thecodingmachine)

---

Top Contributors

[![moufmouf](https://avatars.githubusercontent.com/u/1290952?v=4)](https://github.com/moufmouf "moufmouf (29 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/thecodingmachine-funky/health.svg)

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

###  Alternatives

[akeneo/pim-community-dev

Akeneo PIM, the future of catalog management is open!

1.0k620.8k86](/packages/akeneo-pim-community-dev)[solspace/craft-freeform

The most flexible and user-friendly form building plugin!

53675.5k15](/packages/solspace-craft-freeform)[koriym/attributes

An annotation/attribute reader

433.6M13](/packages/koriym-attributes)[oat-sa/generis

TAO generis library

10144.6k109](/packages/oat-sa-generis)[hostnet/entity-tracker-component

Provides an event when a Tracked entity changes

16159.7k5](/packages/hostnet-entity-tracker-component)[yosimitso/workingforumbundle

A complete forum bundle

425.3k](/packages/yosimitso-workingforumbundle)

PHPackages © 2026

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