UI Component Pattern for a Simple PHP website

PHP UI component patterns

Reusable components are a staple of modern front-end web development. On my simple PHP website, I wanted to build user interface pieces, and reuse them across multiple pages. When I was creating a new page for a newsletter signup form, I realized that I was repeating a lot of code for a contact form section that is displayed on almost every page.

Contact form section

This website is so simple, it does not use any modern framework. The contact form itself is powered by AWS SES.  I created a directory in the root folder of the website called “components”. There, I put files containing HTML, CSS, and JavaScript code that would otherwise be repeated. Implementing this pattern will help my code adhere to the DRY (don’t repeat yourself) principle, and make it quicker and easier to make changes in the future. Centralizing code ensures quality and scalability.

UI component directory

Searching the code base for references to this particular HTML revealed ten instances that could be cleaned up.

searching a code base

In the new component file, I copy and paste my HTML and CSS code.  Then, I go through each of the offending files, and replace the markup with a reference:

<?php include $_SERVER["DOCUMENT_ROOT"] . '/components/contact-section.php'; ?>

I also delete any CSS and JavaScript for this section that’s on the page. At first, I tried adding the JavaScript that controls this form’s functionality to that same file. It failed because it relies on a jQuery reference that is not loaded until lower in the document. Separating the JS code into its own file, similarly named as `contact-section-js.php`, and calling it below the library reference solved the issue. That code is responsible for passing the message along to the back-end, handling UI success/error notifications, and implementing CAPTCHA to thwart bots. Since it was a lot of files were morphed, I ran a quality assurance protocol to ensure nothing broke.