2

I am using PHP-DI with the Slim framework. In Slim you make a route segment optional by putting brackets around it. Now that I have set up PHP-DI when I leave out the optional route segment, I get this error:

Type: Invoker\Exception\NotEnoughParametersException
Message: Unable to invoke the callable because no value was given for parameter 1 ($limit)

Here is my route:

$app->get('/api2/products[/{limit}]', ['\App\Controllers\SampleProductController', 'show']);

I can't find anything in the PHP-DI docs that talk about the optional part, just how to get the value of a named segment.

donfifty
  • 322
  • 2
  • 13
  • What is the signature for the method `\App\Controllers\SampleProductController::show` ? – bassxzero Dec 12 '17 at 17:19
  • public function show($limit = 10, Request $request, Response $response) – donfifty Dec 12 '17 at 17:21
  • The way you've written that method makes the `$limit` look optional but it really is not as there is no way to invoke the function and omit the `$limit` – apokryfos Dec 12 '17 at 17:22
  • 1
    I don't think that method signature is valid. Aren't optional parameters supposed to be last in the list? – bassxzero Dec 12 '17 at 17:22
  • http://php.net/manual/en/functions.arguments.php#functions.arguments.default Look at example #5 – bassxzero Dec 12 '17 at 17:24
  • Thanks for the link, I moved the limit var to the right side and it works. Interesting that the PHP-DI docs show the var for the named segment on the left end of the signature. http://php-di.org/doc/frameworks/slim.html#request-attribute-injection – donfifty Dec 12 '17 at 17:30
  • @dstefani It will probably set $name to null if it's omitted in the URL. – bassxzero Dec 12 '17 at 17:33
  • It still looks like PHP-DI removes the optional segments functionality that Slim offers. I hope I'm wrong, this is a porwerful tool. https://www.slimframework.com/docs/objects/router.html#route-placeholders – donfifty Dec 12 '17 at 17:47
  • dstefani & @bassxzero thanks for the details, I confirm this is a bug. I added an answer with more details. – Matthieu Napoli Dec 12 '17 at 18:02

1 Answers1

3

PHP-DI author here. This is a bug :)

This is something I fixed not so long ago here: #521 But it seems I didn't apply the same logic everywhere (for example in the Invoker package, which is used by all the framework integrations).

I have opened #562 to track this bug, have a look at it for more information.

In the meantime as a workaround you can indeed move the parameter to the end of the method as suggested in the comments.

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • Out of curiosity, why would you offer this functionality in your library if PHP doesn't? – bassxzero Dec 12 '17 at 18:08
  • @bassxzero I asked myself the same question too :) I guess because people would expect it to work so why not. But this is a bit confusing as we can see. – Matthieu Napoli Dec 14 '17 at 08:33