hyphen
hyphen

Reputation: 3440

Codeigniter make sending email DRY using library or helper?

I'm trying to get my mind around when to use custom libraries vs custom helpers vs just regular old controllers in Codeigniter. As I understand it, a custom helper should be more like small functions to accomplish simple repetitive tasks, where as a library can be a full-fledged class.

As an example, I want to use the native email class in CI, but I'm thinking I will be using this in a variety of different controllers and want it to be as "DRY" as possible. Would it make sense to abstract the code to send an email into a helper or a library? or should I just repeat it in the needed controllers? I also have a base controller. Maybe I should place the code there? It would be used often enough to be repetitive, but it's not like every controller is using it.

Per the documentation, the repetitive code I would be looking to abstract would be similar to the following:

This is my code below

$this->load->library('email');

$this->email->from('[email protected]', 'Your Name');
$this->email->to('[email protected]');
$this->email->cc('[email protected]');
$this->email->bcc('[email protected]');

$this->email->subject('Email Test');
$this->email->message('Testing the email class.');

$this->email->send();

I would be using email templates and passing a $data array to the template.

Upvotes: 0

Views: 1465

Answers (1)

Pradeep
Pradeep

Reputation: 9707

I would suggest a helper method would work great for you . Just add a custom helper in your autoload.php like this :

$autoload['helper'] = array('custom'); 

And add a send_email() method like this

function send_email() 
{
    $ci = & get_instance();
    $ci->load->library('email');

    $ci->email->from('[email protected]', 'Your Name');
    $ci->email->to('[email protected]');
    $ci->email->cc('[email protected]');
    $ci->email->bcc('[email protected]');

    $ci->email->subject('Email Test');
    $ci->email->message('Testing the email class.');

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

For more : https://www.codeigniter.com/user_guide/general/helpers.html

Upvotes: 3

Related Questions