PHPackages                             hartmann/planck - 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. hartmann/planck

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

hartmann/planck
===============

minimalistic, PSR-11(+) conformant, provider-based container

2.2.0(7y ago)0391MITPHPPHP &gt;=7.1

Since Mar 27Pushed 7y agoCompare

[ Source](https://github.com/mark-hartmann/planck)[ Packagist](https://packagist.org/packages/hartmann/planck)[ RSS](/packages/hartmann-planck/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (4)Versions (12)Used By (1)

[![Latest Stable Version](https://camo.githubusercontent.com/85f3991cbd9a72494f4a0f2ec159032a21451f0924266cb0bb905efccb7db54c/68747470733a2f2f706f7365722e707567782e6f72672f686172746d616e6e2f706c616e636b2f762f737461626c65)](https://packagist.org/packages/hartmann/planck)[![License](https://camo.githubusercontent.com/c9d33cb3dddc543faa6aaffb2a2557440d27e495983b56072b8bbd2483a99a71/68747470733a2f2f706f7365722e707567782e6f72672f686172746d616e6e2f706c616e636b2f6c6963656e7365)](https://packagist.org/packages/hartmann/planck)

Planck
======

[](#planck)

Planck is a minimalistic dependency injection container with [PSR-11](https://www.php-fig.org/psr/psr-11/)[+](https://github.com/container-interop/service-provider) support, (heavily) inspired by Pimple/Simplex. For now, i even use most of their documentation, but i'll change that later.

- `Hartmann\Planck\Container` implements [`ContainerInterface`](https://github.com/container-interop/container-interop/blob/master/src/Interop/Container/ContainerInterface.php) and fully supports container-interop's [`ServiceProviderInterface`](https://github.com/container-interop/service-provider/blob/master/src/ServiceProviderInterface.php)

    - `$container->extend()`
        - Can be used to extend scalar values, factories and services
    - `$container->factory()`
        - Can be used to mark a callable as being a factory service. If so, each time the entry gets requested, a new instance is returned
    - `$container->preserve()`
        - Can be used to protect/preserve a function from being used by the container as a service factory.
    - `$container->autowire()`
        - Can be used to autowire functions and classes.

Installation
============

[](#installation)

```
composer require hartmann/planck

```

Usage
=====

[](#usage)

Creating a container is a matter of creating a `Container` instance:

```
$container = new \Hartmann\Planck\Container();
```

Defining Service Providers
--------------------------

[](#defining-service-providers)

A service provider is an object that does something as part of a larger system. Examples of services: a database connection, a templating engine, or a mailer. Almost any **global** object can be a service.

Services are defined by **anonymous functions** that return an instance of an object:

```
use Interop\Container\ServiceProviderInterface

class Provider implements ServiceProviderInterface
{
    public function getFactories()
    {
        return [
            stdClass::class => function(ContainerInterface $container) {
                return new stdClass;
            },
            ...
        ];
    }

    public function getExtensions()
    {
        return [
            stdClass::class => function(ContainerInterface $container, ?stdClass $class) {
                $class->foo = 'bar';

                return $class;
            },
            ...
        ];
    }
}
```

Notice that the anonymous function has access to the current container instance, allowing references to other services or parameters.

As objects are only created when you get them, the order of the definitions does not matter.

Using the defined services is also very easy:

```
$class = $container->get(stdClass::class);
```

Defining Factory Services
-------------------------

[](#defining-factory-services)

By default, each time you get a service, Planck returns the **same instance**of it. If you want a different instance to be returned for all calls, wrap your anonymous function with the `factory()` method

```
$container->set('factory', $container->factory(function (ContainerInterface $container) {
    return new stdClass;
}));
```

Each call to `$container->get(stdClass::class)` now returns a new instance of stdClass.

Defining Parameters
-------------------

[](#defining-parameters)

Defining a parameter allows to ease the configuration of your container from the outside and to store global values:

```
$container->set('cookie_name', 'SESSION_ID');
$container->set('session_storage_class', 'SessionStorage');
```

You can now easily change the cookie name by overriding the `session_storage_class` parameter instead of redefining the service definition.

Preserving / Protecting Parameters
----------------------------------

[](#preserving--protecting-parameters)

Because Planck sees anonymous functions as service definitions, you need to wrap anonymous functions with the `preserve()` method to store them as parameters:

```
$container->set('random_bytes', $container->preserve(function () {
    return random_bytes(4);
}));
```

Modifying Services after Definition
-----------------------------------

[](#modifying-services-after-definition)

In some cases you may want to modify a service definition after it has been defined. You can use the `extend()` method to define additional code to be run on your service just after it is created:

```
$container->set('session_storage', function (ContainerInterface $container) {
    return new $container->get('session_storage_class')($container->get('cookie_name'));
});

$container->extend('session_storage', function (ContainerInterface $container, ?SessionStorage $storage) {
    $storage->...();

    return $storage;
});
```

Autowiring
----------

[](#autowiring)

Sometimes it is practical to resolve dependencies on the container itself. To make this possible, the `autowire()` method is used.
Both classes and anonymous functions can be wired.

```
$container->set(Foo::class, new Foo());
$container->set(Bar::class, new Bar());

$container->set('autowired', $container->autowire(function (Foo $foo, Bar $bar) {
    return ...
}));
```

The `autowire()` method has as second parameter `array $parameters = []`.
If you know the `Container` is not able to resolve a parameter or you wish to pass your own value, you can easily do so:

```
class Foo {
    ...
}

$container->set(Foo::class, new Foo());
$container->set('autowired', $container->autowire(function (Foo $foo, $bar) {
    var_dump($foo) // object Foo
    var_dump($bar) // string 'foo'
}, ['bar' => 'foo']]));
```

Since version `1.0.3` it is possible to pass callables in form of arrays.
This allows to autowire static and non-static object methods, which can be useful for an incredible number of things, such as controllers:

```
class HomeController {

    protected $logger

    public function __contruct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function index(Request $request, Response $response): Response
    {
        $this->logger->info('someone visited my site!');

        return $response->write('Hello');
    }
}

// adding the required classes to the container ...
$container->autowire([HomeController::class, 'index']);
```

This also works with already instanciated objects:

```
$container->autowire([$homeControllerInstance, 'index']);
```

Extended classes behave normally as long as the dependencies are registered in the container.

```
class Request
{
    public function __construct(string $method, UriInterface $uri, HeadersInterface $headers, ...);
}

class CreateUserRequest extends Request {
    ...
}

// adding the required classes to the container ...
$container->autowire(CreateUserRequest::class, ['method' => $requestMethod]);
```

Hinted parameters &amp; autowiring:
-----------------------------------

[](#hinted-parameters--autowiring)

With php 5 and 7 named parameters were added. Planck can handle builtin and normal hints.
The following constellations are possible.

```
// unresolvable, must be passed directly to the parameters
function ($foo) {
}

// unresolvable, must be passed directly to the parameters
function (string|int|float|array|bool $foo) {
}

// hinted, required
function (Foo $foo) {
}

// hinted, optional
function (Foo $foo = null) {
}

// hinted, nullable
function (?Foo $foo) {
}
```

If no value could be found for nullable parameters, null is passed.
If no value could be found for optional parameters, the default value is passed.

**Referenced parameters are NOT supported**, you have to register such entries using the `set` method.

Implicit autowiring:
--------------------

[](#implicit-autowiring)

Planck also offers the option of implicit autowiring, i.e. classes that have not yet been stored in the container but are requested can be created automatically.

To activate this, the following method must be called:

```
$container->enableImplicitAutowiring(true); // enable
$container->enableImplicitAutowiring(false); // disable
```

Now the following can be called without errors:

```
$container = new \Hartmann\Planck\Container
$container->enableImplicitAutowiring(true);

$container->set('autowired', $container->autowire(function(Foo $foo, Bar $bar) {
    return ...
}));

$value = $container->get('autowired');
```

After the class has been implicitly loaded, it is stored directly in the container.
Only classes can be loaded implicitly.

Resolve Strategies
------------------

[](#resolve-strategies)

Resolve strategies can be used to automatically resolve classes that can be similarly created.
For example, if you use FormRequests to validate input fields, they can be resolved using a corresponding strategy without having to create a service factory for each one.

This could look like this:

```
use \Hartmann\ResolveStrategy\ResolveStrategyInterface

class RequestResolveStrategy implements ResolveStrategyInterface
{
    public function suitable(string $class): bool
    {
        return method_exists($class, 'createFromEnvironment') && in_array(FormRequest::class, class_parents($class));
    }

    public function resolve(\Psr\Container\ContainerInterface $container, string $class)
    {
        return call_user_func([$class, 'createFromEnvironment'], $container->get('environment'));
    }
}

$container = new \Hartmann\Planck\Container();

$container->enableImplicitAutowiring(true);
$container->addResolveStrategy(new RequestResolveStrategy());

$container->get(CreateUserFormRequest::class);
$container->get(DeletePostFormRequest::class);
$container->get(LoginFormRequest::class);
```

***For this to work, implicit autowiring must be enabled.***

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity61

Established project with proven stability

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

Total

11

Last Release

2578d ago

Major Versions

1.0.5 → 2.0.02019-04-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/1a2b9cbc9878208f8dfc12eaf51dd52aaced7a57a810c35d0731719bd162e7ca?d=identicon)[mark-hartmann](/maintainers/mark-hartmann)

---

Top Contributors

[![mark-hartmann](https://avatars.githubusercontent.com/u/21173286?v=4)](https://github.com/mark-hartmann "mark-hartmann (28 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hartmann-planck/health.svg)

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

###  Alternatives

[pimple/pimple

Pimple, a simple Dependency Injection Container

2.7k130.5M1.4k](/packages/pimple-pimple)[league/container

A fast and intuitive dependency injection container.

86387.8M343](/packages/league-container)[mnapoli/simplex

Pimple fork with full container-interop support

13123.1k16](/packages/mnapoli-simplex)[phpwatch/simple-container

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

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

PHPackages © 2026

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