I'm new to PHP and I am currently creating a PHP web application for an assignment at university. During the development I had realized that alot of elements in the user interface were being replicated in different sections of my application. For example I may have a hyperlink button in a Clients Page called 'New Client' (<a class="bigbutton" href=".......">New Client</a>) and another hyperlink button in a projects page called 'New Project' (<a "bigbutton" href=".......">New Project</a>).
Normally, I could just copy the html that constructs the buttons on the Clients Page and Change the content to suit the 'New Project' button in the projects page. Now If I was convert the hyperlink button to the tag, I would have to go to every instance of that particular button to replace the tag with a tag and if this button exists on so many pages, then updating would be time consuming.
That was just a simplistic example, then I have to think for other repeated elements across multiple pages such as breadcrumbs, list tables etc.
Is there any way to code in a way where I can actually reuse these UI elements that may be worthwhile to look at? Perhaps I could try to code each of these elements into classes, but right now I am not sure.
Any hints, pointers or resources would very helpful and appreciated.
Thanks guys.
You can make PHP functions which echo the HTML when called, optionally including some config stuff e.g.
function make_button($id, $label) {
echo '<button id="'.$id.'">'.$label.'</button>';
}
This can be done for large chunks of the page, or just small bits. Some systems I've used have a html_writer class for this sort of thing, others use render methods where you pass an object in and it'll pass back a string of HTML representing that object on a page.
Up to you which you prefer. Also good to make small functions which can be reused in larger functions like:
function make_buttons_from array($array) {
foreach ($array as $id => $label) {
$this->make_button($id, $label);
}
}
The examples here echo their output, but you can also use string concatenation to assemble the pieces. Again, your call. There's not really a right way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With