/
extensions.texy
194 lines (147 loc) Β· 5.8 KB
/
extensions.texy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
Creating Extensions for Nette DI
********************************
.[perex]
Generating an DI container in addition to configuration files also affect the so-called *extensions*. We activate them in the configuration file in the `extensions` section.
This is how we add the extension represented by class `BlogExtension` with name `blog`:
```neon
extensions:
blog: BlogExtension
```
Each compiler extension inherits from [api:Nette\DI\CompilerExtension] and can implement following methods that are called during DI compilation:
1. getConfigSchema()
2. loadConfiguration()
3. beforeCompile()
4. afterCompile()
getConfigSchema() .[method]
===========================
This method is called first. It defines schema used to validate configuration parameters.
Extensions are configured in a section whose name is the same as the one under which the extension was added, eg `blog`.
```neon
# same name as my extension
blog:
postsPerPage: 10
comments: false
```
We will define a schema describing all configuration options, including their types, accepted values and possibly default values:
```php
use Nette\Schema\Expect;
class BlogExtension extends Nette\DI\CompilerExtension
{
public function getConfigSchema(): Nette\Schema\Schema
{
return Expect::structure([
'postsPerPage' => Expect::int(),
'allowComments' => Expect::bool()->default(true),
]);
}
}
```
See the [Schema |schema:] for documentation. Additionally, you can specify which options can be [dynamic |application:bootstrap#Dynamic Parameters] using `dynamic()`, for example `Expect::int()->dynamic()`.
We access configuration through the `$this->config`, which is an object `stdClass`:
```php
class BlogExtension extends Nette\DI\CompilerExtension
{
public function loadConfiguration()
{
$num = $this->config->postPerPage;
if ($this->config->allowComments) {
// ...
}
}
}
```
loadConfiguration() .[method]
=============================
This method is used to add services to the container. This is done by [api:Nette\DI\ContainerBuilder]:
```php
class BlogExtension extends Nette\DI\CompilerExtension
{
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('articles'))
->setFactory(App\Model\HomepageArticles::class, ['@connection']) // or setCreator()
->addSetup('setLogger', ['@logger']);
}
}
```
The convention is to prefix the services added by an extension with its name so that no name conflicts arise. This is done by `prefix()`, so if the extension is called 'blog', the service will be called `blog.articles`.
If we need to rename a service, we can create an alias with its original name to maintain backward compatibility. Similarly this is what Nette does for eg `routing.router`, which is also available under the earlier name `router`.
```php
$builder->addAlias('router', 'routing.router');
```
Retrieve Services from a File
-----------------------------
We can create services using the ContainerBuilder API, but also we can add them via the familiar NEON configuration file and its `services` section. The prefix `@extension` represents the current extension.
```neon
services:
articles:
create: MyBlog\ArticlesModel(@connection)
comments:
create: MyBlog\CommentsModel(@connection, @extension.articles)
articlesList:
create: MyBlog\Components\ArticlesList(@extension.articles)
```
We will add services this way:
```php
class BlogExtension extends Nette\DI\CompilerExtension
{
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
// load the configuration file for the extension
$this->compiler->loadDefinitionsFromConfig(
$this->loadFromFile(__DIR__ . '/blog.neon')['services'],
);
}
}
```
beforeCompile() .[method]
=========================
The method is called when the container contains all the services added by individual extensions in `loadConfiguration` methods as well as user configuration files. At this phase of assembling, we can then modify service definitions or add links between them. You can use the `findByTag()` method to search for services by tags, or `findByType()` method to search by class or interface.
```php
class BlogExtension extends Nette\DI\CompilerExtension
{
public function beforeCompile()
{
$builder = $this->getContainerBuilder();
foreach ($builder->findByTag('logaware') as $serviceName => $tagValue) {
$builder->getDefinition($serviceName)->addSetup('setLogger');
}
}
}
```
afterCompile() .[method]
========================
At this phase, the container class is already generated as a [ClassType |php-generator:#classes] object, it contains all the methods that the service creates, and is ready for caching as PHP file. We can still edit the resulting class code at this point.
```php
class BlogExtension extends Nette\DI\CompilerExtension
{
public function afterCompile(Nette\PhpGenerator\ClassType $class)
{
$method = $class->getMethod('__construct');
// ...
}
}
```
$initialization .[wiki-method]
==============================
The Configurator calls the initialization code after [container creation |application:bootstrap#index.php], which is created by writing to an object `$this->initialization` using [method addBody() |php-generator:#method-and-function-body].
We will show an example of how to start a session or start services that have the `run` tag using initialization code:
```php
class BlogExtension extends Nette\DI\CompilerExtension
{
public function loadConfiguration()
{
// automatic session startup
if ($this->config->session->autoStart) {
$this->initialization->addBody('$this->getService("session")->start()');
}
// services with tag 'run' must be created after the container is instantiated
$builder = $this->getContainerBuilder();
foreach ($builder->findByTag('run') as $name => $foo) {
$this->initialization->addBody('$this->getService(?);', [$name]);
}
}
}
```