2011-10-06 38 views
1

我想給我的Slim應用程序添加一個函數,但我對PHP不太瞭解,不知道構建這種類型的最佳方式。這不是生產就緒代碼,我顯然不會將我的用戶名和密碼硬編碼到腳本中。我只是爲了說明這個概念。Slim程序結構

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

是否有意義有通過$appauthenticate()或是否有更好的辦法? authenticate()不會是中間件,而是在POST路由中用於在登錄表單上按下提交的函數。

+0

很難說,因爲它在你實際稱之爲「認證」的地方不可見。從它顯示的內容來看,它爲什麼會出錯?有什麼比工作更好? – hakre

+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');