开发者

Slim Program Structure

开发者 https://www.devze.com 2023-04-11 10:11 出处:网络
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 no

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:

<?
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');
0

精彩评论

暂无评论...
验证码 换一张
取 消