In 2022, I inherited a product. Inheriting, in this case, means I started working on it. Still, because the project was written years ago (about four years), my first responsibility was to upgrade the code from procedural to OOP and then make changes across the entire project – which basically meant re-writing.
And, of course, as a live product with users, I had to do it gradually and only push to live gradually, making sure users don’t experience too many changes simultaneously.
One of the changes I made was to change how email is applied. I used the Symphony Email package because it was easy to set up (unlike PHPMailer). Of course, anything I used would have been better than the default PHP mail function the project had implemented before.
The package itself is easy to set up and get working. You can check the official documentation here. However, what I’d like to share is this little piece of code:
private function loadTemplate():void{
$this->template = file_get_contents( "./views/templates/email/{$this->type}.html");
$this->template = str_replace('{NAME}', $this->user_name, $this->template);
$this->template = str_replace('{EMAIL}', $this->user_email, $this->template);
$this->template = str_replace('{TITLE}', $this->subject, $this->template);
$this->template = str_replace('{MESSAGE}', $this->message, $this->template);
if($this->link) {
$this->template = str_replace('{LINK}', $this->link, $this->template);
}
}
With this code snippet, I can load different email templates depending on the type of email I am sending. The template is a basic HTML file, and the code is self-explanatory, but here is a bit of explanation for those who might need it:
- On line 89, I load the HTML file content into a property (variable) and then:
- Lines 90 – 93 replace certain parameters in the file with the correct data.
- Lines 95 – 97: Put a link in the email if there is a link.
Yep, it’s that easy. This way, I can use the class like this:
A little explaanation:
- Line 14 imports the class
- Line 18 initialises the class with the correct template type (I have an email template called welcome)
- Lines 19 – 21 sets the needed parameters
- Line 22 sends the email
If you’d like to see the full code, I have made it available on GitHub. Don’t forget to give it a star if you find it useful.
Happy coding!