Skip to content

404 page #6

@playmate69

Description

@playmate69

Hi nice done! But what if I want to add a 404 page? It would really help me if you have an option for this!

Activity

ocram

ocram commented on Dec 4, 2019

@ocram
Contributor

Thanks, good question!

By default, the router executes all routes that match. You could say it combines the defined routes with AND.

But as each route definition returns whether the route matches, you can change it so that the router executes only the first matching route.

Instead of the default

$router->get('/', function () {
    // do something
});

just write

$router->get('/', function () {
    // do something
}) && exit;

to combine them with OR instead.

If you do that, you can simply include your 404 page after all route definitions. It will only be shown if no route matched.

This is available as of today. Alternatively, we could include a new method like Router#didAnyRouteMatch in the future. With that method, you could check if the request has already been handled or if you should show your 404 page instead.

Does that help?

brahimbjz

brahimbjz commented on May 18, 2020

@brahimbjz

Has the Router#didAnyRouteMatch function already implemented? It would be great, I'm currently using this, and it works fine for me but it would be much better with a function that determines if any routes have been loaded or not:

$router->get('/', function () {
    // do something
}) && $find = true;
ocram

ocram commented on May 18, 2020

@ocram
Contributor

That feature is indeed not available yet. Sorry for that!

In the meantime, the solution we proposed above

$router->get('/', function () {
    // do something
}) && exit;

$router->post('/sign-up', function () {
    // do something
}) && exit;

\http_response_code(404);

or your solution

$matched = false;

$router->get('/', function () {
    // do something
}) && ($matched = true);

$router->post('/sign-up', function () {
    // do something
}) && ($matched = true);

if (!$matched) {
    \http_response_code(404);
}

should both work fine, although admittedly being a little more verbose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ocram@playmate69@brahimbjz

        Issue actions

          404 page · Issue #6 · delight-im/PHP-Router