Code Monkey home page Code Monkey logo

Comments (13)

MaximSavin avatar MaximSavin commented on August 25, 2024 2

I found solution with use Siler\Container, but need to define Container\set('found', true); inside each route.
Can you advised better idea?

use Siler\Container;

Route\get('/', function () {

	echo 'Hello World';
	Container\set('found', true);

});


if (is_null(Container\get('found'))) {

	Response\html($_SERVER['REQUEST_URI']." — not found", 404);

};

from siler.

leocavalcante avatar leocavalcante commented on August 25, 2024 2

Hi @MaximSavin
You can add a route listener that matches any other case at the bottom of the file where your route live:

Route\get('.*', function () {
    Response\html($_SERVER['REQUEST_URI']." — not found", 404);
});

Don't forget that Siler doesn't have an inner breakpoint for routes, so you have to explicit exit the PHP operation:

Route\get('/', function () {
    echo 'It works';
    exit(); // <- explicit stops to avoid the 404 route to be reached
});

Route\get('.*', function () {
    Response\html($_SERVER['REQUEST_URI']." — not found", 404);
});

from siler.

aalasolutions-zz avatar aalasolutions-zz commented on August 25, 2024 1

@MaximSavin @leocavalcante

I think we can use condition mentioned below so we don't have to add exit in each function. It will simply check if something is sent to browser then don't send 404 error.

if (!headers_sent()) {
    Route\get('.*', function () {
        Response\html($_SERVER['REQUEST_URI']." — not found", 404);
    });
}

from siler.

leocavalcante avatar leocavalcante commented on August 25, 2024 1

Sorry about the comment spam, but I just thought that you can also mix both:

$fooHandler = function() {
  Route\stop_propagation();
  return Diactoros\json('foo');
};

$barHandler = function() {
  Route\stop_propagation();
  return Diactoros\json('bar');
};

$response = Route\match([
  Route\get('/foo', $fooHandler),
  Route\get('/bar', $barHandler),
]);

HttpHandlerRunner\sapi_emit($response);

On the first path match, the handler is called, then if Route\stop_propagation() is called on that handler all other routes will immediately return null without any path ou handler evaluation. Basically a short-circuit.

from siler.

MaximSavin avatar MaximSavin commented on August 25, 2024

Wow, it's look more elegant..

Thanks!

from siler.

alturic avatar alturic commented on August 25, 2024

I hate to necro this, but technically there are caveats with that too. For example:

Route\get('/test', __DIR__.'/../pages/test.php');

if (!headers_sent()) {
  Route\get('.*', function () {
      Siler\Http\Response\html("404", 404);
  });
}

In test.php it's a simple echo "temp"; but you'll see "temp404" in the browser.

from siler.

aalasolutions-zz avatar aalasolutions-zz commented on August 25, 2024

@alturic this should be at the end of route, so if nothing is printed to browser only then it should give 404

from siler.

alturic avatar alturic commented on August 25, 2024

@aalasolutions Do you mean "at the end of route" as in exactly how I showed it? If so, in test.php I literally had:

<?php

echo "temp";

And it output "temp404" to the browser.

I appreciate the simplicity of the package (truly), but going from all of my public-facing pages being in /public, to putting them outside of the /public directory and into /pages and just having /public/index.php have the routing (like the example in my comment) broke all my links. I use href="/foo" so it became href="/pages/foo" for some unknown reason. Possibly due to using the PHP CLI while I was testing, no clue why it did that. That basically made me stop testing right there. :P

from siler.

aalasolutions-zz avatar aalasolutions-zz commented on August 25, 2024

This is my router file

<?php
require '_config.php';
use Siler\Route;
use Siler\Http\Response;

// Controller Loaded
use App\Controllers\Room;
use App\Controllers\User;


use App\Game;


//$d = new Game\Deck();


// Controller Objects;
$userController = new User();
$roomController = new Room();
// Routes
//Route\get('/', function () {
//    echo 'Hello World';
//});
define("PATH_DIR", str_replace('\\', '/', __DIR__) . '/');


Route\post('/user/login', [$userController, 'login']);
Route\post('/user/facebookLogin', [$userController, 'facebookLogin']);
//Route\get('test', [$roomController, 'testPage']);
Route\post('/user/signup', [$userController, 'signup']);
Route\get('/room/kicker', [$roomController, 'getKicker']);

// for test
Route\get('/tests', [$roomController, 'test']);

// Authenticated Routes
if (!headers_sent() && !ob_get_contents()) {
    return checkAuth(function () use ($roomController, $userController) {

        Route\post('/tournaments', [$roomController, 'listTournaments']);
        Route\post('/rooms', [$roomController, 'listRooms']);
        Route\post('/room/join', [$roomController, 'joinRoom']);
        Route\post('/room/leave', [$roomController, 'leaveRoom']);
        Route\post('/room/sit', [$roomController, 'sitInRoom']);
        Route\post('/room/roomInfo', [$roomController, 'getRoomInfo']);

        Route\post('/round/start', [$roomController, 'startRound']);

        Route\post('/room/updatePlayer', [$roomController, 'updateRoomPlayer']);
        Route\post('/room/seats', [$roomController, 'getRoomSeats']);
        Route\post('/room/changeRound', [$roomController, 'changeRound']);
        Route\post('/room/winner', [$roomController, 'roundWinner']);
        Route\post('/room/standUp', [$roomController, 'standUp']);
        Route\post('/room/split', [$roomController, 'splitPot']);
        Route\post('/room/sideWinner', [$roomController, 'sidePotWinner']);
        Route\post('/room/getMessages', [$roomController, 'getMessages']);
        Route\post('/room/sendMessage', [$roomController, 'sendMessage']);

        Route\get('/user/details', [$userController, 'userDetails']);

        // for test
        Route\get('/users', [$userController, 'getUsers']);
        Route\get('/user/leaderboard', [$userController, 'leaderboard']);
        Route\get('/user/myRank', [$userController, 'playerPosition']);
        Route\post('/user/dailyReward', [$userController, 'dailyReward']);
        Route\post('/user/uploadImage', [$userController, 'uploadImage']);
        Route\post('/user/changePassword', [$userController, 'changePassword']);
        Route\post('/user/notice/update', [$userController, 'updateNotice']);
        Route\post('/user/notice/delete', [$userController, 'deleteNotice']);
        Route\post('/user/updateChips', [$userController, 'updateUserChips']);
        Route\post('/user/password/reset', [$userController, 'forgotPassword']);

        Route\get('/user/notices', [$userController, 'getNotices']);

        Route\get('/user/getDailyReward', [$userController, 'getDailyReward']);
    });
}

// If no Route found in both above conditions, give 404 ERROR
if (!headers_sent() && !ob_get_contents()) {
    Route\get('.*', function () {
        return Response\html($_SERVER['REQUEST_URI'] . " — Route Not found", 404);
    });
}

exit;

See how I put that at the end.. it is working fine for me

from siler.

aalasolutions-zz avatar aalasolutions-zz commented on August 25, 2024

May be you have output buffering on? for that ob_get_content is important

from siler.

leocavalcante avatar leocavalcante commented on August 25, 2024

Hi @aalasolutions, hi @MaximSavin,
Latest versions of Siler introduced Route\stop_propagation().

Route\get('/', function () {
  echo 'foo';
  Route\stop_propagation();
});

Route\get('/', function () {
  echo 'bar';
  Route\stop_propagation();
});

Only foo will be printed. After stop_propagation() no other route is matched:
https://github.com/leocavalcante/siler/blob/master/src/Route/Route.php#L113

Tell me if this solve the issue or we can think on something properly ;)

Cheers.

from siler.

leocavalcante avatar leocavalcante commented on August 25, 2024

Ah, we also have Route\match(array) now. It will stop-on-first:

$body = Route\match([
  Route\get('/', λ\always('foo')),
  Route\get('/', λ\always('bar')),
]);

echo $body; // foo

from siler.

leocavalcante avatar leocavalcante commented on August 25, 2024

P.S.: key difference here: stop_propagation is lazy and match is eager. Route\match will evaluate all routes then return the first-non-null. Route\stop_propagation can prevent subsequent routes to be evaluated.

P.S. 2: route evaluation on match doesn't mean that all handlers will always be evaluated, if the paths doesn't match it immediately returns null:

$fooHandler = function() {
  echo 'foo';
  return 'foo';
};

$barHandler = function () {
  echo 'bar';
  return 'bar';
};

$response = Route\match([
  Route\get('/foo', $fooHandler),
  Route\get('/bar', $barHandler),
]);

echo $response;

On a request with /foo as path, $barHandler is not called ;)

from siler.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.