# Laminas-cli controller plugin injection

**URL:** <https://discourse.laminas.dev/t/laminas-cli-controller-plugin-injection/2720>\
**Category:** Components & MVC\
**Tags:** laminas-mvc, laminas-cli\
**Created:** [January 15, 2022, 4:24pm UTC](https://discourse.laminas.dev/t/laminas-cli-controller-plugin-injection/2720 "2022-01-15T16:24:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ebuddy](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/ebuddy/32/1536_2.png) [@ebuddy](https://discourse.laminas.dev/u/ebuddy)\
**Post date:** [January 15, 2022, 4:24pm UTC](https://discourse.laminas.dev/t/laminas-cli-controller-plugin-injection/2720/1 "2022-01-15T16:24:49Z")

</div>

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 :

```auto
<?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

```auto
<?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

```auto
<?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

```auto
<?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

---

<div class="post-metadata">

**Author:** ![ebuddy](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/ebuddy/32/1536_2.png) [@ebuddy](https://discourse.laminas.dev/u/ebuddy)\
**Post date:** [January 20, 2022, 7:50pm UTC](https://discourse.laminas.dev/t/laminas-cli-controller-plugin-injection/2720/2 "2022-01-20T19:50:30Z")

</div>

Problem solved by creating a new class with PHPMailer

---

<div class="post-metadata">

**Author:** ![froschdesign](https://yyz2.discourse-cdn.com/flex032/user_avatar/discourse.laminas.dev/froschdesign/32/38_2.png) [@froschdesign](https://discourse.laminas.dev/u/froschdesign)\
**Post date:** [January 21, 2022, 8:46am UTC](https://discourse.laminas.dev/t/laminas-cli-controller-plugin-injection/2720/3 "2022-01-21T08:46:55Z")

</div>

> [@ebuddy](#):
>
> The problem I have is to use my mail controller plugin which works fine.

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:

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

```

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

```

You can use:

```php
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.
