Reputation: 73
I am kinda new with Slim framework and now I have this problem with named routing... My code for the first route goes like this
$app->get('/admin/home', function() use ($app){
if(!isset($_SESSION)){
$app->render('admin/login.php', [
'message' => 'Restricted access!'
]);
}else{
session_start();
$app->render('admin/home.php', [
'username' => $_SESSION['username']
]);
}
})->name('/admin/home');
but then, when i call this route from another one like this
$app->post('/admin/login', function() use ($app, $conn) {
$app->urlFor('/admin/home');
})->name('/admin/login');
it throws an exception "Named route already exists with name: /admin/login"
i just don't get it... is it even possible to call one route from another one? As i have seen in Slim documentation it should be... Where am i going wrong? Thanks
Upvotes: 0
Views: 941
Reputation: 15430
Avoid naming your routes with slashes.
Instead try this:
$app->get('/admin/home', function() use ($app){
// details here
})->name('admin_home');
Call like so:
$app->post('/admin/login', function() use ($app, $conn) {
echo $app->urlFor('admin_home'); // test it
})->name('admin_login');
Besides, in those two examples, there is currently little advantage to those names you're giving. You're saying: 'Get me the route for /admin/home
and it's returning /admin/home
. If they're identical, why not use a string. Rather, the named routes are convenience methods useful for when you're doing things like returning something the url isn't totally clear about.
Simple example:
name('user_login')
could map to users/login
but name('admin_login')
might map to admin/login
Routes that add clarity:
name('all_customers')
-> /customers
name('top_n_customers)
-> /customers/top/{count:[0-9]+}
name('recent_n_customers)
-> /customers/recent/{count:[0-9]+}
Fancier
`name('filtered_customers)` -> `/customers/{field:[a-z]+}/{value}`
// example:
/customers/country/spain // customers in Spain
/customers/created/2016-01-01 // New customers this year
Obviously, in that last example you'd have to check for valid fields and return an appropriate response if you don't support it.
NOTE: The syntax is for Slim Framework 3.0. Adjust for version 2.0 accordingly.
Upvotes: 0