1

For example I have a table Shops. So I have ORM model Shop.

I need a function to send email to shop owners.:

function sendEmail($body){
}

Now I want this Work:

Shop::find(1)->sendEmail('Email body to one shop')
Shop::all()->sendEmail('Send bulk email')

Where to put sendEmail function? in the ORM model?
What is the best-practive for that?

1
  • I think you're better off creating your own mailer class in line with following the single responsibility principle. I think you would just throw the method in the model though if you wanted it to work the way you've got the code above. Commented Apr 16, 2015 at 8:14

1 Answer 1

1

This should be a mail service. Ideally working towards an interface.

Something like:

$shop = Shop::where('postcode', '=', 44444)->first();
AppMailer::send($shop);
AppMailer::bulk(Shop::where('postcode', '=', 44444));

Service method, over in your service class

// Single send
function send(IMailable $mailable) 
{
    // do mail stuff here
    // the mail service doesn't even need to care if its 
    // eloquent or not
    $this->doSomething($mailable->email); 
}

// Bulk send
function bulk(Collection $mailables)
{
    foreach ($mailables as $mailable)
    {
        if($mailable instanceof IMailable) 
        {
            $this->send($mailable);
        }
    }

}

IMailable, over in your IMailer interface class

interface IMailable {
    public function getEmailAddress();
    public function getName();
}

Shop class somewhere

class Shop extends Eloquent implements IMailable {
    // bla bla your normal attributes for a shop

    // add some special attributes to statisfy the mailable contract
    public function getEmailAddress() 
    {
        return $this->email;
    }

    public function getName()
    {
        return $this->streetNumber . ' ' . $this->streetName;
    }
}

The good thing about all this is that later if you want to email Cafes as well as Shops you just need to make sure your Cafe class implements IMailable and you are laughing all the way to the shop, and well cafe.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your work. But one problem. I want to be able to send bulk emails "Shop::all()->sendEmail". How I do that? your AppMailer class, gets only the first shop. How to write the "Send" function for that?
Updated. It just loops over the collection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.