diff --git a/en/components.texy b/en/components.texy index 4b60e62629..cbabea4b2a 100644 --- a/en/components.texy +++ b/en/components.texy @@ -203,6 +203,86 @@ This parameter will be automatically passed in every link as a `GET` parameter u .[caution] 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. +Components with dependencies +=========================== + +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: + +/--php +class PollControl extends Control +{ + /** + * @var App\Model\PollManager + */ + private pollManager; + + /** + * @var int Id of a poll, for which the component is created + */ + private $pollId; + + /** + * @param $pollId + * @param App\Model\PollManager $pollManager model providing the voting + */ + public function __construct($pollId, PollManager $pollManager) + { + $this->pollManager = $pollManager; + $this->pollId = $pollId + } + + /** + * @param $voteId Option Id we voted for + */ + public function handleVote($voteId) + { + $this->pollManager->vote($pollId, $voteId); + //... + } +} +\-- + +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: + +/--php +interface IPollControlFactory +{ + /** + * @param $pollId + * @return PollControl + */ + public function create($pollId); +} +\-- + +And this interface has to be registered in our container in [neon | configuring#toc-custom-services]: + + +/--neon +services: + - IPollControlFactory +\-- + +Finally, we will use this factory in our presenter: + +/--php +class PollPresenter extends \Nette\UI\Application\Presenter +{ + /** + * @var IPollControlFactory + * @inject + */ + public $pollControlFactory; + + protected function createComponentPollControl() + { + $pollId = 1; // we can pass our parameter + return $this->pollControlFactory->create($pollId); + } +} +\-- + +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. Advanced use of components ==========================