Zend Framework:我用什么来自动渲染来自 FlashMessenger 的消息(如果有的话)

问题描述 投票:0回答:2

我想知道我的许多页面是否会使用 FlashMessenger,自动呈现页面顶部的所有消息的最佳方式是什么(就像 SO 中的消息,告诉用户他们获得了徽章等)

php zend-framework
2个回答
3
投票

我有这个视图助手:

<?php

class Zf_View_Helper_FlashMessenger extends Zend_View_Helper_Abstract
{
    /**
     * @var Zend_Controller_Action_Helper_FlashMessenger
     */
    private $_flashMessenger = null;

    /**
     * Display Flash Messages.
     *
     * @param  string $key Message level for string messages
     * @param  string $template Format string for message output
     * @return string Flash messages formatted for output
     */
    public function flashMessenger($key = 'success',
                                   $template='<div id="flash-message" style="display:none"><p class="%s">%s</p></div>')
    {
        $flashMessenger = $this->_getFlashMessenger();

        //get messages from previous requests
        $messages = $flashMessenger->getMessages();

        //add any messages from this request
        if ($flashMessenger->hasCurrentMessages()) {
            $messages = array_merge(
                $messages,
                $flashMessenger->getCurrentMessages()
            );
            //we don't need to display them twice.
            $flashMessenger->clearCurrentMessages();
        }

        //initialise return string
        $output ='';

        //process messages
        foreach ($messages as $message)
        {
            if (is_array($message)) {
                list($key,$message) = each($message);
            }
            $output .= sprintf($template,$key,$message);
        }

        return $output;
    }

    /**
     * Lazily fetches FlashMessenger Instance.
     *
     * @return Zend_Controller_Action_Helper_FlashMessenger
     */
    public function _getFlashMessenger()
    {
        if (null === $this->_flashMessenger) {
            $this->_flashMessenger =
                Zend_Controller_Action_HelperBroker::getStaticHelper(
                    'FlashMessenger');
        }
        return $this->_flashMessenger;
    }
}

在我的控制器中我有这个:

if($form->isValid($formData))
{
   $Model = $this->getModel();
   $id = $Model->add($formData);

   $this->_helper->flashMessenger('The category has been inserted.');
   $this->_helper->redirector('list');
}

所以,在我看来,我只是回应助手:

<?php echo $this->flashMessenger(); ?>

0
投票

您可以使用 preDispatch-Plugin 将 FlashMessenger 的内容注入到您的视图中并将其输出到您的布局模板中。

© www.soinside.com 2019 - 2024. All rights reserved.