2

ログインが必要なアプリケーションのコンテンツの外にあるアクションに自由に含めることができるログイン ウィジェットを作成しようとしました。ここでの私の考えは、以前のログイン試行からのエラー メッセージを含むログイン ボックスをレンダリングするための DRY アプローチが必要であるということでした。これを有効にするために、失敗したログイン試行の結果を保存するためにFlashMessengerを利用しました。また、ウィジェットはPost/Redirect/Get パターンを使用して、ブラウザーの戻るボタンを使用するときにデータを複数回投稿する問題を回避します。

ここでの問題は、Zend_View_Helper_Actionを使用したくないということです。Zend_View_Helper_Action ヘルパーはリクエストを複製し、ディスパッチ ループの別の実行を作成するため、かなりリソースを消費します。それでは、以下のコードを見て、次のようにコードをリファクタリングする方法についてアドバイスをいただけないでしょうか。

  1. ウィジェットは任意のビュー スクリプトに含めることができます
  2. 前回のログイン試行の結果が表示されます
  3. ウィジェットがディスパッチ ループで実行を呼び出さない

現在、ログイン ウィジェットは、ビュー スクリプトで以下を呼び出すことによってレンダリングされます。

echo $this->action('auth', 'login-widget');

AuthController.php:

class AuthController extends Zend_Controller_Action {    
    // This method is invoked by Zend_View_Helper_Action to render the
    // login widget
    public function loginWidgetAction () {
        $flashMessenger = $this->_helper->flashMessenger->setNamespace('login');
        $this->view->messages = $flashMessenger->getMessages();
    }

    public function loginAction () {
        if($this->getRequest()->isPost()) {
            $result = Auth::doLogin($this->getRequest()->getPost());
            if($result->isValid()) {
                $this->_redirect('user');
            } 
            else {
                $flashMessenger = $this->_helper->flashMessenger->
                                                  setNamespace('login');
                foreach($result->getMessages() as $message) {
                    $flashMessenger->addMessage($message);    
                }
            }
        }
        // This will be changed to redirect either to the index page,
        // or the page the request originated from if available.
        $this->_redirect('');
    }
    [...]
}

/models/Auth.php:

/**
 * Model for encapsulating the actions that deals with authentication,
 * such as registering and activating users, as well as logging in and
 * logging out.
 * @todo: Refactor this to remove static methods
 */
class Auth {

    /**
     * 
     * @return Zend_Auth_Result
     */
    public static function doLogin ($credentials) {
        $authAdapter = new Auth_Adapter_DbTable(
            Zend_Db_Table::getDefaultAdapter(),
            'Users',
            'username',
            'pwdHash',
            'SHA1(CONCAT(?, salt))'
        );
        $authAdapter->setIdentity($credentials['username']);
        $authAdapter->setCredential($credentials['password']);
        $auth = Zend_Auth::getInstance();
        return $auth->authenticate($authAdapter);
}
[...]
}

/models/Auth/Adapter/DbTable.php:

class Auth_Adapter_DbTable extends Zend_Auth_Adapter_DbTable {    

    /**
     * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method 
     * is called to attempt an authenication.  Previous to this call, this
     * adapter would have already been configured with all necessary 
     * information to successfully connect to a database table and attempt
     * to find a record matching the provided identity.
     *
     * @throws Zend_Auth_Adapter_Exception if answering the authentication 
     * query is impossible
     * @see library/Zend/Auth/Adapter/Zend_Auth_Adapter_DbTable#authenticate()
     * @return MedU_Auth_Result
     */
    public function authenticate() {
        return parent::authenticate();
    }

    /**
     * _authenticateValidateResult() - This method attempts to validate that
     * the record in the result set is indeed a record that matched the 
     * identity provided to this adapter.
     * 
     * Additionally it checks that the user account is activated. 
     *
     * @param array $resultIdentity
     * @return MedU_Auth_Result
     */
    protected function _authenticateValidateResult($resultIdentity)
    {
        $result = parent::_authenticateValidateResult($resultIdentity);
        if(!$result->isValid()) { return $result; }

        $this->_checkAccountIsActivated($resultIdentity);
        $this->_checkAccountIsSuspended($resultIdentity);

        // Overwrite the username supplied by the user and instead
        // use the name supplied upon registration, i.e if the
        // user signs in as uSERNAME and registered as Username,
        // the identity is Username
        $this->_authenticateResultInfo['identity'] = 
            $resultIdentity[$this->_identityColumn]; 

        return $this->_authenticateCreateAuthResult();
    }

    protected function _checkAccountIsActivated ($resultIdentity) {
        if(!$resultIdentity['activated']) {
            $this->_authenticateResultInfo['code'] = 
                MedU_Auth_Result::FAILURE_NOT_ACTIVATED;
            $this->_authenticateResultInfo['messages'] = 
                array('The account has not yet been activated. 
                       Please click on the link provided in the 
                       activation email.');
        }
    }

    protected function _checkAccountIsSuspended ($resultIdentity) {
        if($resultIdentity['suspended']) {
            $this->_authenticateResultInfo['code'] = 
                MedU_Auth_Result::FAILURE_SUSPENDED;
            $this->_authenticateResultInfo['messages'] = 
                  array('The account has been suspended. 
                         If you feel this is a mistake, 
                         please contact our support: support@meduniverse.com');
        }
    }

    /**
     * _authenticateCreateAuthResult() - This method creates a 
     * MedU_Auth_Result object from the information that has 
     * been collected during the authenticate() attempt.
     *
     * @return MedU_Auth_Result
     */
    protected function _authenticateCreateAuthResult()
    {
        return new MedU_Auth_Result(
            $this->_authenticateResultInfo['code'],
            $this->_authenticateResultInfo['identity'],
            $this->_authenticateResultInfo['messages']
           );
    }
}

/views/scripts/auth/partials/login-widget.phtml

// The fetchForm-view helper returns a Zend_Form object. 
// The form definition (xml) is attached below in the
// code box below this one.
<div class="box">
    <h3>Login</h3>
    <?php if($this->messages) : ?>
            <ul class="errors">
                <?php foreach($this->messages as $message) : ?>
                    <li><?php echo $message ?></li>

                <?php endforeach; ?>
            </ul>
    <?php endif; ?>
    <div>
        <?php echo $this->fetchForm('user', 'login') ?>
    </div>
</div>

/application/configs/forms.xml

// Configuration of the Login form. 'user' and 'login' are 
// just keys for the view helper to return the correct form
<forms>
    <user>
        <login>
            <action value="/auth/login" />
            <method value="post" />
            <elements>
                <username>
                    <type value="text"></type>
                    <options>
                        <label value="Username" />
                        <required value="true" />
                        <validators>
                            <alnum validator="alnum" />
                            <strlen validator="StringLength">
                                <options min="6" max="45" />
                            </strlen>
                        </validators>
                    </options>
                </username>

                <password>
                    <type value="password" />
                    <options>
                        <label value="Password" />
                        <required value="true" />
                        <validators>
                            <strlen validator="StringLength">
                                <options min="6" max="20" />
                            </strlen>
                        </validators>
                    </options>
                </password>

                <submit>
                    <type value="submit" />
                    <options>
                        <label value="Log in" />
                    </options>
                </submit>
            </elements>
    </login>
4

3 に答える 3

1

私があなたの解決策を理解している限り、Zend_View_Helper_Actionヘルパーへの現在の呼び出しは、ログインフォームをレンダリングするだけです。フラッシュ メッセンジャーからログイン関連のメッセージを取得し、ログイン フォームをレンダリングするオン ビュー ヘルパーを作成してみませんか?

編集:

  1. 静的ブローカーからフラッシュ メッセンジャーを取得できます。

    $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
    $flashMessenger->setNamespace('login');
    $messages = $flashMessenger->getMessages();
    
  2. ビュー ヘルパーで新しいフラッシュ メッセンジャーをインスタンス化する必要はありません。その現在のインスタンスを取得するだけで済みます (1. を参照)。設計の観点からは、ビュー ヘルパー内でアプリケーション コンポーネントを取得することは絶対に可能であると言えます (Zend_View_Helper_Urlたとえば、静的フロント コントローラーからルーターを取得します)。カップリングを減らし、setter-dependency-injection-pattern を実装するには、次のことをお勧めします (Zend_View_Helper_Translate同様のパターンを使用してトランスレーターを取得します)。

    class My_View_Helper_Login extends Zend_View_Helper_Abstract
    {
        // [...]
        /**
         * @var Zend_Controller_Action_Helper_FlashMessenger
         */
        protected $_flash;
        /**
         * @param Zend_Controller_Action_Helper_FlashMessenger $flash
         * @return My_View_Helper_Login Provides a fluent interface
         */
        public function setFlashMessenger(Zend_Controller_Action_Helper_FlashMessenger $flash)
        {
            $this->_flash = $flash;
            return $this;
        }
        /**
         * @return Zend_Controller_Action_Helper_FlashMessenger
         */
        public function getFlashMessenger()
        {
            if ($this->_flash === null) {
                $this->_flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
            }
            return $this->_flash;
        }
        /**
         *
         */
        public function login()
        {
            $flashMessenger = $this->getFlashMessenger();
            $flashMessenger->setNamespace('login');
            $messages = $flashMessenger->getMessages();
            // [...]
         }
    }
    
  3. フラッシュメッセンジャーが必要な機能を提供する場合ではありません。たとえば、エラー メッセージ、情報メッセージ、および成功メッセージを区別する必要がある場合は、自家製のソリューションを使用することをお勧めします。

于 2009-06-09T07:34:17.267 に答える
1

もう 1 つの追加機能は、FlashMessenger を使用して任意のデータを保存できることです。だからあなたはすることができます

$flash->addMessage(array('status'=>'error','message'=> 'oops'));

そして foreach で使用

foreach($messages as $message){
echo '<div class="message '. $message['status'] .'">' . $message['message'] . '</div>'
}
于 2009-06-09T12:50:05.460 に答える
0

ViewHelper を使用してフォームをレンダリングし、ActionController を認証に使用する必要があるのではないでしょうか? これにより、2 番目のディスパッチ ループから解放されます。必要に応じて、いくつかの例を示します。

PSフォームのバリデーターが必要ですか?あなたの例には何の用途もありません。

于 2009-06-09T07:14:49.303 に答える