简体   繁体   English

在Slim中为路由参数指定默认值

[英]Assign default value to route parameter in Slim

Let's say, I have 让我们说,我有

$app->get('/hello/:name', function($name){
  echo 'Hello' . $name;
});

Is it possible to have default value for $name so if I just go to 是否有可能有$name默认值,所以如果我去

http://myurl.com/hello

*without second segment, it will out put *没有第二段,它将出局

Hello default 你好默认

If yes, How to do that ? 如果是的话,怎么做? How to assign default value to route parameter in Slim ? 如何在Slim中为route参数指定默认值?

I know there is Optional Route Parameter , but I'm not sure to use it since it's still experimental. 我知道有可选的路由参数 ,但我不确定使用它,因为它仍然是实验性的。

Thanks. 谢谢。

Try this, I've tested it. 试试这个,我测试过了。 I works well. 我运作良好。

<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello(/:name)', function ($name = 'default') {
    echo "Hello, $name";
});
$app->run();

You can visit like this: 你可以这样访问:

http://slim.test.com/hello
http://slim.test.com/hello/srain

can not visit like this: 不能这样访问:

http://slim.test.com/hello/

update: If you want to make both of them can be visited: 更新:如果你想让他们两个都可以访问:

<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello(/)(/:name)', function ($name = 'default') {
    echo "Hello, $name";
});
$app->run();

You can simply use default parameters . 您只需使用default parameters

$app->get('/hello/:name', function($name="default"){
  echo 'Hello' . $name;
});
$app->get('/hello/:name', function($name){
  if (empty($name)){
    $name='default';
  }
  echo 'Hello' . $name;
});

I was having a similar issue wherein I had to handle an optional parameter in the request. 我遇到了类似的问题,我必须处理请求中的可选参数。 Try this I have tested it myself. 试试这个我自己测试过。

$app->get('/hello(/:name)',function($name="default"){
  echo 'Hello' . $name;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM