For my webapp, I need to make the navbar status-aware and adapts to many combinations: whether the user is logged-in or not, its role (admin, user, guest, ...), etc.
Injecting multi-nested if
s and function calls in HTML makes me cringe and I want to keep my code as clean and DRY as possible, for easy maintenance.
So, I thought of writing a function to automate the process. Something that would look like this :
public function insertButtons(array $buttons) {
foreach($buttons as $button) {
echo "<a href='" . $button['url'] . "'>". $button['text'] . "</a>";
}
}
So that I can craft the $buttons
in the Controller
:
if($_SESSION['loggedin']) {
$buttons[] = array('url' => '/profile', 'text' => $_SESSION['username']);
$buttons[] = array('url' => '/logout', 'text' => 'Log out');
} else {
// ...
}
And then inject them in the HTML:
<div class="nav navbar">
<!-- ... -->
<?php insertButtons($buttons); ?>
<!-- ... -->
</div>
The drawback for such a solution is, of course, the lack of flexibility.
Are there any known patterns to be used in these situations? If yes, what are they or where can I find information about them. If not, is my pseudo-code a viable solution?
Aucun commentaire:
Enregistrer un commentaire