Maytrok's avatar
Level 10

Responsibility for mail templates

hello,

i am just curious. A part of an Application will send an E-Mail to an customer. The Mail markdown depends on the existing of an order in our system.

My Question is, who is responsible to define which markdown file to use. In My optionion the "build" method of the mailclass. An other option i can think about is, the class themself. In that case i must create an additional class for that state. But i think its a little bit overkill.

thanks in advance for your feedback

0 likes
3 replies
LaryAI's avatar
Level 58

In my opinion, the responsibility for defining which markdown file to use for the email should be handled by the mail class itself. One way to achieve this is by passing the necessary data to the mail class and having it determine which markdown file to use based on the existence of an order in the system.

For example, you could have a method in the mail class that checks for the existence of an order and sets a variable to the appropriate markdown file name. Then, in the build method, you can use this variable to render the correct markdown file.

Here's an example implementation:

class OrderConfirmationMail extends Mailable
{
    protected $markdownFile;

    public function __construct($order)
    {
        if ($order) {
            $this->markdownFile = 'order-confirmation';
        } else {
            $this->markdownFile = 'generic-email';
        }
    }

    public function build()
    {
        return $this->markdown($this->markdownFile);
    }
}

In this example, the OrderConfirmationMail class takes an order object as a parameter in its constructor. If the order exists, it sets the $markdownFile variable to 'order-confirmation', otherwise it sets it to 'generic-email'. Then, in the build method, it uses the $markdownFile variable to render the appropriate markdown file.

This way, the responsibility for determining which markdown file to use is encapsulated within the mail class itself, making it easier to maintain and modify in the future.

martinbean's avatar

@maytrok Follow the docs. It illustrates where you should be defining the template name.

Please or to participate in this conversation.