Skip to content

Instantly share code, notes, and snippets.

@orobogenius
Created October 1, 2019 09:33
Show Gist options
  • Save orobogenius/f61d155f05882e44a622dcd39b7d7bda to your computer and use it in GitHub Desktop.
Save orobogenius/f61d155f05882e44a622dcd39b7d7bda to your computer and use it in GitHub Desktop.
<?php
class Router
{
/**
* An array of the routes keyed by URI.
*
* @var array
*/
protected $routes = [];
/**
* An array of view paths to search for views.
*
* @var array
*/
protected $viewPaths = [''];
/**
* Create an instance of the router.
*
* @return void;
*/
public function __construct()
{
$this->basePath = dirname(__DIR__);
}
/**
* Add a route to the routes collection.
*
* @param array|string $url
* @param string|null $view
* @return this
*/
public function add($url, $view = null)
{
// If the url is an array, let's quickly iterate through them and
// add them to the collection. Otherwise, we'll register the single
// route and return the router instance.
if (func_num_args() === 1 && is_array($url)) {
foreach ($url as $path => $view) {
$this->routes[$path] = $view;
}
return $this;
}
$this->routes[$url] = $view;
return $this;
}
/**
* Find the route that match the request url.
*
* @param string $url
* @return string
*/
public function match($url)
{
// We'll first look through the list of defined routes
// and if there's a match, we'll just return that, otherwise,
// we'll search through the viewpaths to look for a view matching the
// route.
if (isset($this->routes[$url])) {
return $this->getViewPath().$this->routes[$url];
}
// This basically matches and captures the path of the url.
//For example: /products/asun :)
preg_match('/(.*\/(.*))/', $url, $matches);
// We might have multiple view paths to search for views.
// We'll go through them and try to match the view with the route
foreach ($this->viewPaths as $path) {
if (@file_exists($matchedPath = $this->getViewPath($path).$path.end($matches).'.php')) {
return $matchedPath;
}
}
// Add a fallback route for when there's no match for the current request.
return $this->getViewPath().'404.php';
}
/**
* Get the path to the views.
*
* @return string
*/
protected function getViewPath()
{
return $this->basePath.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment