1

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!";
}
mrmar
  • 1,407
  • 3
  • 11
  • 26

1 Answers1

1

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!";
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • It works now, but what if I want multiple functions in my test.php? How would I name them in order to be able to differentiate them? – mrmar Jul 07 '21 at 15:40
  • 1
    You're really talking about how to organize your routes. Check out the repl.it `handlers.php` file for how you can organize by namespace and reference each one from a single file. So either each handler has it's own file, or create a file that loads your namespaced handlers, or implement `use` statements to declare the functions in the top of `index.php`, which can then live in files organized separately but only be loaded if used. – Jared Farrish Jul 07 '21 at 15:49