Skip to content

Commit

Permalink
readme.md: completely rewritten
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jun 10, 2015
1 parent 72bc3f0 commit 912f91c
Showing 1 changed file with 301 additions and 34 deletions.
335 changes: 301 additions & 34 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,77 +1,344 @@
Nette Dependency Injection
==========================
Nette Dependency Injection (DI)
===============================

[![Downloads this Month](https://img.shields.io/packagist/dm/nette/di.svg)](https://packagist.org/packages/nette/di)
[![Build Status](https://travis-ci.org/nette/di.svg?branch=master)](https://travis-ci.org/nette/di)

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.

Class `Nette\DI\Container` is a flexible implementation of the universal DI container. It ensures automatically, that instance of services are created only once.
Nette DI is one of the most interesting part of framework. It is compiled DI container, extremely fast and easy to configure.

Names of factory methods follow an uniform convention, they consist of the prefix `createService` + name of the service starting with first letter upper-cased. If they are not supposed to be accesible from outside, it is possible to lower their visibility to `protected`. Note that the container has already defined the field `$parameters` for user parameters.
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:

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

An object which can send emails:

```php
interface Mailer
{
function send(Mail $mail, $to);
}
```

A support for logging:

```php
interface Logger
{
function log($message);
}
```

And finally, a class that provides sending newsletters:

```php
class NewsletterManager
{
private $mailer;
private $logger;

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

function distribute(array $recipients)
{
$mail = new Mail;
...
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:

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

class FileLogger implements Logger
{
private $file;

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

function log($message)
{
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:

```php
class MyContainer extends Nette\DI\Container
class Container
{
private $logger;
private $mailer;

protected function createServiceConnection()
function getLogger()
{
return new Nette\Database\Connection(
$this->parameters['dsn'],
$this->parameters['user'],
$this->parameters['password']
);
if (!$this->logger) {
$this->logger = new FileLogger('log.txt');
}
return $this->logger;
}

protected function createServiceArticle()
function getMailer()
{
return new Article($this->connection);
if (!$this->mailer) {
$this->mailer = new SendMailMailer;
}
return $this->mailer;
}

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

Now we create an instance of the container and pass parameters:
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 :-)

```php
$container = new MyContainer(array(
'dsn' => 'mysql:',
'user' => 'root',
'password' => '***',
));
$container = new Container;
$manager = $container->createNewsletterManager();
$manager->distribute(...);
```

We get the service by calling the `getService` method or by a shortcut:
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:

```neon
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. In first, install it using Composer:

```
composer require nette/di
```

Save the (above) configuration to the file `config.neon` and let's create a container:

```php
$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:

```php
$article = $container->getService('article');
$manager = $container->getByType('NewsletterManager');
$manager->distribute(['[email protected]', ...]);
```

As have been said, all services are created in one container only once, but it would be more useful, if the container was creating always a new instance of `Article`. It could be achieved easily: Instead of the factory for the service `article` we'll create an ordinary method `createArticle`:
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:

```php
class MyContainer extends Nette\DI\Container
$loader = new Nette\DI\ContainerLoader(__DIR__ . '/temp', TRUE);
```


Services
--------

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

```neon
services:
service1: App\Service1
```

All dependencies declared in the constructor of this service will be automatically passed:

```php
namespace App;

class Service1
{
private $anotherService;

function createServiceConnection()
public function __construct(AnotherService $service)
{
return new Nette\Database\Connection(
$this->parameters['dsn'],
$this->parameters['user'],
$this->parameters['password']
);
$this->anotherService = $service;
}
}
```

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:

```neon
services:
service2:
class: App\Service2
setup:
- setAnotherService
```

Class of the service:

```php
namespace App;

function createArticle()
class Service2
{
private $anotherService;

public function setAnotherService(AnotherService $service)
{
return new Article($this->connection);
$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` annotations:

```neon
services:
service3:
class: App\Service3
inject: yes
```

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

```php
namespace App;

class Service3
{
// 1) inject* method:
private $service1;

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

// 2) Assign to the variable with the @inject annotation:
/** @inject @var \App\Service2 */
public $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.

$container = new MyContainer(...);

$article = $container->createArticle();

Component Factory
-----------------

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

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

```php
interface ITableFactory
{
/**
* @return Table
*/
public function create();
}
```

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

```php
class Table
{
private $manager;

public function __construct(Manager $Manager)
{
$this->Manager = $manager;
}
}
```

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

```neon
services:
- ITableFactory
```

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:

```neon
services:
tableFactory:
implement: ITableFactory
```

From the call of `$container->createArticle()` is evident, that a new object is always created. It is then a programmer's convention.
This full definition allows us to declare additional configuration of the component 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:

```php
class Foo
{
private $tableFactory;

function __construct(ITableFactory $tableFactory)
{
$this->tableFactory = $tableFactory;
}

function bar()
{
$table = $this->tableFactory->create();
}
}
```

0 comments on commit 912f91c

Please sign in to comment.