4

Zend Framework での最初のユーザー ログインに取り組んでいますが、Zend_Auth について少し混乱しています。それについて私が読んだすべての記事は、コントローラーで直接使用しています。しかし、私にとっては、プラグインとして機能する方が理にかなっています。

4

2 に答える 2

3

プラグインとして使用できます。唯一の欠点は、ブートストラップでプラグインを初期化すると、コントローラーの前に実行する必要があるため、すべてのコントローラーとアクションに対してプラグインが実行されることです。

Zend_Auth を拡張し、追加のメソッドを追加して認証アダプターをセットアップし、ストレージを管理することができます。その後、Your_Custom_Auth::getInstance() を呼び出して認証インスタンスを取得し、preDispatcth() 部分で認証を確認できます。認証が必要なコントローラー。

このようにして、より少ないコードで複数の場所で zend_auth を簡単に操作できます

<?php

class My_User_Authenticator extends Zend_Auth
{
    protected function __construct()
    {}

    protected function __clone()
    {}

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    // example using zend_db_adapter_dbtable and mysql
    public static function getAdapter($username, $password)
    {
        $db = Zend_Controller_Front::getInstance()
                                     ->getParam('bootstrap')
                                     ->getResource('db');

        $authAdapter = new Zend_Auth_Adapter_DbTable($db,
                                                     'accounts',
                                                     'username',
                                                     'password');

        $authAdapter->setIdentity($username)
                    ->setCredential($password)
                    ->setCredentialTreatment(
                        'SHA1(?)'
                    );

        return $authAdapter;
    }

    public static function updateStorage($storageObject)
    {
        self::$_instance->getStorage()->write($storageObject);
    }
}


// in your controllers that should be fully protected, or specific actions
// you could put this in your controller's preDispatch() method
if (My_User_Authenticator::getInstance()->hasIdentity() == false) {
    // forward to login action
}


// to log someone in
$auth = My_User_Authenticator::getInstance();

$result = $auth->authenticate(
    My_User_Authenticator::getAdapter(
        $form->getValue('username'),
        $form->getValue('password'))
);

if ($result->isValid()) {
    $storage = new My_Session_Object();
    $storage->username = $form->getValue('username');
    // this object should hold the info about the logged in user, e.g. account details
    My_User_Authenticator::getInstance()->updateStorage($storage); // session now has identity of $storage
    // forward to page
} else {
    // invalid user or pass
}

それが役立つことを願っています。

于 2011-09-18T07:13:36.803 に答える
1

ZF での「プラグイン」は、「フロント コントローラー プラグイン」だけでなく、アクション ヘルパー、ビュー ヘルパーなども意味します。

ZF の第一人者である Matthew Weier O'Phinney は、アクション ヘルパーの作成に関する優れた記事を書きました。

彼はそれを Auth ウィジェットで説明しています!

http://weerophinney.net/matthew/archives/246-Using-Action-Helpers-To-Implement-Re-Usable-Widgets.html

興味深い Q&A がたくさん扱われているので、記事のコメントを読むことを忘れないでください。

于 2011-09-18T22:08:46.477 に答える