Creating a route system

Asked

Viewed 158 times

0

First good afternoon.

I’m trying to create a route system in PHP. So far I have the following routes:

$prefix['teste'] = array('dados' => array(
                        'GET' => array(
                            'Auth/{id}' => array('Method' => 'ControllerAutenticacao@Auth', 'Logged' => 'true'),
                            'Outros/{id}' => array('Method' => 'ControllerAutenticacao@Auth', 'Logged' => 'true'),
                            'Outro/{id}' => array('Method' => 'ControllerAutenticacao@Auth', 'Logged' => 'true')),
                        'POST' => array(
                            'Auth/{id}' => array('Method' => 'ControllerAutenticacao@Auth', 'Logged' => 'true'))    
                        ));

my question: how do I make PHP understand what is inside keys /{id} is a parameter?

I don’t know if I was clear, it’s just that I prefer to understand the logic before I start using frameworks..

1 answer

1


The simplest way is through regular expressions, you must:

  1. Change string inside keys to ([^/]*) so any character other than / repeated 0 or will often be captured

  2. Use the function preg_match to compare the created route (as a regular expression) and the request path, this function returns 1 if the regular expression matches the request route and 0 otherwise check if the return is 1 to continue

  3. The third parameter passed to the previous function will have the values of the captured strings, create an associative array where the keys are the strings defined between keys and the values are the corresponding string in the request path

Code

$rotaDaRequisicao = '/bar/1/teste';

$rotasCriadas = [
    '/foo',
    '/bar/{id}/{qualquerCoisa}'
];

// Parte 1
$rotasRegExp = preg_replace('#\{[a-z]+\}#i', '([^/]*)', $rotasCriadas);

foreach ($rotasRegExp as $index => $rota) {
    //Parte 2
    if (preg_match('#'.$rota.'#', $rotaDaRequisicao, $combinacoes) == 1) {
        array_shift($combinacoes);

        //Parte 3
        preg_match_all('#\{([a-z]+)\}#i', $rotasCriadas[$index], $chaves);

        $chaves = $chaves[1];

        $parametrosDaRota = array_combine($chaves, $combinacoes);

        //Aqui contém o array final, com o nome dos parâmetros definidos ao criar a rota e seus valores
        var_dump($parametrosDaRota);
    }
}

If you only need the values of each parameter, other than with the keys as its name, you can skip part 3, the value of $combinacoes will have a numeric array with values

I suggest looking at the source code of some simpler frameworks:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.