Webiny\Component\Bootstrap\Router::initializeRouter PHP Method

initializeRouter() public method

The method initializes router and tries to call the callback assigned to the current url. Method is call automatically from the Bootstrap class.
public initializeRouter ( string $url = null ) : Dispatcher
$url string Url to route. If not set, the current url is used.
return Dispatcher
    public function initializeRouter($url = null)
    {
        // current url
        $currentUrl = is_null($url) ? $this->httpRequest()->getCurrentUrl() : $url;
        // init the router
        try {
            // try matching a custom route
            $result = $this->router()->match($currentUrl);
            if ($result) {
                // custom route matched
                // based on callback, route the request
                $callback = $result->getCallback();
                // namespace
                $ns = Bootstrap::getInstance()->getEnvironment()->getApplicationConfig()->get('Namespace', false);
                // extract callback parts
                $callbackData = $this->str($callback['Class'])->trimLeft('\\')->trimLeft($ns)->explode('\\')->val();
                if ($callbackData[1] == 'Modules' && $callbackData[3] == 'Controllers') {
                    // custom route, but still an MVC application
                    return $this->dispatchMvc($callbackData[2], $callbackData[4], $callback['Method'], $result->getParams());
                } else {
                    // custom route and custom callback (non MVC)
                    return $this->dispatchCustom($callback['Class'], $callback['Method'], $result->getParams());
                }
            } else {
                // fallback to the mvc router
                return $this->mvcRouter($this->httpRequest()->getCurrentUrl(true)->getPath());
            }
        } catch (\Exception $e) {
            throw $e;
        }
        throw new BootstrapException('No router matched the request.');
    }

Usage Example

Exemplo n.º 1
0
 /**
  * Initializes the router.
  *
  * @throws BootstrapException
  * @throws \Exception
  */
 public function initializeRouter()
 {
     try {
         // initialize router
         $this->router = Router::getInstance();
         // if a route is matched, a dispatcher instance is returned, and the callback is issued
         $this->router->initializeRouter()->issueCallback();
     } catch (BootstrapException $e) {
         throw $e;
     }
 }