Question

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.

Was it helpful?

Solution

I suggest you use registry method.. ohbtw $app->config($ptions); should be $app->config($options);

as for "registry", I use the following class:

<?
class Registry {
  private static $data;

  /**
  * Returns saved variable named $key
  * @param string $key
  * @return mixed
  */
    public static function get($key) {
      if(!empty(self::$data[$key])) {
        return self::$data[$key];
      }
      return null;
    }

  /**
  * Saves variable to registry with the name $key
  * @param string $key
  * @param mixed $value
  * @return boolean
  */
  public static function set($key, $value) {
    if(!empty($value)) {
      self::$data[$key] = $value;
        return true;
      }
      return false;
  }
}
?>

to save use

Registry::set('key', $value);

to retrieve use

Registry::get('key');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top