Skip to content

Instantly share code, notes, and snippets.

@NoxArt
Forked from vojtech-dobes/BasePresenter.php
Created March 21, 2012 07:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NoxArt/2145394 to your computer and use it in GitHub Desktop.
Save NoxArt/2145394 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) {
$defaultArgs = array($presenter, $id);
return call_user_func_array(array($presenter, $method), array_merge($defaultArgs, $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 array($this->context->model->getPosts()->fetchAssoc('id'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment