I wanted to add a function to my Slim application but I’m not familiar enough with PHP to know the best way to structure something like this. This is not production ready code and I obviously will not be hard coding my username and password into the script. I made this simply to illustrate the concept.
$options = array(
'username' => 'admin',
'password' => 'password'
);
$app = new Slim(array(
'view' => new TwigView()
));
$app->config($ptions);
function authenticate($app, $username, $password) {
if($username==$app->config('username') && $password==$app->config('password')){
return true;
} else {
return false;
}
}
$app->get('/', function () use ($app) { // ... }
// ... other routes
$app->post('/login', function() use ($app) {
$username = $app->request()->post('username');
$password = $app->request()->post('password');
if(authenticate($app, $username,$password)) {
$app->redirect('/');
}
$app->redirect('/login');
});
$app->run();
Does it make sense to have to pass $app to authenticate() or is there a better way? authenticate() would not be middleware, but a function called in the POST route for pressing submit on a login form.
I suggest you use registry method.. ohbtw
$app->config($ptions);should be$app->config($options);as for “registry”, I use the following class:
to save use
to retrieve use