slimphp / PHP-View

A Simple PHP Renderer for Slim 3 & 4 (or any other PSR-7 project)
MIT License
264 stars 60 forks source link

Unable to flush/reset reset body when calling multiple render() #89

Closed ajpgtech closed 2 years ago

ajpgtech commented 2 years ago

I created a slim4 action to send more than one email. The two emails get their output from views and sends two separate emails.

The first email is sent ok, But the second one is sent with the body of the first and second (The recipient and subject is correct.)

I have excluded the email library by debugging and tracing the values being received. I can confirm the same response body is being set,

I tried making a copy of $response. That did not change things.

The code below is a summary

public function actionContact(RequestInterface $request, ResponseInterface $response, array $args): ResponseInterface

   $form_data = (array)$request->getParsedBody();

   $notify_view_ = $this->renderer->render(
      $response,
      'emails/contactus_notify.php',
      ['form_data' => $form_data]
   );
   $notify_message = $response->getBody();
   $notify_mail = new Email('user1@domain.com, 'Subject 1', $notify_message)->send();

   // Send second email
   $thankyou_view_ = $this->renderer->render(
      $response,
      'emails/contactus_thankyou.php',
      ['form_data' => $form_data]
   );
   $thankyou_message = $response->getBody();
   $thankyou_mail = new Email('user2@domain.com, 'Subject 2', $thankyou_message)->send();
}

I figured after further debugging that the second getBody() was actually concatenating the results of the two render()s.

I tried resetting the body

$response->getBody()->write('');

but this had no effect. The second email is the concatenation of the two writes by render.

ajpgtech commented 2 years ago

The issues was fixed by using the fetch() method, which renders the template and returns the result instead of writing it to the response. (Unfortunate name for the method, I think.)

Replace

       $notify_view_ = $this->renderer->render(
          $response,
          'emails/contactus_notify.php',
          ['form_data' => $form_data]
       );
       $notify_message = $response->getBody();

by

       $notify_message = $this->renderer->fetch(
          'emails/contactus_notify.php',
          ['form_data' => $form_data]
       );
ajpgtech commented 2 years ago

case of RTFM. Closing issue.