【问题标题】:Slim Program Structure精简程序结构
【发布时间】:2011-10-06 23:28:08
【问题描述】:

我想在我的 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 路由中调用的函数,用于在登录表单上按下提交。

【问题讨论】:

  • 很难说,因为它在您实际调用authenticate 的位置不可见。从它显示的内容来看,它为什么会出错?还有什么比工作更好的呢?
  • 我添加了调用它的位置。我问是因为我通常不会看到像这样传递的“全局”或“主要”对象。

标签: php slim


【解决方案1】:

我建议你使用注册表方法.. 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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2021-05-06
    相关资源
    最近更新 更多