0

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('your@example.com', 'Your Name');
$this->email->to('someone@example.com');
$this->email->cc('another@another-example.com');
$this->email->bcc('them@their-example.com');

$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.

Pradeep
  • 9,667
  • 13
  • 27
  • 34
hyphen
  • 2,368
  • 5
  • 28
  • 59
  • 1
    a helper method would be best to this, since it uses no controller and it can be used both in controller and view without the help of controller or any other library – Pradeep Jul 21 '18 at 12:28
  • Ok, I guess I'll go with a helper then. Thanks! – hyphen Jul 21 '18 at 13:08

1 Answers1

3

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('your@example.com', 'Your Name');
    $ci->email->to('someone@example.com');
    $ci->email->cc('another@another-example.com');
    $ci->email->bcc('them@their-example.com');

    $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

Pradeep
  • 9,667
  • 13
  • 27
  • 34