You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: doc/en/components.texy
+80Lines changed: 80 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -203,6 +203,86 @@ This parameter will be automatically passed in every link as a `GET` parameter u
203
203
.[caution]
204
204
Never trust persistent parameters blindly because they can be faked easily (by overwriting the URL). Verify, for example, if the page number is within the correct interval.
205
205
206
+
Components with dependencies
207
+
===========================
208
+
209
+
When our component needs some things to work, like `PollControl` needs `PollManager` to manage voting and save polls, it can be done by [injecting these dependencies | dependency-injection] into the constructor:
210
+
211
+
/--php
212
+
class PollControl extends Control
213
+
{
214
+
/**
215
+
* @var App\Model\PollManager
216
+
*/
217
+
private pollManager;
218
+
219
+
/**
220
+
* @var int Id of a poll, for which the component is created
221
+
*/
222
+
private $pollId;
223
+
224
+
/**
225
+
* @param $pollId
226
+
* @param App\Model\PollManager $pollManager model providing the voting
227
+
*/
228
+
public function __construct($pollId, PollManager $pollManager)
229
+
{
230
+
$this->pollManager = $pollManager;
231
+
$this->pollId = $pollId
232
+
}
233
+
234
+
/**
235
+
* @param $voteId Option Id we voted for
236
+
*/
237
+
public function handleVote($voteId)
238
+
{
239
+
$this->pollManager->vote($pollId, $voteId);
240
+
//...
241
+
}
242
+
}
243
+
\--
244
+
245
+
OK, but how the `PollManager` is put into the `PollControl`'s constructor? That's job for [DI | dependency-injection] container. It put it there automatically through an interface we provide it:
246
+
247
+
/--php
248
+
interface IPollControlFactory
249
+
{
250
+
/**
251
+
* @param $pollId
252
+
* @return PollControl
253
+
*/
254
+
public function create($pollId);
255
+
}
256
+
\--
257
+
258
+
And this interface has to be registered in our container in [neon | configuring#toc-custom-services]:
259
+
260
+
261
+
/--neon
262
+
services:
263
+
- IPollControlFactory
264
+
\--
265
+
266
+
Finally, we will use this factory in our presenter:
267
+
268
+
/--php
269
+
class PollPresenter extends \Nette\UI\Application\Presenter
That's all. Nette internally implements this interface and injects it to our presenter, where we can use it. It also magically passes our parameter `$pollId` and instance of class `App\Model\PollManager` into our component.
0 commit comments