flightphp / core

An extensible micro-framework for PHP
https://docs.flightphp.com
MIT License
2.64k stars 408 forks source link

[Docs > Routing] Method Routing #561

Closed ampmonteiro closed 8 months ago

ampmonteiro commented 8 months ago

Hi,

// GET request
$router->get('/users', function() {
    echo 'users';
});
// $router->post();
// $router->put();
// $router->delete();
// $router->patch();

How to do the registration of this routes on Flight class ? which method to use ?

n0nag0n commented 8 months ago

So if I'm following you right, if you want to get a router object you simple would do $router = Flight::router(). Or if you created your Engine instance with Flight::app() or $app = new flight\Engine(); then you would do $router = $app->router();

ampmonteiro commented 8 months ago

Hi, maybe i did not explain well the problem.

in the docs you put the above code example ( the screenshot ) to use not static method for routes def.

My question is, after defined that routes like this:

require dirname(__DIR__) . '/vendor/autoload.php';

$router = Flight::router();

$router->get(
    '/',
    fn () =>  Flight::response()->write('from resp ')
);

// Finally, start the framework.
Flight::start();

This will give me an error of not found. As such how i am going to append this router instance into Flight class ?

n0nag0n commented 8 months ago

So the issue here is your line fn () => Flight::response()->write('from resp '). This could be rewritten as function() { return Flight::response()->write('from resp '); } The issue here is related to https://docs.flightphp.com/learn/routing#passing where you can bypass the executed route by returning true. In this case, the true is loose so basically anything that is returned will be considered true.

That is something that could be changed in the future, but for now it has to stay that way to handle backwards compatibility.

n0nag0n commented 8 months ago

I added this to the v4 roadmap

ampmonteiro commented 8 months ago

So the issue here is your line fn () => Flight::response()->write('from resp '). This could be rewritten as

function() { 
return Flight::response()->write('from resp '); 
}

No need of return. I try just this:

$router->get(
    '/',
    function () {
        Flight::response()->write('from resp ');
    }
);

And it just works fine. ;)

n0nag0n commented 8 months ago

Glad you got it working :) Thanks for using Flight! Tell your friends!