Implement Command Pattern for Complex Operations

Implement Command Pattern for Complex Operations

Use the Command pattern to encapsulate requests as objects, allowing for parameterization of clients with queues, requests, and operations.

interface CommandInterface
{
    public function execute();
}

class SendEmailCommand implements CommandInterface
{
    private $recipient;
    private $subject;
    private $body;

    public function __construct($recipient, $subject, $body)
    {
        $this->recipient = $recipient;
        $this->subject = $subject;
        $this->body = $body;
    }

    public function execute()
    {
        // Logic to send email
        echo "Sending email to {$this->recipient} with subject '{$this->subject}'";
    }
}

class CommandInvoker
{
    private $command;

    public function setCommand(CommandInterface $command)
    {
        $this->command = $command;
    }

    public function executeCommand()
    {
        $this->command->execute();
    }
}

// Usage
$invoker = new CommandInvoker();
$invoker->setCommand(new SendEmailCommand('user@example.com', 'Hello', 'This is a test email'));
$invoker->executeCommand();
← Back to Tips List