PHPackages                             nette/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. nette/di

ActiveLibrary[Framework](/categories/framework)

nette/di
========

💎 Nette Dependency Injection Container: Flexible, compiled and full-featured DIC with perfectly usable autowiring and support for all new PHP features.

v3.2.5(9mo ago)92340.6M↓17.2%75[16 issues](https://github.com/nette/di/issues)[18 PRs](https://github.com/nette/di/pulls)20BSD-3-ClausePHPPHP 8.1 - 8.5CI failing

Since May 11Pushed 1w ago36 watchersCompare

[ Source](https://github.com/nette/di)[ Packagist](https://packagist.org/packages/nette/di)[ Docs](https://nette.org)[ RSS](/packages/nette-di/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (79)Used By (20)

[![Nette Dependency Injection](https://private-user-images.githubusercontent.com/194960/331389329-d368a458-bac1-48b1-9b4b-7929f4bb2f98.jpg?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzkxNzAyODUsIm5iZiI6MTc3OTE2OTk4NSwicGF0aCI6Ii8xOTQ5NjAvMzMxMzg5MzI5LWQzNjhhNDU4LWJhYzEtNDhiMS05YjRiLTc5MjlmNGJiMmY5OC5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYwNTE5JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MDUxOVQwNTUzMDVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1hYmJhMWQxYzFiODBjZDY2NzdhODMzNmE1NzhkYTkxZmFhNjlkZGY1MGU3NGI1ZDQ3OWQ2NjgwNDhlMGVkZTU0JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZyZXNwb25zZS1jb250ZW50LXR5cGU9aW1hZ2UlMkZqcGVnIn0.vRt0-CMUAwoh4EPQx18b4O7y9uaem2Xh3xApqKW-Wcc)](https://doc.nette.org/dependency-injection)

[![Downloads this Month](https://camo.githubusercontent.com/0c90bbf42ac891d6b11fef2c92429290516000b0c5ddb2d5159b497d62c7b4fe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6e657474652f64692e737667)](https://packagist.org/packages/nette/di)[![Tests](https://github.com/nette/di/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/di/actions)[![Coverage Status](https://camo.githubusercontent.com/c31d73ed66c05ded7d159bd6ad7f0b9e49faac60cf52a72651f915df0aaa56e5/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6e657474652f64692f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/nette/di?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/f82e48bd79d00609a53f8ad0f70a48c98e16a0fc97f398ba96683e165d5e98ef/68747470733a2f2f706f7365722e707567782e6f72672f6e657474652f64692f762f737461626c65)](https://github.com/nette/di/releases)[![License](https://camo.githubusercontent.com/fa7d5fcf2c84b580327af52da95dd751703af65f079dc3c5a0081beac0789718/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4e65772532304253442d626c75652e737667)](https://github.com/nette/di/blob/master/license.md)

Introduction
------------

[](#introduction)

Purpose of the Dependecy Injection (DI) is to free classes from the responsibility for obtaining objects that they need for its operation (these objects are called **services**). To pass them these services on their instantiation instead.

Nette DI is one of the most interesting part of framework. It is compiled DI container, extremely fast and easy to configure.

Documentation can be found on the [website](https://doc.nette.org/dependency-injection).

[Support Me](https://github.com/sponsors/dg)
--------------------------------------------

[](#support-me)

Do you like Nette DI? Are you looking forward to the new features?

[![Buy me a coffee](https://camo.githubusercontent.com/afa7c20ccaac10ac4f1f51669bafb212856b932e0c8b276cb290336cf08624b8/68747470733a2f2f66696c65732e6e657474652e6f72672f69636f6e732f646f6e6174696f6e2d332e737667)](https://github.com/sponsors/dg)

Thank you!

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

[](#installation)

The recommended way to install is via Composer:

```
composer require nette/di

```

It requires PHP version 8.2 and supports PHP up to 8.5.

Usage
-----

[](#usage)

Let's have an application for sending newsletters. The code is maximally simplified and is available on the [GitHub](https://github.com/dg/di-example).

We have the object representing email:

```
class Mail
{
	public string $subject;
	public string $message;
}
```

An object which can send emails:

```
interface Mailer
{
	function send(Mail $mail, string $to): void;
}
```

A support for logging:

```
interface Logger
{
	function log(string $message): void;
}
```

And finally, a class that provides sending newsletters:

```
class NewsletterManager
{
	private Mailer $mailer;
	private Logger $logger;

	public function __construct(Mailer $mailer, Logger $logger)
	{
		$this->mailer = $mailer;
		$this->logger = $logger;
	}

	public function distribute(array $recipients): void
	{
		$mail = new Mail;
		$mail->subject = '...';
		$mail->message = '...';

		foreach ($recipients as $recipient) {
			$this->mailer->send($mail, $recipient);
		}
		$this->logger->log('...');
	}
}
```

The code respects Dependency Injection, ie. **each object uses only variables which we had passed into it.**

Also, we have a ability to implement own `Logger` or `Mailer`, like this:

```
class SendMailMailer implements Mailer
{
	public function send(Mail $mail, string $to): void
	{
		mail($to, $mail->subject, $mail->message);
	}
}

class FileLogger implements Logger
{
	private string $file;

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

	public function log(string $message): void
	{
		file_put_contents($this->file, $message . "\n", FILE_APPEND);
	}
}
```

**DI container is the supreme architect** which can create individual objects (in the terminology DI called services) and assemble and configure them exactly according to our needs.

Container for our application might look like this:

```
class Container
{
	private ?Logger $logger;
	private ?Mailer $mailer;

	public function getLogger(): Logger
	{
		if (!isset($this->logger)) {
			$this->logger = new FileLogger('log.txt');
		}
		return $this->logger;
	}

	public function getMailer(): Mailer
	{
		if (!isset($this->mailer)) {
			$this->mailer = new SendMailMailer;
		}
		return $this->mailer;
	}

	public function createNewsletterManager(): NewsletterManager
	{
		return new NewsletterManager($this->getMailer(), $this->getLogger());
	}
}
```

The implementation looks like this because:

- the individual services are created only on demand (lazy loading)
- doubly called `createNewsletterManager` will use the same logger and mailer instances

Let's instantiate `Container`, let it create manager and we can start spamming users with newsletters :-)

```
$container = new Container;
$manager = $container->createNewsletterManager();
$manager->distribute(...);
```

Significant to Dependency Injection is that no class depends on the container. Thus it can be easily replaced with another one. For example with the container generated by Nette DI.

Nette DI
--------

[](#nette-di)

Nette DI is the generator of containers. We instruct it (usually) with configuration files. This is configuration that leads to generate nearly the same class as the class `Container` above:

```
services:
	- FileLogger( log.txt )
	- SendMailMailer
	- NewsletterManager
```

The big advantage is the shortness of configuration.

Nette DI actually generates PHP code of container. Therefore it is extremely fast. Developer can see the code, so he knows exactly what it is doing. He can even trace it.

Usage of Nette DI is very easy. Save the (above) configuration to the file `config.neon` and let's create a container:

```
$loader = new Nette\DI\ContainerLoader(__DIR__ . '/temp');
$class = $loader->load(function($compiler) {
    $compiler->loadConfig(__DIR__ . '/config.neon');
});
$container = new $class;
```

and then use container to create object `NewsletterManager` and we can send e-mails:

```
$manager = $container->getByType(NewsletterManager::class);
$manager->distribute(['john@example.com', ...]);
```

The container will be generated only once and the code is stored in cache (in directory `__DIR__ . '/temp'`). Therefore the loading of configuration file is placed in the closure in `$loader->load()`, so it is called only once.

During development it is useful to activate auto-refresh mode which automatically regenerate the container when any class or configuration file is changed. Just in the constructor `ContainerLoader` append `true` as the second argument:

```
$loader = new Nette\DI\ContainerLoader(__DIR__ . '/temp', autoRebuild: true);
```

Services
--------

[](#services)

Services are registered in the DI container and their dependencies are automatically passed.

```
services:
	manager: NewsletterManager
```

All dependencies declared in the constructor of this service will be automatically passed. Constructor passing is the preferred way of dependency injection for services.

If we want to pass dependencies by the setter, we can add the `setup` section to the service definition:

```
services:
	manager:
		factory: NewsletterManager
		setup:
			- setAnotherService
```

Class of the service:

```
class NewsletterManager
{
	private AnotherService $anotherService;

	public function setAnotherService(AnotherService $service): void
	{
		$this->anotherService = $service;
	}

...
```

We can also add the `inject: yes` directive. This directive will enable automatic call of `inject*` methods and passing dependencies to public variables with #\[Inject\] attribute:

```
services:
	foo:
		factory: FooClass
		inject: yes
```

Dependency `Service1` will be passed by calling the `inject*` method, dependency `Service2` will be assigned to the `$service2` variable:

```
use Nette\DI\Attributes\Inject;

class FooClass
{
	private Service1 $service1;

	// 1) inject* method:

	public function injectService1(Service1 $service): void
	{
		$this->service1 = $service1;
	}

	// 2) Assign to the variable with the #[Inject] attribute:

	#[Inject]
	public Service2 $service2;
}
```

However, this method is not ideal, because the variable must be declared as public and there is no way how you can ensure that the passed object will be of the given type. We also lose the ability to handle the assigned dependency in our code and we violate the principles of encapsulation.

Factories
---------

[](#factories)

We can use factories generated from an interface. The interface must declare the returning type of the method. Nette will generate a proper implementation of the interface.

The interface must have exactly one method named `create`. Our factory interface could be declared in the following way:

```
interface BarFactory
{
	function create(): Bar;
}
```

The `create` method will instantiate an `Bar` with the following definition:

```
class Bar
{
	private Logger $logger;

	public function __construct(Logger $logger)
	{
		$this->logger = $logger;
	}
}
```

The factory will be registered in the `config.neon` file:

```
services:
	- BarFactory
```

Nette will check if the declared service is an interface. If yes, it will also generate the corresponding implementation of the factory. The definition can be also written in a more verbose form:

```
services:
	barFactory:
		implement: BarFactory
```

This full definition allows us to declare additional configuration of the object using the `arguments` and `setup` sections, similarly as for all other services.

In our code, we only have to obtain the factory instance and call the `create` method:

```
class Foo
{
	private BarFactory $barFactory;

	function __construct(BarFactory $barFactory)
	{
		$this->barFactory = $barFactory;
	}

	function bar(): void
	{
		$bar = $this->barFactory->create();
	}
}
```

###  Health Score

79

—

ExcellentBetter than 100% of packages

Maintenance80

Actively maintained with recent releases

Popularity72

Solid adoption and visibility

Community58

Growing community involvement

Maturity96

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 92.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 ~56 days

Recently: every ~130 days

Total

77

Last Release

71d ago

Major Versions

v2.4.15 → v3.0.02019-04-03

v2.4.16 → v3.0.22019-12-17

v2.4.17 → v3.0.62020-11-25

v2.4.x-dev → v3.0.82021-03-02

PHP version history (13 changes)v2.2.0PHP &gt;=5.3.1

v2.4.0PHP &gt;=5.6.0

v3.0.0PHP &gt;=7.1

v2.4.17PHP &gt;=5.6 &lt;8.1

v3.0.6PHP &gt;=7.1 &lt;8.1

v3.0.9PHP &gt;=7.1 &lt;8.2

v3.0.14PHP &gt;=7.1 &lt;8.3

v3.1.0PHP &gt;=7.2 &lt;8.3

v3.1.3PHP 7.2 - 8.3

v3.2.0PHP 8.1 - 8.3

v3.2.3PHP 8.1 - 8.4

v3.2.5PHP 8.1 - 8.5

v3.3.x-devPHP 8.2 - 8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/17f266513a3ca97500ec3d85d562b9279c7a6346358fe2b8d90390ece717a027?d=identicon)[david@grudl.com](/maintainers/david@grudl.com)

---

Top Contributors

[![dg](https://avatars.githubusercontent.com/u/194960?v=4)](https://github.com/dg "dg (1229 commits)")[![fprochazka](https://avatars.githubusercontent.com/u/158625?v=4)](https://github.com/fprochazka "fprochazka (16 commits)")[![matej21](https://avatars.githubusercontent.com/u/1276059?v=4)](https://github.com/matej21 "matej21 (13 commits)")[![JanTvrdik](https://avatars.githubusercontent.com/u/175109?v=4)](https://github.com/JanTvrdik "JanTvrdik (10 commits)")[![enumag](https://avatars.githubusercontent.com/u/539462?v=4)](https://github.com/enumag "enumag (9 commits)")[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (5 commits)")[![Vrtak-CZ](https://avatars.githubusercontent.com/u/112567?v=4)](https://github.com/Vrtak-CZ "Vrtak-CZ (5 commits)")[![milo](https://avatars.githubusercontent.com/u/439140?v=4)](https://github.com/milo "milo (5 commits)")[![hrach](https://avatars.githubusercontent.com/u/284263?v=4)](https://github.com/hrach "hrach (5 commits)")[![lookyman](https://avatars.githubusercontent.com/u/3863468?v=4)](https://github.com/lookyman "lookyman (4 commits)")[![pavelkouril](https://avatars.githubusercontent.com/u/636912?v=4)](https://github.com/pavelkouril "pavelkouril (4 commits)")[![kravco](https://avatars.githubusercontent.com/u/115938?v=4)](https://github.com/kravco "kravco (3 commits)")[![xificurk](https://avatars.githubusercontent.com/u/117465?v=4)](https://github.com/xificurk "xificurk (3 commits)")[![Majkl578](https://avatars.githubusercontent.com/u/144181?v=4)](https://github.com/Majkl578 "Majkl578 (2 commits)")[![kukulich](https://avatars.githubusercontent.com/u/260445?v=4)](https://github.com/kukulich "kukulich (2 commits)")[![adaamz](https://avatars.githubusercontent.com/u/4347332?v=4)](https://github.com/adaamz "adaamz (2 commits)")[![sallyx](https://avatars.githubusercontent.com/u/4263901?v=4)](https://github.com/sallyx "sallyx (2 commits)")[![vojtech-dobes](https://avatars.githubusercontent.com/u/415925?v=4)](https://github.com/vojtech-dobes "vojtech-dobes (2 commits)")[![vrana](https://avatars.githubusercontent.com/u/117453?v=4)](https://github.com/vrana "vrana (2 commits)")[![ondrahb](https://avatars.githubusercontent.com/u/22585932?v=4)](https://github.com/ondrahb "ondrahb (1 commits)")

---

Tags

dependency-injectiondependency-injection-containerdi-containerfactoriesnettenette-frameworkphpfactorynettediiocdicstaticcompiled

### Embed Badge

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

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

###  Alternatives

[rdlowrey/auryn

Auryn is a dependency injector for bootstrapping object-oriented PHP applications.

7262.2M76](/packages/rdlowrey-auryn)[kdyby/autowired

Syntax sugar for working with services in Nette Framework

30885.7k9](/packages/kdyby-autowired)[nette/web-project

Nette: Standard Web Project

10991.8k](/packages/nette-web-project)[mouf/mouf

The Mouf PHP framework: an open-source PHP framework providing an easy way to download, install, use and reuse components, with a graphical user interface.

55146.0k17](/packages/mouf-mouf)[nasext/dependent-select-box

Dependent Select Box for Nette Framework.

21262.8k2](/packages/nasext-dependent-select-box)[joomla/di

Joomla DI Package

15391.2k11](/packages/joomla-di)

PHPackages © 2026

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