Erich Mosier
Erich Mosier

Reputation: 33

Silex url parameter routing incorrectly

I am setting up a site with silex and I am sure this is a n00b question. I have my htaccess set up (per the silex recommendation) to redirect to my home page if a url does not exist.

<IfModule mod_rewrite.c>
Options -MultiViews

RewriteEngine On
RewriteBase /home
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

so /mysite/api/v1/users will load correctly and display the JSON and list all users, but /mysite/api/v1/somerandomfolder will redirect to the home page. that is all working fine.

The problem I am having is when I try /mysite/api/v1/users/00001 (00001 being the user id), it is redirecting me back to the homepage rather than displaying the JSON for the specific user.

my code in index.php inside my users folder looks like this:

$users = array(
 '00001'=> array(
     'name' => 'John Doe',
     'age' => '53',
     'description' => '...',
     'image' => 'john.jpg',
 ),
 '00002' => array(
     'name' => 'Jane Doe',
     'age' => '27',
     'description' => '...',
     'image' => 'jane.jpg',
 ),
 );

$app->get('/', function() use ($users) {

 return json_encode($users);
 });

 $app->get('/{userid}', function (Silex\Application $app, $userid) use ($users) {

 if (!isset($users[$userid])) {
     $app->abort(404, "User ID {$userid} does not exist.");
 }
 return json_encode($users[$userid]);
 });

$app->run();

I am sure there is some basic concept I am missing but I cannot figure out what it is.

Upvotes: 0

Views: 138

Answers (2)

ooXei1sh
ooXei1sh

Reputation: 3539

I ran your code in my Silex app and it seems to work fine.

I think you may be using multiple front controllers (multiple index.php files). This may be possible to accomplish but it goes against the usual MVC single entry point concept. Let me know if I'm wrong about the multiple index.php files.

Upvotes: 0

Greg Kelesidis
Greg Kelesidis

Reputation: 1054

The route is

$app->get('/mysite/api/v1/users/{userid}', function (Silex\Application $app, $userid) use ($users) {
}

The RewriteBase must be the path to the site root, relative to document root.

Upvotes: 1

Related Questions