Skip to content

Instantly share code, notes, and snippets.

@vojtech-dobes
Created March 20, 2012 23:16
Show Gist options
  • Save vojtech-dobes/2142331 to your computer and use it in GitHub Desktop.
Save vojtech-dobes/2142331 to your computer and use it in GitHub Desktop.
Annotation support for multiplied Nette components
<?php
use Nette\Application\UI;
use Nette\Reflection\Method;
class BasePresenter extends UI\Presenter
{
/** @var array datasets for Multipliers */
private $datasets = array();
/**
* Adds support for component factories
* with '@multiple' annotation marking usage
* of Nette\Application\UI\Multiplier
*/
protected function createComponent($name)
{
$method = 'createComponent' . ucfirst($name);
if (method_exists($this, $method) && Method::from($this, $method)->hasAnnotation('multiple')) {
$presenter = $this;
return new UI\Multiplier(function ($id) use ($presenter, $name) {
return $presenter->$method($presenter, $id, $presenter->getDataset($name));
});
# in PHP 5.4 factory for multiplied component can be protected
# return new UI\Multiplier(function ($id) use ($name) {
# return $this->$method($this, $id, $this->getDataset($name));
# });
}
return parent::createComponent($name);
}
/**
* Returns dataset with given name
* (dataset factory can be protected)
*
* @return mixed|array
*/
public function getDataset($name)
{
if (!array_key_exists($name, $this->datasets))
{
$this->datasets[$name] = method_exists($this, "createDataset$name") ? call_user_func(array($this, "createDataset$name")) : array();
}
return $this->datasets[$name];
}
}
{block content}
<ul n:if="$control->getDataset('likeIt')">
<li n:foreach="$control->getDataset('likeIt') as $post">
{control likeIt-$post->id}
</li>
</ul>
{/block}
<?php
class FooPresenter extends BasePresenter
{
/**
* Factory for LikeItControl
*
* @multiple
* @param int id of post
* @param array associative array of posts
* @return LikeItControl
*/
public function createComponentLikeIt($id, array $posts)
{
return new LikeItControl($posts[$id]);
}
/**
* Creates dataset for LikeItControl
*
* @return array associative array of posts
*/
protected function createDatasetLikeIt()
{
return $this->context->model->getPosts()->fetchAssoc('id');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment