Resuable HTML Code PHP UI Elements

I am new to PHP and I am currently building a PHP web application for university studies. During development, I realized that many elements in the user interface are replicated across different sections of my application. For example, I might have a hyperlink button on the clients page called "New Client" ( <a class="bigbutton" href=".......">New Client</a>

) and another hyperlink button on the projects page called "New Project" ( <a "bigbutton" href=".......">New Project</a>

).

Usually I could just copy the html that creates the buttons on the Clients page and change the content to match the New Project button on the projects page. Now, if I were to convert a hyperlink button to a tag, I would have to go to every instance of that particular button to replace the tag with a tag, and if that button exists on so many pages then updating will be time consuming.

It was just a simplified example, then I have to think about other repeating elements across multiple pages like bread crumbs, table tables, etc.

Is there any way I can code the code so that I can reuse these UI elements that might be worth looking at? Perhaps I could try to code each of these elements into classes, but I'm not sure right now.

Any hints, pointers or resources would be very helpful and appreciated.

Thanks guys.

+3


source to share


2 answers


You can create PHP functions that invoke HTML when called, optionally including some configuration elements, such as.

function make_button($id, $label) {
    echo '<button id="'.$id.'">'.$label.'</button>';
}

      

This can be done for large chunks of the page or small bits. Some systems I have used have an html_writer class for this kind of thing, others use render methods where you pass in an object and it will pass an HTML string representing that object on the page.



It is up to you what you prefer. It's also helpful to create small functions that can be reused in larger functions, such as:

function make_buttons_from array($array) {
    foreach ($array as $id => $label) {
        $this->make_button($id, $label);
    }
}

      

The examples here reflect their output, but you can also use string concatenation to assemble snippets. Again, your call. There really isn't.

+3


source


There are all sorts of specific possibilities here, but the basic approach is to have a set of templated functions or methods in the class that create all the common elements of your pages. Anything that divides (or has only minor changes) from page to page is defined once in those functions, and you simply call functions from each page, providing enough information to allow the function to distinguish how it should display its content depending on details of the page calling it.



If you have a change to a shared item, you just go to the function and change it, and this way it gets copied across all pages.

+1


source







All Articles