PHPackages                             anax/di - 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. [Framework](/categories/framework)
4. /
5. anax/di

ActiveLibrary[Framework](/categories/framework)

anax/di
=======

Anax DI module, dependency injection (PHP-FIG PSR-11).

v2.0.4(7y ago)020.8k↓90%20MITPHPPHP ^7.2

Since Jun 29Pushed 7y ago1 watchersCompare

[ Source](https://github.com/canax/di)[ Packagist](https://packagist.org/packages/anax/di)[ Docs](https://dbwebb.se/anax)[ RSS](/packages/anax-di/feed)WikiDiscussions master Synced 3w ago

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

Anax DI
=======

[](#anax-di)

[![Join the chat at https://gitter.im/canax/di](https://camo.githubusercontent.com/c095b5f8b50d1d1b66fff067d33441c8b3286f9e956344e75d4fd34c1a965787/68747470733a2f2f6261646765732e6769747465722e696d2f63616e61782f64692e737667)](https://gitter.im/canax/di?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)[![Latest Stable Version](https://camo.githubusercontent.com/781787f517361053afbf67967c14d41c1e366c60e8b6f64d881f8ffdbfa10d93/68747470733a2f2f706f7365722e707567782e6f72672f616e61782f64692f762f737461626c65)](https://packagist.org/packages/anax/di)

[![Build Status](https://camo.githubusercontent.com/1793c9daf394b327f6fc02b595f01af65dc1e6dd3a5f707217106ab9213c450e/68747470733a2f2f7472617669732d63692e6f72672f63616e61782f64692e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/canax/di)[![CircleCI](https://camo.githubusercontent.com/6a041ec4c239f0d815b238665169d83d984c42543ab2a8e8f0838eb9a6a77598/68747470733a2f2f636972636c6563692e636f6d2f67682f63616e61782f64692e7376673f7374796c653d737667)](https://circleci.com/gh/canax/di)

[![Build Status](https://camo.githubusercontent.com/308fa9b11ef86e389e49cc70602f5daa14b45304ee66ac1f8d3a6090cc18eeb8/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f63616e61782f64692f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/canax/di/build-status/master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/e915d9045b96fc8257e38ccf015d226e5b5f7a212d3d9dbcee5cdb02dc5c3ae4/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f63616e61782f64692f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/canax/di/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/173b5cd6dad96be6260c7515b3289939fe805be53ae9dbcaae5116fb72d82a3f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f63616e61782f64692f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/canax/di/?branch=master)

[![Maintainability](https://camo.githubusercontent.com/9dad7d9aef8704b91f226a2f51a88b1c2e8e96da8fd4d827ce374d41ffc59f71/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f66663938346230336337653034323166356661612f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/canax/di/maintainability)[![Codacy Badge](https://camo.githubusercontent.com/81e5607227c93cb07b9b3bd3add1ccdd4b26fb9d7d2b16a5afcc3331b24ca189/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f6334383032656466376366353439356539626538646662643563313136636231)](https://www.codacy.com/app/mosbth/di?utm_source=github.com&utm_medium=referral&utm_content=canax/di&utm_campaign=Badge_Grade)

Anax DI service container for dependency injection of framework services using creation and lazy loading of services.

The implementation of the container is compliant with [PHP-FIG PSR-11: Container interface](https://www.php-fig.org/psr/psr-11/)

Table of content
----------------

[](#table-of-content)

- [Install](#install)
- [Development](#development)
- [Basic usage](#basic-usage)
- [Shared service](#shared-service)
- [Lazy loading](#lazy-loading)
- [Usage in Anax](#usage-in-anax)
- [Anax initialization of services](#Anax-initialization-of-services)
- [Anax configuration of services](#Anax-configuration-of-services)
- [Dependency](#Dependency)
- [License](#License)

You can also read this [documentation online](https://canax.github.io/di/).

Install
-------

[](#install)

You can install the module from [`anax/di` on Packagist](https://packagist.org/packages/anax/di) using composer.

```
composer require anax/di

```

Development
-----------

[](#development)

To work as a developer you clone the repo and install the local environment through make. Then you can run the unit tests.

```
make install
make test

```

Basic usage
-----------

[](#basic-usage)

This is the basic usage of the container.

First you create the container.

```
// Create it
$di = new \Anax\DI\DI();

// Check its a PSR-11 interface
assert($di instanceof \Psr\Container\ContainerInterface);
```

Add services onto the container.

```
// Add a service
$di->set("response", "\Anax\Response\Response");

// Add a shared service
$di->setShared("view", "\Anax\View\ViewContainer");
```

Check if the service is loaded.

```
// Check if service is loaded
if ($di->has("view")) {
    ; // the service is loaded
}
```

Get and use the service.

```
// Get and use a service
$response = $di->get("response");
$response->addBody($body)->send();

// Same, without storing in a variable
$di->get("response")->addBody($body)->send();
```

Shared service
--------------

[](#shared-service)

A shared service always return the same object. The object is instantiated once and then stored for the next wanting to use the service. There is only one instance af a shared service. The service is shared among all its users.

```
// Add a shared service
$di->setShared("view", "\Anax\View\ViewContainer");

// Get two instances of the shared service
$view1 = $di->get("view");
$view2 = $di->get("view");
assert($view1 === $view2);
```

A service that is not shared will return a new instance each time it is get from the container.

```
// Add a service
$di->set("response", "\Anax\Response\Response");

// Get two instances of the service
$response1 = $di->get("response");
$response2 = $di->get("response");
assert($response1 !== $response2);
```

Lazy loading
------------

[](#lazy-loading)

The services added to the container are not activated until accessed. They are lazy loaded to ensure they are only active when used.

You can see what services are loaded onto the container and you can see what services are activated.

```
// Add services
$di->set("response", "\Anax\Response\Response");
$di->setShared("view", "\Anax\View\ViewContainer");

// Get one service
$response = $di->get("response");

// Check what services are loaded
implode(",", $di->getServices()); // response,view

// Check what services are active
implode(",", $di->getActiveServices()); // response
```

Usage in Anax
-------------

[](#usage-in-anax)

In Anax all services are loaded during the bootstrap phase in the file `htdocs/index.php`. It looks like this.

```
// Add all framework services to $di
$di = new Anax\DI\DIFactoryConfig();
$di->loadServices(ANAX_INSTALL_PATH . "/config/di");
```

The variable `$di` is the only global variable within the framework. The main dependency, as a global variable, is to the be accessable within the view template files and view helpers.

Anax initialization of services
-------------------------------

[](#anax-initialization-of-services)

All the framework services are loaded from files in the directory `ANAX_INSTALL_PATH . "/config/di"`. Each file contains one service. A file can contain several services.

This is a example of a service configuration file for the service "request".

```
/**
 * Configuration file for request service.
 */
return [
    // Services to add to the container.
    "services" => [
        "request" => [
            "shared" => true,
            "callback" => function () {
                $obj = new \Anax\Request\Request();
                $obj->init();
                return $obj;
            }
        ],
    ],
];
```

A service may contain a callback that initiates the service when it is loaded. The callback should return the initiated object.

The service can be defined through its class name when the service needs no extra initialisation.

```
"callback" => "\Anax\Request\Request",
```

One common way to initialize the service is to inject `$di` into the service. This is an example of that.

```
"response" => [
    "shared" => true,
    //"callback" => "\Anax\Response\Response",
    "callback" => function () {
        $obj = new \Anax\Response\ResponseUtility();
        $obj->setDI($this);
        return $obj;
    }
],
```

Anax configuration of services
------------------------------

[](#anax-configuration-of-services)

During the initialization phase some services might want to read additional configuration information. They can do so by using `anax/configuration`, like this.

First, lets have a look at the service "configuration".

```
"configuration" => [
    "shared" => true,
    "callback" => function () {
        $config = new \Anax\Configure\Configuration();
        $dirs = require ANAX_INSTALL_PATH . "/config/configuration.php";
        $config->setBaseDirectories($dirs);
        return $config;
    }
],
```

It is a service to read configuration files from those directories that the framework specifies. It can be used like this, when creating other services that depends on their own configuration files.

```
"session" => [
    "active" => defined("ANAX_WITH_SESSION") && ANAX_WITH_SESSION, // true|false
    "shared" => true,
    "callback" => function () {
        $session = new \Anax\Session\Session();

        // Load the configuration files
        $cfg = $this->get("configuration");
        $config = $cfg->load("session");

        // Set various settings in the $session
        // ...

        return $session;
    }
],
```

The configuration setting "active" states wether the service should be activated when its loaded, or if it should be lazy loaded.

In the callback, first the service "configuration" is retrieved from $di. Then it is used to read the configuration file named "session".

The actual configuration is returned from the configuration file "session" and can then be used to configure and setup the object, before returning it as a framework service.

A configuration file is in general stored by its service name in `ANAX_INSTALL_PATH . "/config/servicename.php"`. It should return something, like this.

```
/**
 * Config-file for sessions.
 */
return [
    // Session name
    "name" => preg_replace("/[^a-z\d]/i", "", __DIR__),
];
```

Dependency
----------

[](#dependency)

Using psr11 through `psr/container`.

License
-------

[](#license)

This software carries a MIT license. See [LICENSE.txt](LICENSE.txt) for details.

```
 .
..:  Copyright (c) 2013 - 2018 Mikael Roos, mos@dbwebb.se

```

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity68

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

Recently: every ~0 days

Total

25

Last Release

2776d ago

Major Versions

v1.0.10 → v2.0.0-alpha.12018-08-01

PHP version history (3 changes)v1.0.0PHP &gt;=5.6

v2.0.0-alpha.2PHP ~7.2

v2.0.0-alpha.8PHP ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/4cac244120f54c02a4fb3186b91323f3f0805dd9daefd0babeb4a82a19232faf?d=identicon)[mikael\_roos](/maintainers/mikael_roos)

---

Top Contributors

[![mosbth](https://avatars.githubusercontent.com/u/169550?v=4)](https://github.com/mosbth "mosbth (57 commits)")

---

Tags

frameworkmicromvcboilerplateeducation

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

PHPackages © 2026

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