Practical Approach to Writing Classes
If you are new to writing classes you should start with what you know and then refactor it into a class. You can start out with straight forward linear code, convert the final code to functions then move from functions to a class.
Starting with linear code:
//define variables
$to = 'myemail@whateva.com';
$subject = 'This is the subject of test message';
$message = 'This is the body of the test message';
//send email
$result = mail($to, $subject, $message);
//confirm that email was sent
if($result){
echo "Email was sent.";
}else{
echo "Fail!";
}
Clean up above code using functions:
function sendMail($to, $subject, $message, $successMsg, $failMsg){
//send email
$result = mail($to, $subject, $message);
//confirm that email was sent
if($result){
$return = $successMsg;
}else{
$return = $failMsg;
}
//return status message
return $return;
}
Then we call it as follows:
//define variables $to = 'myemail@whateva.com'; $subject = 'This is the subject of test message'; $message = 'This is the body of the test message'; $successMsg = 'Email was sent.'; $failmsg = ' Fail!'; echo sendMail($to, $subject, $message, $successMsg, $failMsg);
We now have reusable code which can be invoked many times over. But still we don’t have a class. The above code should give you a pretty good idea of what you would include in your class.
Covert the above to a class
class handleMail{
//define vars
var $emailResult;
function __construct(){
//not used at the moment, but could
//be used at a later date.
}
function sendMail($to, $subject, $message){
//send email
$this->emailResult = mail($to, $subject, $message);
}
function mailError($successMsg, $failMsg){
//confirm that email was sent
if($this->emailResult){
$return = $successMsg;
}else{
$return = $failMsg;
}
return $return;
}
}
Then call the above with:
$email = new handleMail;
$email->sendMail('myemail@whateva.com', 'This is the subject of test message', 'This is the body of the test message');
echo $email->mailError('Email was sent.', 'Fail'); //notice that the class internally ties this method to the sendMail.
We now have a class which can be extended to add more functionality.
disclaimer: The example is not intended as an ideal example of an email class. It is only for illustrating the process of going from linear code to class.
Tags: PHP

