Welcome Guest, Not a member yet? Register   Sign In
Which Design Pattern can help me when I need send different emails in different actions
#1

[eluser]Unknown[/eluser]
Sorry for my poor English.

In my project, there are many actions (I call the function in Controller action) need to send an email to user after manipulating database. For example, when a user (account) has been created, an email need to be sent to him to welcome him; when a purchase order has been placed by a user, another email need to be sent, and so on.

Code:
<?php
class User extends Controller {

    function create() {
        // ... ...
        $this->user_model->create($user);

        // send an email
        $this->load->library('email');

        $this->email->from('[email protected]', 'Your Name');
        $this->email->to('[email protected]');
        $this->email->subject('Email Test');
        $this->email->message('Testing the email class.');

        $this->email->send();
    }
}

class Purchase_order extends Controller {
    
    function place() {
        // ... ...
        $this->order_model->create($order);
        
        // send another email
        $this->load->library('email');

        $this->email->from('[email protected]', 'Your Name');
        $this->email->to('[email protected]');
        $this->email->subject('Email Test');
        $this->email->message('Testing the email class.');

        $this->email->send();
    }
}

... ...

I don't think it is a good method to hardcode those $this->email after manipulating database via Model's API, because

* It is not a mission to the action whose mission is to manipulate database to send an email.

* The piece of code about sending an email varies frequently. For example, One day, my boss said, let's send a new type of email when a user changes his order, or we need a more beautiful email template when a user registered successfully.

* If an action does not need to send an email any more, I need to delete or comment the piece of code. Which action need to send an email, and which not, this is not configurable via a config file.

Is there a design pattern can help me to resolve this problem? I read a few documents about Observer Patter, is it suitable for my problem? Thank you.
#2

[eluser]jedd[/eluser]
Hi huyi,

I'd *probably* have this as a helper function, that you can send the key bits of data to as parameters (addressee, subject, type of mail, and so on). In there you could have a switch based on 'type' if you want to get fancy with different email types for orders, account creation and so on.

If it's the kind of thing you are likely to do from every controller, you could put this function in [url="/wiki/MY_Controller"]MY_Controller[/url] (extend the core controller).

Certainly you're on the right track by coming at the problem as wanting to not repeat these processes in various places through your project.




Theme © iAndrew 2016 - Forum software by © MyBB