[eluser]chobo[/eluser]
Hi, I just finished refactoring please let me know what you think. I moved the email settings into a custom config file, and broke the controller into more discrete functions. Hi Rick, you mentioned that I should move my email into a library, could you please elaborate on that, I'm still kind a super newb, so I don't know how to take advantage of that or what the benefits are. Anyways here is my latest revision, any feedback is appreciated.
Code:
<?php
require_once 'template_engine.php';
class Contact extends TemplateEngine {
/* Load email config and helpers */
public function __construct()
{
parent::__construct();
$this->config->load('email_config');
$this->load->helper(array('form', 'url'));
$this->load->library('validation');
}
/* Displays default page */
public function index() {
parent::set_section('header', $this->load->view('layouts/default_header', $this->header, true));
parent::set_section('left', $this->load->view('left_ad_view', '', true));
parent::set_section('footer', $this->load->view('layouts/default_footer', '', true));
// run validation and see if it passes
if ($this->validate() == FALSE) {
parent::set_section('content', $this->load->view('contact_view', '', true));
} else {
$error['message'] = $this->sendMail();
parent::set_section('content', $this->load->view('message_sent_view', $error, true));
}
parent::build_template();
}
/* Runs validation rules (returns true or false) */
private function validate()
{
//set rules
$rules['name'] = "required|min_length[2]|max_length[35]";
$rules['email'] = "required|valid_email";
$rules['message'] = "required|min_length[10]|max_length[1000]";
$this->validation->set_rules($rules);
// if it fails set the fields
$fields['name'] = 'Name';
$fields['email'] = 'Email Address';
$fields['message'] = 'Message';
$this->validation->set_fields($fields);
return $this->validation->run();
}
/* Send email off */
private function sendMail()
{
$from_name = ($_POST['name']);
$from_address = ($_POST['email']);
$subject = ($_POST['subject']);
$body = ($_POST['message']);
require_once EXT_LIB . 'phpmailer/class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = $this->config->item('smtp_server'); // SMTP server
//$mail->Username = $this->config->item('user');;
//$mail->Password = $this->config->item('password');;
//$mail->SMTPAuth = $this->config->item('auth'); // turn on SMTP authentication
$mail->FromName = $from_name; // Sets the name of the emailer
$mail->From = $from_address; // Sets the email address of the sender
$mail->AddAddress($this->config->item('to')); // Sets the To Address
$mail->Subject = $subject; // Sets the subject heading
$mail->Body = $body;
$mail->WordWrap = 50;
//init $message var?
if(!$mail->Send())
{
$message = "There was a problem sending your email, please try again later.";
$message .= "Mailer Error: " . $mail->ErrorInfo;
}
else
{
$message = "Your message has been sent successfully!";
}
return $message;
}
}
?>