• Stars
    star
    841
  • Rank 52,021 (Top 2 %)
  • Language
    PHP
  • License
    Other
  • Created about 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Nette Dependency Injection (DI)

Downloads this Month Tests Coverage Status Latest Stable Version License

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.

Support Me

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

Buy me a coffee

Thank you!

Installation

The recommended way to install is via Composer:

composer require nette/di

It requires PHP version 8.0 and supports PHP up to 8.3.

Usage

Let's have an application for sending newsletters. The code is maximally simplified and is available on the GitHub.

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 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(['[email protected]', ...]);

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 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

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();
	}
}

More Repositories

1

php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.
PHP
1,978
star
2

utils

🛠 Lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.
PHP
1,868
star
3

tracy

😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.
PHP
1,712
star
4

nette

👪 METAPACKAGE for Nette Framework components
PHP
1,514
star
5

latte

☕ Latte: the safest & truly intuitive templates for PHP. Engine for those who want the most secure PHP sites.
PHP
1,044
star
6

finder

🔍 Finder: find files and directories with an intuitive API.
931
star
7

neon

🍸 Encodes and decodes NEON file format.
PHP
879
star
8

robot-loader

🍀 RobotLoader: high performance and comfortable autoloader that will search and autoload classes within your application.
PHP
854
star
9

schema

📐 Validating data structures against a given Schema.
PHP
811
star
10

bootstrap

🅱 The simple way to configure and bootstrap your Nette application.
PHP
654
star
11

forms

📝 Generating, validating and processing secure forms in PHP. Handy API, fully customizable, server & client side validation and mature design.
PHP
470
star
12

database

💾 A database layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.
PHP
470
star
13

mail

A handy library for creating and sending emails in PHP
PHP
448
star
14

tester

Tester: enjoyable unit testing in PHP with code coverage reporter. 🍏🍏🍎🍏
PHP
440
star
15

http

🌐 Abstraction for HTTP request, response and session. Provides careful data sanitization and utility for URL and cookies manipulation.
PHP
437
star
16

caching

⏱ Caching library with easy-to-use API and many cache backends.
PHP
390
star
17

application

🏆 A full-stack component-based MVC kernel for PHP that helps you write powerful and modern web applications. Write less, have cleaner code and your work will bring you joy.
PHP
384
star
18

security

🔑 Provides authentication, authorization and a role-based access control management via ACL (Access Control List)
PHP
338
star
19

component-model

⚛ Component model foundation for Nette.
PHP
251
star
20

routing

Nette Routing: two-ways URL conversion
PHP
220
star
21

sandbox

142
star
22

tokenizer

[DISCONTINUED] Source code tokenizer
PHP
141
star
23

safe-stream

SafeStream: atomic and safe manipulation with files via native PHP functions.
PHP
117
star
24

docs

📖 The Nette documentation
115
star
25

web-project

Standard Web Project: a simple skeleton application using the Nette
Latte
102
star
26

reflection

[DISCONTINUED] Docblock annotations parser and common reflection classes
PHP
94
star
27

examples

🎓 Examples demonstrating the Nette Framework.
88
star
28

code-checker

✅ A simple tool to check source code against a set of Nette coding standards.
PHP
85
star
29

web-addons.nette.org

[DISCONTINUED] Website https://addons.nette.org source code.
PHP
55
star
30

coding-standard

Nette Coding Standard code checker & fixer
PHP
40
star
31

command-line

⌨ Command line options and arguments parser.
PHP
37
star
32

type-fixer

🆙 A tool to automatically update typehints in your code.
PHP
29
star
33

resources

Client-side resources for Nette Framework.
23
star
34

latte-tools

Twig & HTML to Latte converters
PHP
22
star
35

grunt-nette-tester

Grunt plugin for Nette Tester
JavaScript
20
star
36

middleware

PHP
20
star
37

deprecated

[DISCONTINUED] APIs and features removed from Nette Framework
PHP
19
star
38

safe

🛡 PHP functions smarten up to throw exceptions instead of returning false or triggering errors.
PHP
17
star
39

nette-minified

[DISCONTINUED] Minified version of Nette Framework.
PHP
16
star
40

tutorial-todo

[DISCONTINUED] Tutorial for simple task manager.
PHP
10
star
41

union

[READ-ONLY] Subtree union of Nette repositories
PHP
7
star
42

assistant

PHP
3
star
43

.github

1
star