Skip to content

Latest commit

 

History

History
executable file
·
143 lines (108 loc) · 5.4 KB

5.3Router.php.md

File metadata and controls

executable file
·
143 lines (108 loc) · 5.4 KB

Criação da classe Router

Criar a pasta /var/www/html/app-mvc/src/Core

E dentro dela o arquivo Router.php contendo o código abaixo:

<?php
/** For more info about namespaces plase @see http://php.net/manual/en/language.namespaces.importing.php */
namespace Mvc\Core;

class Router
{
    /** @var null The controller */
    private $url_controller = null;

    /** @var null The method (of the above controller), often also named "action" */
    private $url_action = null;

    /** @var array URL parameters */
    private $url_params = array();

    /**
     * "Start" the application:
     * Analyze the URL elements and calls the according controller/method or the fallback
     */
    public function __construct()
    {
        // create array with URL parts in $url
        $this->splitUrl();

        // check for controller: no controller given ? then load start-page
        if (!$this->url_controller) {
			// if none controller is found call HomeController with index action
            $page = new \Mvc\Controller\HomeController();
            $page->index();

		// if encounter a controller
        } elseif (file_exists(APP . 'Controller/' . ucfirst($this->url_controller) . 'Controller.php')) {
            // here we did check for controller: does such a controller exist ?

            // if so, then load this file and create this controller
            // like \Mvc\Controller\CustomersController
            $controller = "\\Mvc\\Controller\\" . ucfirst($this->url_controller) . 'Controller';
            $this->url_controller = new $controller();

            // check for method: does such a method exist in the controller ?
			// if exists method and if is callable method
            if (method_exists($this->url_controller, $this->url_action) && is_callable(array($this->url_controller, $this->url_action))) {
                
				// check if params is d'ont empty
                if (!empty($this->url_params)) {
                    // if exists Call the method and pass arguments to it
                    call_user_func_array(array($this->url_controller, $this->url_action), $this->url_params);
                } else {
                    // If no parameters are given, just call the method without parameters, like $this->home->method();
                    $this->url_controller->{$this->url_action}();
                }

			// if none method is found
            } else {
                if (strlen($this->url_action) == 0) {
                    // no action defined: call the default index() method of a selected controller
                    $this->url_controller->index();

				// otherwise fire ErrorController
                } else {
                    $page = new \Mvc\Controller\ErrorController();
                    $page->index();
                }
            }

		// if none controller is found fire ErrorController
        } else {
            $page = new \Mvc\Controller\ErrorController();
            $page->index();
        }
    }

    /**
     * Get and split the URL
     */
    private function splitUrl()
    {
		// check if url is isset
        if (isset($_GET['url'])) {

            // split URL
            $url = trim($_GET['url'], '/');
            $url = filter_var($url, FILTER_SANITIZE_URL);
            $url = explode('/', $url);

            // Put URL parts into according properties
            // By the way, the syntax here is just a short form of if/else, called "Ternary Operators"
            // @see http://davidwalsh.name/php-shorthand-if-else-ternary-operators
            $this->url_controller = isset($url[0]) ? $url[0] : null;
            $this->url_action = isset($url[1]) ? $url[1] : 'index';// null

            // Remove controller and action from the split URL
            unset($url[0], $url[1]);

            // Rebase array keys and store the URL params
            $this->url_params = array_values($url);

            // for debugging. uncomment lines below if you have problems with the URL
            //echo 'Controller: ' . $this->url_controller . '<br>';
            //echo 'Action: ' . $this->url_action . '<br>';
            //echo 'Parameters: ' . print_r($this->url_params, true) . '<br>';
        }
    }
}

Explicando um pouco:

Veja que é uma classe bem documentada, com comentários distribuídos por toda ela. É uma classe com todos os métodos e propriedades privates, portanto nada pode ser executado fora da classe. A classe apenas é instanciada e tudo acontece, ou seja, ela fica disponível para o aplicativo.

Inicialmente chama o método splitUrl() que quebra a URL em partes: controller, action e parameters.

Logo no construtor ele lida com os controllers, actions e parâmetros e abaixo com o método splitUrl(), quebra a URL.

Então checa por controllers, caso exista será chamado,

Depois verifica o método e o chama. Caso nenhum action seja chamado será aberto o default, que é o index

Caso exista parâmetros os chama também. Caso nenhum seja chamado será aberto apenas controller/action

Também controla os demais ou disparará o controller Error caso seja apropriado.

Nossa classe Router lida com controller, action e parameters.

Os usuários tanto podem usar os links do menu, quando podem digitar diretamente o link para o recurso desejado. Exemplos:

Ao chamar pelo navegador novamente, agora ele reclama do HomeController.php

Vamos a ele.