Simplify working with Router in Handlebars helpers

This commit is contained in:
Dmitriy Simushev 2015-03-19 09:34:16 +00:00
parent 93c5cb995a
commit db702e43c9
2 changed files with 19 additions and 38 deletions

View File

@ -88,17 +88,6 @@ abstract class AbstractController implements
public function setRouter(RouterInterface $router)
{
$this->router = $router;
// Update router in the style helpers
if (!is_null($this->style) && $this->style instanceof HandlebarsAwareInterface) {
$handlebars = $this->style->getHandlebars();
if ($handlebars->hasHelper('route')) {
$handlebars->getHelper('route')->setRouter($router);
}
if ($handlebars->hasHelper('csrfProtectedRoute')) {
$handlebars->getHelper('csrfProtectedRoute')->setRouter($router);
}
}
}
/**
@ -361,13 +350,10 @@ abstract class AbstractController implements
$hbs->setCache(new HandlebarsCacheAdapter($this->getCache()));
// Add more helpers to template engine
$hbs->addHelper(
'route',
new RouteHelper($this->getRouter())
);
$hbs->addHelper('route', new RouteHelper($this));
$hbs->addHelper(
'csrfProtectedRoute',
new CsrfProtectedRouteHelper($this->getRouter())
new CsrfProtectedRouteHelper($this)
);
$hbs->addHelper(
'asset',

View File

@ -35,37 +35,22 @@ use Mibew\Routing\RouterInterface;
* The code above generates URL for route named "hello" and pass parameter
* "to" equals to "world" to URL generator.
*/
class RouteHelper implements HelperInterface, RouterAwareInterface
class RouteHelper implements HelperInterface
{
/**
* @var RouterInterface
* @var RouterAwareInterface
*/
protected $router = null;
/**
* {@inheritdoc}
*/
public function getRouter()
{
return $this->router;
}
/**
* {@inheritdoc}
*/
public function setRouter(RouterInterface $router)
{
$this->router = $router;
}
protected $routerContainer = null;
/**
* Helper's constructor.
*
* @param RouterInterface $router A Router instance.
* @param RouterAwareInterface $router_container An object that keeps router
* instance.
*/
public function __construct(RouterInterface $router)
public function __construct(RouterAwareInterface $router_container)
{
$this->setRouter($router);
$this->routerContainer = $router_container;
}
/**
@ -87,4 +72,14 @@ class RouteHelper implements HelperInterface, RouterAwareInterface
return $this->getRouter()->generate($route_name, $parameters);
}
/**
* Extracts router from the router's container related with the object.
*
* @return RouterInterface
*/
protected function getRouter()
{
return $this->routerContainer->getRouter();
}
}