PHP code example of jlorente / yii2-command-handler

1. Go to this page and download the library: Download jlorente/yii2-command-handler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jlorente / yii2-command-handler example snippets


    // ... other configurations ...
    "modules" => [
        // ... other modules ...
        "command" => [
            "class" => "jlorente\command\Module"
        ]
    ]

namespace common\models;

use yii\db\ActiveRecord;
use jlorente\command\base\Receiver;

class Group extends ActiveRecord implements Receiver {

    public function sendEmailToUsers() {
        //Implementation of the send email to group users method goes here.
    }
}

//In our example we will extend the \jlorente\command\db\Command because Group extends from \yii\db\ActiveRecord

namespace common\models\commands;

use jlorente\command\db\Command;

class GroupSendEmailCommand extends Command {

    /**
     * @inheritdoc
     */
    public function run() {
        $this->getReciver()->sendEmailToUsers();
    }
}

namespace frontend\controllers;

use yii\web\Controller;
use yii\web\NotFoundHttpException;
use common\models\commands\GroupSendEmailCommand;
use jlorente\command\db\CommandMapper;

class GroupController extends Controller {
    
    public function actionSendEmail($groupId) {
        $group = Group::findOne($groupId);
        if ($group === null) {
            throw new NotFoundHttpException();
        }
        $command = new GroupSendEmailCommand();
        $command->setReceiver($group);
        CommandMapper::map($command); //Enqueues the command
    }
}

namespace common\models;

use yii\db\ActiveRecord;
use jlorente\command\base\Receiver;
use jlorente\command\behaviors\CommandGeneratorBehavior;
use common\models\commands\GroupSendEmailCommand;

class Group extends ActiveRecord implements Receiver {

    public function sendEmailToUsers() {
        //Implementation of the send email to group users method goes here.
    }
    
    public function behaviors() {
        return array_merge(parent::behaviors(), [
            // ... other behaviors ...
            [
                'class' => CommandGeneratorBehavior::className(),
                'commands' => [
                    self::EVENT_BEFORE_SAVE => GroupSendEmailCommand::className(),
                ],
                'condition' => function ($model) {
                    return $model->isAttributeChanged('state');
                }
            ]
        ]);
    }
}

use jlorente\command\base\CommandProcessor;

$processor = new CommandProcessor();
$processor->run();

$processor->setMode(CommandProcessor::MODE_QUEUE)

$processor->run(10, false); //This will limit the commands to 10 and won't restore the erroneous ones.
bash
$ php composer.phar