Codeigniter 使用库或助手使发送电子邮件变干?
Codeigniter make sending email DRY using library or helper?
我正在考虑何时使用自定义库、自定义帮助程序以及 Codeigniter 中的常规旧控制器。据我了解,自定义助手应该更像是完成简单重复性任务的小函数,而库可以是成熟的 class。
例如,我想在 CI 中使用本机电子邮件 class,但我想我会在各种不同的控制器中使用它,并希望它像"DRY" 尽可能。抽象代码以将电子邮件发送到助手或库是否有意义?或者我应该在需要的控制器中重复它吗?我还有一个基本控制器。也许我应该把代码放在那里?它的使用频率足以重复,但并不是每个控制器都在使用它。
根据文档,我希望抽象的重复代码类似于以下内容:
下面是我的代码
$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
数组传递给模板。
我建议 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
我正在考虑何时使用自定义库、自定义帮助程序以及 Codeigniter 中的常规旧控制器。据我了解,自定义助手应该更像是完成简单重复性任务的小函数,而库可以是成熟的 class。
例如,我想在 CI 中使用本机电子邮件 class,但我想我会在各种不同的控制器中使用它,并希望它像"DRY" 尽可能。抽象代码以将电子邮件发送到助手或库是否有意义?或者我应该在需要的控制器中重复它吗?我还有一个基本控制器。也许我应该把代码放在那里?它的使用频率足以重复,但并不是每个控制器都在使用它。
根据文档,我希望抽象的重复代码类似于以下内容:
下面是我的代码
$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
数组传递给模板。
我建议 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