Laminas-cli controller plugin injection

I used laminas-cli to execute my scripts in console and everything is ok.
The problem I have is to use my mail controller plugin which works fine.
here are my code ;

My console class :

<?php

declare(strict_types=1);

namespace Commun\Scripts;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;

class ConsoleGenerationRelances extends Command
{
    /** @var string */
    private $mapper;
    private $cronEnv;    
    private $MAIL;    
    protected static $defaultName = 'console-generation-relances';
    
    public function __construct($mapper=[],$cronEnv=[]){
        $this->mapper = $mapper;
        $this->cronEnv = $cronEnv;        
        //$this->MAIL = $MAIL;        
        parent::__construct();
    }

    protected function configure() : void
    {
        $this->setName(self::$defaultName);
        //$this->addOption('name', null, InputOption::VALUE_REQUIRED, 'Module name');
    }

    protected function execute(InputInterface $input, OutputInterface $output) : int
    {
        $mapperAbonnementPrestation = $this->mapper['mapperAbonnementPrestation'];
        $relances = $mapperAbonnementPrestation->getDataRelancesForConsole();        
        $output->writeln('Démarrage du script des relances |~>  : '.date('Y-m-d H:i:s'));
        $nbreJourAvantRelance = $this->cronEnv['cron'];  
        //$output->writeln(json_encode($this->MAIL));
        foreach ($relances as $relance){            
            if(empty($nbreJourAvantRelance) || empty($relance['dateLimitePaiement']) ){         // Si parametre de relance non defini alors on saute l'execution       
                continue;
            }
            $now = strtotime(date('Y-m-d H:i:s')); // or your date as well
            $dateLimitePaiement = strtotime($relance['dateLimitePaiement']);
            $datediff = $now-$dateLimitePaiement;
            $nombreJour = abs(round($datediff / 86400));            
            if($nombreJour<=$nbreJourAvantRelance){ // On envoie le mail
                //$this->MAIL->envoiMailCreationCompte(['emailTo'  => ['nanguisamuel@gmail.com'],'nomPrenoms'  => 'Samuel NANGUI','motDePasse'  => 'test']); //On envoie un mail au user avec ses parametres               
            }
        }
        $output->writeln('Fin du script des relances |~>  : '.date('Y-m-d H:i:s'));
        return 0;
    }
}

My dependencies.global.php

<?php

return [
    'service_manager' => [
        'factories'  => [
            \Commun\Scripts\CronTest::class   => \Commun\Scripts\Factory\CronTestFactory::class,
            Commun\Scripts\ConsoleGenerationRelances::class => Commun\Scripts\Factory\ConsoleGenerationRelancesFactory::class,            
        ],         
    ],
    /*'dependencies'  => [
        \Commun\Controller\Plugin\GestionMailPlugin::class => Commun\Factory\Controller\Plugin\GestionMailPluginFactory::class,        
    ],
    'aliases'  => [
        'MAIL' => \Commun\Controller\Plugin\GestionMailPlugin::class       
    ],*/
];

My console code Factory

<?php

declare(strict_types=1);

namespace Commun\Scripts\Factory;

use Commun\Scripts\ConsoleGenerationRelances;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\Factory\FactoryInterface;
//use Commun\Controller\Plugin\NslabsMail;
class ConsoleGenerationRelancesFactory implements FactoryInterface
{
    /**
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param null|array $options
     * @return $requestedName Entity
     */
        
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {        
        $mappers = ['mapperAbonnementPrestation' => $container->get('TABONNEMENTPRESTATION')];        
        return new ConsoleGenerationRelances($mappers,$container->get('config'));
        
    }     
}

My mail controller plugin

<?php

/**
    * @module     Commun
    * @subpackage Controller/Plugin
    * @author     Samuel NANGUI <nanguisamuel@gmail.com>
    * @copyright  Copyright (c) 2020 Nslabs
    */

namespace Commun\Controller\Plugin; 
use Laminas\Mvc\Controller\Plugin\AbstractPlugin;
use Commun\Controller\Plugin\NslabsMail;


class GestionMailPlugin extends AbstractPlugin
{
    
    
    protected $classMail;

    function __construct(NslabsMail $_classMail)
    {
        $this->classMail = $_classMail;        
    }
    
    
    public function test($to){
        $this->classMail->ajouterDestinataire($to);
        $this->classMail->ajouterReplyTo('nanguisamuel@gmail.com');
        $this->classMail->ajouterExpediteur('nanguisamuel@gmail.com');
        $message = $this->classMail->enteteEmail()
                .'Cher/Chère SAM,<br/><br/>'
                ."Ca marche avec PHP MAILER.<br/><br/>"                                 
                ."<br/><br/>"                                    
                .$this->classMail->ajoutSignature(); 
                
        try{
            $this->classMail->setMessage('TEST LAMINAS', $message);
            $this->classMail->send();               
        } catch (\Exception $e){
            //var_dump($e->getMessage());
            //die();
        }
        $this->classMail->clearAllAddressesAndAttachments();
    }
       
    public function envoiMailCreationCompte($params){
        
        $this->classMail->ajouterDestinataire($params['emailTo']);
        $this->classMail->ajouterReplyTo('nanguisamuel@gmail.com');
        $this->classMail->ajouterExpediteur(EXPEDITEUR_MAIL_GENERAL);
        $this->classMail->ajouterDestinaireCopieCarbone(['nanguisamuel@gmail.com']);
        $message = $this->classMail->enteteEmail()
                .'Cher/Chère ' . $params['nomPrenoms'] . ',<br/><br/>'
                ."Nous avons le plaisir de vous informer de la création de votre compte utilisateur avec le mot de passe suivant : ".$params['motDePasse']." <br/><br/>"                 
                ."Nous vous recommandons de le changer dès votre première connexion a la platefome.<br/>"                                           
                ."<br/><br/>"                                      
                .$this->classMail->ajoutSignature(); 
                
        try{
            $this->classMail->setMessage('['.PORTAIL.'] Confirmation de création de compte utilisateur', $message);
            $this->classMail->send();            
        } catch (\Exception $e){
            //var_dump($e->getMessage());
            //die();
        }
        $this->classMail->clearAllAddressesAndAttachments();
        
    }    
}

And I would like to know also how to handle errors or exceptions

1 Like

Problem solved by creating a new class with PHPMailer

It is a controller plugin and therefore designed for use in a controller only.

And the problem with your controller plugin: to send messages in another place like a CLI command you must create something new or you must duplicate code.

Instead of:

MyController
{
    public function someAction()
    {
        $this->service->doSomething();
        $this->sendMail();
    }
}
MyCommand
{
    public function execute()
    {
        $this->service->doSomething();
        $this->sendMail();
    }
}

You can use:

MyService
{
    public function doSomething()
    {
        // …

        $this->sendMail();
    }
}

Another option is to trigger an event in your controller, command or service which can be handled in different ways, because maybe tomorrow the information will no longer be sent by email, but via a Telegram bot.
Find a way that is independent of the framework, then it will also help with an upgrade or migration.