细长的程序结构

时间:2011-10-06 15:14:10

标签: php slim

我想在我的Slim应用程序中添加一个函数,但我对PHP不熟悉,不知道构造这样的东西的最佳方法。这不是生产就绪代码,我显然不会将我的用户名和密码硬编码到脚本中。我这样做只是为了说明这个概念。

$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();

必须将$app传递给authenticate()还是有更好的方法? authenticate()不是中间件,而是在POST路由中调用的函数,用于在登录表单上按提交。

1 个答案:

答案 0 :(得分:0)

我建议您使用注册表方法.. ohbtw $app->config($ptions);应为$app->config($options);

对于“注册表”,我使用以下类:

<?
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;
  }
}
?>

保存使用

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

检索使用

Registry::get('key');