Slim 4 flash message addMessageNow point?

What is the point of using the addMessageNow method with in slim flash package?

 if (!$totalUnits) {
            $this->messages->addMessageNow('warning', 'Complex unit amount need to be update first.');
        }

        
        dump($users, $units, $totalUnits, $this->messages->getMessages(), $_SESSION);

The addMessage adds to the next request and into the session and thats fine works 100% but now the request is already happened so the only other why is to add the message as a view param

if (!$totalUnits) {
            $this->messages->addMessageNow('warning', 'Complex unit amount need to be update first.');
        }

         dump($users, $units, $totalUnits, $this->messages->getMessages(), $_SESSION);

        return $this->view->render($response, '/secure/units/manage_units.twig', compact(
$this->messages->getMessages()
));

so i can just use a messageVar locally and pass that…?

Hi @FvsJson

I also use the Messages class. As far as I understand adds “addMessage” an entry in the $_SESSION[‘slimFlash’] which gets read on the next request. So if you call getMessages() in the same request you won’t get anything.
“addMessageNow” doesn’t store the entry into the Session but into the class properties. So if you call getMessages() on the same request, the message will be there.

I also use Twig and I set the Message class as a global variable in Twig.

$view->getEnvironment()->addGlobal('flash', $container->get(Messages::class));

In the Twig Template I get the messages like this:

{% if flash.getMessages() %}
    {% if flash.getMessage('error') %}
        <ul class="flash alert alert-danger fade show">
            {% for msg in flash.getMessage('error') %}
            <li>{{ msg }}</li>
            {% endfor %}
        </ul>
    {% endif %}
    {% if flash.getMessage('success') %}
        <ul class="flash alert alert-success fade show">
            {% for msg in flash.getMessage('success') %}
            <li>{{ msg }}</li>
            {% endfor %}
        </ul>
    {% endif %}
{% endif %}

So if I return a redirect after adding the message I use addMessage() and if I return view->render after adding the message I use addMessageNow().

Hi Philipp thanks for the replay but that’s my whole point the addMessageNow method is little pointless in my case. Maybe if you want to add the message now and then route to author controller or method and use the message there makes more sense but ya…

Well for me the advantage is, that I have my Twig-Template above included in all pages where I possibly want to show messages. Then in the code I just have to write flash->addMessage() if I call a redirect or flash->addMessageNow() if I render a template. So I don’t have to check for different messages in Twig.
But of course you can also send the message as variable with the render method.