Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions en/components.texy
Original file line number Diff line number Diff line change
Expand Up @@ -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
==========================
Expand Down