Doubt with dynamic layouts

2

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

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

$logado = FALSE;

If the user is logged in, I assign TRUE and within the view's, I make 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 too, for example, logged in user, can save a new information in a form, not logged in user, just view the result of the selected information already saved.

My question is: Is this a good practice?

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

    
asked by anonymous 18.07.2014 / 18:51

1 answer

3
Dynamic views , 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 one, but can easily lead to code that is difficult to understand, maintenance-prone and error-prone.

Template Engines

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

Some mechanisms allow templates to "compile" to solve the performance problem, but this will require extra care in implementation.

I particularly like the templates approach.

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 that way.

The advantage is that there is a somewhat degree of reuse of code, but because of the great abstraction and complexity you can easily lose control of what you are doing, as well as render tasks that once were trivial in something that depends on a relative knowledge depth 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 system logic.

A very simple example of how to use the PHP language itself as a type of template , thus avoiding the large number 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; ?>
    
18.07.2014 / 19:30