I'm implementing the Klein router in php and I have a little problem... I would like to call a special function from my controller, giving it (or not) $request variable like this :
$klein->respond('GET', '/[i:id]?', HomeController::view($request));
But I have the error : Uncaught InvalidArgumentException: Expected a callable. Got an uncallable NULL So I changed my code to :
$klein->respond('GET', '/[i:id]?', new HomeController::view($request));
and now the error is this one : syntax error, unexpected 'view' (T_STRING), expecting variable (T_VARIABLE) or '$' Finally I found a solution writting my code like this :
$klein->respond('GET', '/[i:id]?', function($request){ HomeController::view($request); });
This one is working but I feel I'm missing something... I would like to factorize this, is there any solution? Thanks you
Try this:
$klein->respond('GET', '/[i:id]?', array('HomeController','view'));
In the Klein examples, like in your third example, we're passing a closure, or an anonymous function, or a lambda, or whatever else you want to call it. At any rate, because we're declaring it inline, we have to specify the parameters.
On the other hand, HomeController::view
has its arguments specified in its own declaration. If you put the arguments inline, like in your first and second examples, you're actually calling your view
function on that line. You want to pass the function to $klein
, to be called later, which is what my example above should do.
Klein's respond
function takes what PHP refers to as a callable. It turns out there's a million ways to specify a callable in PHP:
http://php.net/manual/en/language.types.callable.php
I was thinking you could do $klein->respond('GET', '/[i:id]?', HomeController::view);
but that doesn't appear to be correct. It works in Python, but not PHP. Oh well.
If you're using PHP 5.4 or later, you can use the short array syntax:
$klein->respond('GET', '/[i:id]?', ['HomeController','view']);
to make it a little more compact.