在我的路由中调用两个函数slim

问题描述:

我在调用我的路由中的两个独立函数时遇到问题。我正在使用PSR-r自动加载并创建我自己的名称空间。 请参阅以下两个函数的代码。在我的路由中调用两个函数slim

<?php 

namespace App\Controllers; 
use PHPMailer; 

class Mailer { 
    public function sendMail($request, $response) 
    { 
    echo "walking up the hill walking up the hill"; 
    } 
    public function updateDB($request, $response) { 
    echo "Sending message sending message"; 
    } 
} 

我有这两个功能,我想其他的以后叫他们在我的路线之一。我怎么能做到这一点。

查看我的路线下面我将如何调用函数?

$app->post('/confirm', function($request, $response) { 
      //sendMail 
      //updateDB 
})->setName('usersend'); 

我想先调用sendmail函数,然后使用两个单独的函数来保持我的代码更清洁后再更新数据库。

您可以将您的Mailer类加载到Slim's Dependency Container 然后将它们注入到您的路由/控制器中。 首先你Mailer类添加到容器

$container = $app->getContainer(); 
$container['Mailer'] = function ($container) { 
    return new Mailer(); 
}; 

然后你就可以在你的路由一样使用它:

$app->post('/confirm', function($request, $response) { 
    $mailer = $this->get('Mailer'); 
    echo $mailer->sendMail(); 
    echo $mailer->updateDB(); 
})->setName('usersend');