PHPackages                             pimple/pimple - 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. pimple/pimple

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

pimple/pimple
=============

Pimple, a simple Dependency Injection Container

v3.6.2(2mo ago)2.7k130.5M—2.7%30320MITPHPPHP &gt;=7.2.5CI passing

Since May 8Pushed 2mo ago96 watchersCompare

[ Source](https://github.com/silexphp/Pimple)[ Packagist](https://packagist.org/packages/pimple/pimple)[ Docs](https://pimple.symfony.com)[ RSS](/packages/pimple-pimple/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (26)Used By (20)

Pimple
======

[](#pimple)

Caution!

Pimple is now closed for changes. No new features will be added and no cosmetic changes will be accepted either. The only accepted changes are compatibility with newer PHP versions and security issue fixes.

Caution!

This is the documentation for Pimple 3.x. If you are using Pimple 1.x, read the [Pimple 1.x documentation](https://github.com/silexphp/Pimple/tree/1.1). Reading the Pimple 1.x code is also a good way to learn more about how to create a simple Dependency Injection Container (recent versions of Pimple are more focused on performance).

Pimple is a small Dependency Injection Container for PHP.

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

[](#installation)

Before using Pimple in your project, add it to your `composer.json` file:

```
$ ./composer.phar require pimple/pimple "^3.0"
```

Usage
-----

[](#usage)

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

```
use Pimple\Container;

$container = new Container();
```

As many other dependency injection containers, Pimple manages two different kind of data: **services** and **parameters**.

### Defining Services

[](#defining-services)

A service 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:

```
// define some services
$container['session_storage'] = fn($c) => new SessionStorage('SESSION_ID');

$container['session'] = fn($c) => new Session($c['session_storage']);
```

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:

```
// get the session object
$session = $container['session'];

// the above call is roughly equivalent to the following code:
// $storage = new SessionStorage('SESSION_ID');
// $session = new Session($storage);
```

### Defining Factory Services

[](#defining-factory-services)

By default, each time you get a service, Pimple 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['session'] = $container->factory(fn($c) => new Session($c['session_storage']));
```

Now, each call to `$container['session']` returns a new instance of the session.

### Defining Parameters

[](#defining-parameters)

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

```
// define some parameters
$container['cookie_name'] = 'SESSION_ID';
$container['session_storage_class'] = 'SessionStorage';
```

If you change the `session_storage` service definition like below:

```
$container['session_storage'] = fn($c) => new $c['session_storage_class']($c['cookie_name']);
```

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

### Protecting Parameters

[](#protecting-parameters)

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

```
$container['random_func'] = $container->protect(fn() => rand());
```

### 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['session_storage'] = fn($c) => new $c['session_storage_class']($c['cookie_name']);

$container->extend('session_storage', function ($storage, $c) {
    $storage->...();

    return $storage;
});
```

The first argument is the name of the service to extend, the second a function that gets access to the object instance and the container.

### Extending a Container

[](#extending-a-container)

If you use the same libraries over and over, you might want to reuse some services from one project to the next one; package your services into a **provider** by implementing `Pimple\ServiceProviderInterface`:

```
use Pimple\Container;

class FooProvider implements Pimple\ServiceProviderInterface
{
    public function register(Container $pimple)
    {
        // register some services and parameters
        // on $pimple
    }
}
```

Then, register the provider on a Container:

```
$pimple->register(new FooProvider());
```

### Fetching the Service Creation Function

[](#fetching-the-service-creation-function)

When you access an object, Pimple automatically calls the anonymous function that you defined, which creates the service object for you. If you want to get raw access to this function, you can use the `raw()` method:

```
$container['session'] = fn($c) => new Session($c['session_storage']);

$sessionFunction = $container->raw('session');
```

PSR-11 compatibility
--------------------

[](#psr-11-compatibility)

For historical reasons, the `Container` class does not implement the PSR-11 `ContainerInterface`. However, Pimple provides a helper class that will let you decouple your code from the Pimple container class.

### The PSR-11 container class

[](#the-psr-11-container-class)

The `Pimple\Psr11\Container` class lets you access the content of an underlying Pimple container using `Psr\Container\ContainerInterface`methods:

```
use Pimple\Container;
use Pimple\Psr11\Container as PsrContainer;

$container = new Container();
$container['service'] = fn($c) => new Service();
$psr11 = new PsrContainer($container);

$controller = function (PsrContainer $container) {
    $service = $container->get('service');
};
$controller($psr11);
```

### Using the PSR-11 ServiceLocator

[](#using-the-psr-11-servicelocator)

Sometimes, a service needs access to several other services without being sure that all of them will actually be used. In those cases, you may want the instantiation of the services to be lazy.

The traditional solution is to inject the entire service container to get only the services really needed. However, this is not recommended because it gives services a too broad access to the rest of the application and it hides their actual dependencies.

The `ServiceLocator` is intended to solve this problem by giving access to a set of predefined services while instantiating them only when actually needed.

It also allows you to make your services available under a different name than the one used to register them. For instance, you may want to use an object that expects an instance of `EventDispatcherInterface` to be available under the name `event_dispatcher` while your event dispatcher has been registered under the name `dispatcher`:

```
use Monolog\Logger;
use Pimple\Psr11\ServiceLocator;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

class MyService
{
    /**
     * "logger" must be an instance of Psr\Log\LoggerInterface
     * "event_dispatcher" must be an instance of Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    private $services;

    public function __construct(ContainerInterface $services)
    {
        $this->services = $services;
    }
}

$container['logger'] = fn($c) => new Monolog\Logger();
$container['dispatcher'] = fn($c) => new EventDispatcher();

$container['service'] = function ($c) {
    $locator = new ServiceLocator($c, array('logger', 'event_dispatcher' => 'dispatcher'));

    return new MyService($locator);
};
```

### Referencing a Collection of Services Lazily

[](#referencing-a-collection-of-services-lazily)

Passing a collection of services instances in an array may prove inefficient if the class that consumes the collection only needs to iterate over it at a later stage, when one of its method is called. It can also lead to problems if there is a circular dependency between one of the services stored in the collection and the class that consumes it.

The `ServiceIterator` class helps you solve these issues. It receives a list of service names during instantiation and will retrieve the services when iterated over:

```
use Pimple\Container;
use Pimple\ServiceIterator;

class AuthorizationService
{
    private $voters;

    public function __construct($voters)
    {
        $this->voters = $voters;
    }

    public function canAccess($resource)
    {
        foreach ($this->voters as $voter) {
            if (true === $voter->canAccess($resource)) {
                return true;
            }
        }

        return false;
    }
}

$container = new Container();

$container['voter1'] = fn($c) => new SomeVoter();
$container['voter2'] = fn($c) => new SomeOtherVoter($c['auth']);
$container['auth'] = fn ($c) => new AuthorizationService(new ServiceIterator($c, array('voter1', 'voter2'));
```

###  Health Score

75

—

ExcellentBetter than 100% of packages

Maintenance84

Actively maintained with recent releases

Popularity81

Widely adopted with strong download metrics

Community62

Healthy contributor diversity

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 73.1% 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 ~219 days

Recently: every ~454 days

Total

24

Last Release

82d ago

Major Versions

v1.1.1 → v2.0.02014-02-10

v2.1.1 → v3.0.02014-07-24

1.1.x-dev → v3.1.02017-07-03

PHP version history (3 changes)1.0.0PHP &gt;=5.3.0

v3.3.0PHP ^7.2.5

v3.3.1PHP &gt;=7.2.5

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/47313?v=4)[Fabien Potencier](/maintainers/fabpot)[@fabpot](https://github.com/fabpot)

---

Top Contributors

[![fabpot](https://avatars.githubusercontent.com/u/47313?v=4)](https://github.com/fabpot "fabpot (207 commits)")[![igorw](https://avatars.githubusercontent.com/u/88061?v=4)](https://github.com/igorw "igorw (15 commits)")[![skalpa](https://avatars.githubusercontent.com/u/4943191?v=4)](https://github.com/skalpa "skalpa (9 commits)")[![lyrixx](https://avatars.githubusercontent.com/u/408368?v=4)](https://github.com/lyrixx "lyrixx (5 commits)")[![davedevelopment](https://avatars.githubusercontent.com/u/61351?v=4)](https://github.com/davedevelopment "davedevelopment (4 commits)")[![stof](https://avatars.githubusercontent.com/u/439401?v=4)](https://github.com/stof "stof (4 commits)")[![whatthejeff](https://avatars.githubusercontent.com/u/306525?v=4)](https://github.com/whatthejeff "whatthejeff (4 commits)")[![derrabus](https://avatars.githubusercontent.com/u/1506493?v=4)](https://github.com/derrabus "derrabus (3 commits)")[![glensc](https://avatars.githubusercontent.com/u/199095?v=4)](https://github.com/glensc "glensc (3 commits)")[![mtdowling](https://avatars.githubusercontent.com/u/190930?v=4)](https://github.com/mtdowling "mtdowling (3 commits)")[![wouterj](https://avatars.githubusercontent.com/u/749025?v=4)](https://github.com/wouterj "wouterj (2 commits)")[![GromNaN](https://avatars.githubusercontent.com/u/400034?v=4)](https://github.com/GromNaN "GromNaN (2 commits)")[![chris-kruining](https://avatars.githubusercontent.com/u/5786905?v=4)](https://github.com/chris-kruining "chris-kruining (2 commits)")[![reedy](https://avatars.githubusercontent.com/u/67615?v=4)](https://github.com/reedy "reedy (2 commits)")[![gigr](https://avatars.githubusercontent.com/u/4009793?v=4)](https://github.com/gigr "gigr (2 commits)")[![dominikzogg](https://avatars.githubusercontent.com/u/1011217?v=4)](https://github.com/dominikzogg "dominikzogg (2 commits)")[![kix](https://avatars.githubusercontent.com/u/345754?v=4)](https://github.com/kix "kix (1 commits)")[![arduanov](https://avatars.githubusercontent.com/u/8693029?v=4)](https://github.com/arduanov "arduanov (1 commits)")[![cordoval](https://avatars.githubusercontent.com/u/328359?v=4)](https://github.com/cordoval "cordoval (1 commits)")[![h4cc](https://avatars.githubusercontent.com/u/2981491?v=4)](https://github.com/h4cc "h4cc (1 commits)")

---

Tags

dependency-injectionphppimplesilexcontainerdependency-injection

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[php-di/php-di

The dependency injection container for humans

2.8k48.9M994](/packages/php-di-php-di)[aura/di

A serializable dependency injection container with constructor and setter injection, interface and trait awareness, configuration inheritance, and much more.

356968.3k58](/packages/aura-di)[acclimate/container

Provides adapters for various third-party service containers.

219390.6k15](/packages/acclimate-container)[mrclay/props-dic

Props is a simple DI container that allows retrieving values via custom property and method names

3611.7M3](/packages/mrclay-props-dic)[slince/di

A flexible dependency injection container

20260.4k6](/packages/slince-di)[capsule/di

A PSR-11 compliant autowiring dependency injection container.

2857.5k2](/packages/capsule-di)

PHPackages © 2026

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