问题
I have a very simple application where I intend to optionally accept a parameter on the index route such that the user can either go to http://example.com/
or http://example.com/somethingrandom
I wish to be able to capture the somethingrandom
as an optional parameter but I am having no luck. Here is my route:
$app -> get('/(:random)', function($random=null) use($app) {
... do some stuff
});
回答1:
According to the Slim documentation, the /
needs to be inside the parentheses. So try:
$app -> get('(/:random)', function($random=null) use($app) {
... do some stuff
});
回答2:
So getting this working was not a lack of understanding of the slim framework but to do with my default apache2 setup on OS X. By default in later versions of OS X, PHP is not enabled. This was not MY issue but is part of the cause. I followed this tutorial to ensure my setup was correct. In addition to this article I had to uncomment the line that loads up the mod_rewrite
module.
I then created a virtual host in /etc/apache2/extra/httpd-vhosts.conf
<VirtualHost *:80>
DocumentRoot "/Users/tbm/Sites/example.com"
ServerName shor.ty
<Directory "/Users/tbm/Sites/example.com">
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>
and added 127.0.0.1 example.com www.example.com
into my hosts file so that I was able to access the site with a domain name from my browser.
Last, thanks to enabling the mod_rewrite
module, I created a .htaccess
file that ensured that all requests go through index.php
allowing the slim router to take over and display the correct page
Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ /index.php [QSA,L]
Having done all this I was then able to solve my problem using the following syntax
$app -> get('/(:random)', function($random=null) use($app) {
... do some stuff
});
The difference now is that when I visit a page at /some_string
apache is told to rewrite the request and run index.php
that then invokes slim to find the correct route and render the correct page. I hope this makes sense
来源:https://stackoverflow.com/questions/30576322/optional-parameters-on-index-route