【问题标题】:Codeigniter make sending email DRY using library or helper?Codeigniter 使用库或助手使发送电子邮件干燥?
【发布时间】:2018-12-29 13:25:21
【问题描述】:

我正在努力思考何时在 Codeigniter 中使用自定义库、自定义助手和常规旧控制器。据我了解,自定义助手应该更像是完成简单重复性任务的小函数,而库可以是一个成熟的类。

例如,我想在 CI 中使用本机电子邮件类,但我想我将在各种不同的控制器中使用它,并希望它尽可能“干”。抽象代码以将电子邮件发送到帮助程序或库是否有意义?还是我应该在所需的控制器中重复它?我也有一个基本控制器。也许我应该把代码放在那里?它会经常被重复使用,但并不是每个控制器都在使用它。

根据文档,我希望抽象的重复代码类似于以下内容:

这是我下面的代码

$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();

我将使用电子邮件模板并将$data 数组传递给模板。

【问题讨论】:

  • 辅助方法最好,因为它不使用控制器,并且无需控制器或任何其他库的帮助即可在控制器和视图中使用
  • 好吧,我想我会和一个帮手一起去。谢谢!

标签: php codeigniter email codeigniter-3 codeigniter-email


【解决方案1】:

我建议helper 方法对您很有用。只需在您的 autoload.php 中添加一个 custom 助手,如下所示:

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

并像这样添加send_email() 方法

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();
}

更多:https://www.codeigniter.com/user_guide/general/helpers.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 2015-09-06
    • 2017-12-07
    • 1970-01-01
    • 2012-07-24
    • 2013-09-06
    相关资源
    最近更新 更多