Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/feb4768dbb118c651ba0 to your computer and use it in GitHub Desktop.
Save mindplay-dk/feb4768dbb118c651ba0 to your computer and use it in GitHub Desktop.
Options for Router design
<?php
// (1) With support for caching and URL creation:
// - can't retain Route objects; use named routes instead
// - can't use closures; static coupling to class-name only, not to method-name; use method-name convention instead
class ArticleUrl
{
/** @var Router */
protected $router;
public function __construct(Router $router)
{
// retaining the Router reference
$this->router = $router;
}
public function registerRoutes(Router $router)
{
$router
->route('/articles/<article_id:int>-<title:slug>')
->name('article', 'show')
->get(ShowArticleController::class);
}
public function show(Article $article)
{
return $this->router->url('article', 'show', ['id' => $article->getId(), 'title' => $article->getTitle()]);
}
}
class ShowArticleController
{
public function get($article_id)
{
return new PageResult(new ArticlePage(article_api()->getRepo()->getArticle($article_id)));
}
}
<?php
// (2) NO support for caching:
// - retain references to Route objects; don't need named routes
// - dispatch via closures; static coupling to class-name and method-name
class ArticleUrl
{
/** @var Route */
protected $show_route;
public function registerRoutes(Router $router)
{
$this->show_route = $router->route('/articles/<article_id:int>-<title:slug>')->get(function ($article_id) {
return (new ArticleController)->showArticle($article_id);
});
}
public function show(Article $article)
{
return $this->show_route->url(['id' => $article->getId(), 'title' => $article->getTitle()]);
}
}
class ArticleController
{
public function showArticle($article_id)
{
return new PageResult(new ArticlePage(article_api()->getRepo()->getArticle($article_id)));
}
}
<?php
// (3) With support for caching, but NO support for URL creation:
// - can't retain Route objects; don't need named routes for URL creation
// - can't use closures; static coupling to class-name only, not to method-name; use method-name convention instead
// - don't need to retain Router reference: URL creation independent of Router
class ArticleUrl extends UrlHelper
{
public function registerRoutes(Router $router)
{
$router
->route('/articles/<article_id:int>-<title:slug>')
->get(ShowArticleController::class);
}
public function show(Article $article)
{
return "/articles/{$article->getId()}-{$this->slug($article->getTitle())}";
}
}
class ShowArticleController
{
public function get($article_id)
{
return new PageResult(new ArticlePage(article_api()->getRepo()->getArticle($article_id)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment