Problem with calling function with Alto Router package in PHP

239 Views Asked by At

I have a problem with calling function using alto routing. On index.php I I have my route that calls function that is in another file (test.php) and those two files are in the same directory (root). I get no response, but when I put that function from test.php to index.php where are my routes then it works and I need that function to work in test.php file. I tried putting 'require(index.php)' in test.php file but it doesn't work. Any help is appreciated if someone knows workaround for this. Here is my code.

index.php

<?php

require 'vendor/autoload.php';

$router = new AltoRouter();

$router->map('GET','/test', 'test.php', 'testfunction'); // HERE IS THAT ROUTE!!!

$match = $router->match();

if ( is_array($match) && is_callable( $match['target'] ) ) {
    call_user_func_array( $match['target'], $match['params'] ); 
} else {
    header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}

test.php

<?php

require 'index.php';

function testfunction()
{
    echo "YES IT WORKS!";
}
1

There are 1 best solutions below

2
Jared Farrish On

This is speculative, since I don't know AltoRouter, however if each page has it's own (single) specific function, you can return the function as a closure:

<?php // ./test.php

return function () {
    return "YES IT WORKS!";
};

Closures were introduced in PHP 5.3. Then, your router would be something like:

$router->map('GET', '/test', require 'test.php'); 

This works because require and include give the return from the script:

Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would for a normal function.

https://www.php.net/manual/en/function.include.php

See a sample in action here:

https://replit.com/@userdude/SimpleRouterReturnClosure#index.php


If you have 7.4, arrow functions make the syntax much simpler for the example:

<?php // ./test.php

return fn() => "YES IT WORKS!";