Doubt with dynamic layouts

Asked

Viewed 81 times

2

I usually mount the views of the php applications I use with conditional operators.

For example, not logged in user, Seto an initial variable in the session:

$logado = FALSE;

If the user is logged in, attribute TRUE and within the view’s, I turn some dynamic things, for example, the login button.

if (!$logado) {
    //exibe formulário de login
} else {
    //Exibe mensagem: bem vindo user xxxx, clique aqui para efetuar logoff.
}

And I use this in other things also, for example, logged in user, can save a new information in a form, not logged in user, just view the result of select of already saved information.

My question is: This is good practice?

Utilise if in the context of structuring html and making it adaptable according to variables set in session?

1 answer

3


Beget views dynamics, according to certain parameters, is a challenge in any language.

There are basically three main approaches to dealing with this:

Scripts

The approach of mixing scripts with HTML is the most efficient, but can easily lead to code difficult to understand, maintain and error-prone.

Template Engines

Use a mechanism of templates helps separate logic from presentation. The side effect is performance, since the templates need to be interpreted to generate the output.

Some mechanisms allow the "compilation" of templates to solve the problem of performance, but this will require further care in implementing.

Particularly I like the approach based on templates.

Components

Some frameworks generate views through components, which are actually a collection of objects that encapsulate the generated HTML.

In PHP this is not as common as in Java, for example, but if I remember well Yii works this way.

The advantage is that there is a degree of code reuse, but due to the great abstraction and complexity you can easily lose control of what you’re doing, in addition to making tasks that would once be trivial into something that depends on a relatively deep knowledge of the framework.

Considerations

There is no problem in using some ifs or loops in the code, as long as you can separate it from the logic of the system.

A very simple example of how to use the PHP language itself as a type of template engine, thus avoiding the large amount of classes included when using frameworks, can be seen in some templates of Wordpress. Example:

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>    
    <!-- do stuff ... -->
    <?php endwhile; ?>
<?php endif; ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.