Access external variable in the beforeSend callback

Hi,

I was wondering wether there are any best practices for accessing an external variable inside the beforeSend callback. The only solution I’ve found so far is to set a global variable, which is not that elegant nor recommended.

// site/controllers/upload.php (simplified)
$newApplication;
return function ($kirby, $pages, $page) {
  global $newApplication;

  if ($kirby->request()->is('POST') == true && get('submit')) {
    $uploads = $kirby->request()->files()->get('files');
    $newApplication = $page->createChild([
      // Create child
    ]);

    foreach ($uploads as $upload) {
      $newApplication->createFile([
        // Create upload file
      ]);
    }

    $kirby->email([
      // …
      'beforeSend' => function ($mailer) {
        global $newApplication;
        $images = $newApplication->files()->template('upload');

        $index = 0;
        foreach ($images as $image) {
          $mailer->AddEmbeddedImage($image->root(), 'upload-' . $index, $image->filename(), 'base64', $image->mime());
          $index++;
        }

        return $mailer;
      }
    ]);

    // …
  }
};

Any suggestions?

Thank you in advance <3
NG

'beforeSend' => function ($mailer) use ($newApplication) {
1 Like