Calling member function of other controller in zend framework 3 for sending email?

75 Views Asked by At

Calling member function of other controller in zend framework3?

2

There are 2 best solutions below

0
On

You should write a mailer class and inject it in to action and send mails on it. Probably you will need mailer class in few actions so an aware trait would be nice so you will not have to inject it on every action on __construct method. I think something like that can solve problem, so you can use your mailer service in anywhere you want. Just don't forget to inject it.

interface MailServiceInterface
{
    public function send(string $to, string $from, string $subject, string $body, array $headers = []);
}

trait MailServiceAwareTrait
{
    /**
     * @var \Infrastructure\Mailer\MailServiceInterface
     */
    protected $mailService;

    public function setMailService(MailServiceInterface $mailService)
    {
        $this->mailService = $mailService;
    }

    public function getMailService(): MailServiceInterface
    {
        return $this->mailService;
    }
}

class myAction extends AbstractActionControl
{
    use MailServiceAwareTrait;

    public function processAction()
    {
        $this->getMailService()->send($to, $from, $subject, $body);
    }
}
0
On

"Sending emails" is a service, so typically it should be in a separate model file (aka service file), not in the controller. While you actually can put it in a controller as a function, but that will simply means you are completely misusing the MVC concept itself.

Anyway, I'll answer how to do it but I strongly do NOT recommend it. In your controller (for example, IndexController), this is what you can do:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController {
    public function indexAction() {
        // This below line will call FooController's barAction()
        $otherViewModel = $this->forward()->dispatch(\Application\Controller\FooController::class, ['action'=>'bar']);
        $otherViewModel->setTemplate('application/foo/bar');// you must set which template does this view use
        return $otherViewModel;
    }
}