Is it good practice to mix Php and Html?

15

I see that in python, there is the bottle for example that does the same thing as what I intend to do then ...

I'm new to web practice, student indeed and would like to know if I can use php and html in the same place, wanted to know if this is a default, not recommended, or whatever. There is only Body because I intend to use Ajax and load the posts without refreshing the page.

Follow the example code:

<?php
    function __autoload($class_name){
        require_once  $class_name . '.php';
    }
?>

<body>
<?php 
    $noticia = new Noticia();
?>
<div id="posts">
<?php foreach ($noticia->findAll() as $value): ?>
    <div style=" word-wrap: break-word; width: 400px; ">

    <?php echo $value->mensagem; ?> <br><br><br><br>

    </div> 
<?php endforeach; ?>
</body>
    
asked by anonymous 06.05.2015 / 01:00

8 answers

16

It's a pattern.

Not recommended.

Not good practice.

In many cases it does.

There is a principle in software design called separation of concerns , which dictates that each part of the system cares about only one thing.

In your case, the principle would determine that a separate part of your code should take care of presentation , another party should take care of the structure of what is being presented, you should take care of the content shown, and you may still have separate parts to take care of presentation logic and business logic .

If you want to follow this principle, you should have html files, css files, php files ... each with a different responsibility or "concern."

This principle is widely accepted and it is believed that its failure to observe large or complex applications results in the difficulty (cost increase) of system maintenance and evolution and software quality reduction.

    
06.05.2015 / 02:00
10

To say whether or not it's a good practice depends heavily on opinion.

This is a practice used, for example, in Wordpress template files, which mix HTML and PHP. In addition, by the PSR-1 standard proposed by the PHP Framework Interop Group (various frameworks have already joined - Joomla, Laravel Yii, etc.):

  

Files MUST or declare symbols (classes, functions, constants, etc.) or cause side effects (eg generate output, modify settings in php.ini, etc.), but DO NOT do both.

This way you should only worry about not defining functions / classes in your example file to respect the default.

More information on link (partially translated)

Note that this is not a rule. If the site you are developing is more complex than just a blog it is recommended to do a split using MVC or a template library as suggested in the other response.

    
06.05.2015 / 14:10
7

I find it quite normal to use these "web practices", but that depends on the way the programmer finds it easier to develop and do future maintenance. Or you can make a function for every thing that the application does (which is easier to do for maintenance): main.php

class News { ...
 public function getAllNews() {
      foreach ($noticia->findAll() as $value) {
           echo $value->mensagem; ?>
      }
 }

}

index.php:

<?php
function __autoload($class_name){
    require_once  $class_name . '.php';
}   $noticia = new Noticia(); ?>

<body>
<div id="posts">
<?php $noticia->getAllNews(); ?>
</body>

A practice widely used by programmers is the MVC: In which a view receives the variables to be used, and the functions are usually in the View separate class. link

    
06.05.2015 / 01:29
7

It is not recommended to mix PHP with HTML, I really like, and even encourage my students, to use a library called Smarty, with it we can manage templates without mixing php with HTML. Here's an example:

NoticiaView.php

class NoticiaView {
/**
 * @all controllers must contain an index method
 */
function index(){

    $smarty = new \Smarty;

    $smarty->debugging = false;
    $smarty->caching = false;
    $smarty->cache_lifetime = 120;

    $nc = new NoticiaControl();

    $smarty->append("news",$nc->getNews(),true);

    $smarty->display('notica.tpl');
}

} 

notica.tpl

<html>
     <head>
     </head>
     <body>
          {foreach $news as $n}
               {$n->valorDaNoticia()}
          {/foreach}
     </body>
</html>
    
06.05.2015 / 02:03
6

This can and should vary depending on the tipo de arquivo you are working on. If you follow padrão MVC , your point of view should be the last one. Try to maintain a separação de exibição/formatação de saída e a lógica that provides the data.

Example:

<?php
  # aqui você define algumas funções aqui que fornecem dados
?>
<html>
<body>
<?php foreach ($noticia->findAll() as $value): ?>
  <p>
    <?=$value;?>
  </p>
  <?php endforeach; ?>
</body>
</html>
    
06.05.2015 / 01:41
5

It is not a good practice, this dificulta much manutenções future, the ideal would be to use the MVC architecture, where you separate your model, controller e view . To make your life easier, you have a very good view framework, which I recommend that is twig , when you start programming in MVC you will not want to change any more.

    
06.05.2015 / 13:17
4

This is not a good practice to mix controller (system logic) with view (visual part of the program that interfaces with the user), to avoid the problems caused by this mix and gain more operational security (Web Designer and Developer can work at the same time without interfering with each other) is used templates

Sample templates:

Smarty: Download and Documentation Link

Dwoo: Download link and documentation

Example usage (more examples are provided in the documentation for other features):

<html>
  <head></head>
  <body>
    <blockquote>

    Knock knock! <br/>
    Who's there? <br/>
    {$name}      <br/>
    {$name} who? <br/>
    {$punchline}
    </blockquote>

  </body>
</html>

<?php
// auto-loader
include 'dwooAutoload.php';

// cria objeto Dwoo 
$dwoo = new Dwoo();

// le o templete acima definido
$tpl = new Dwoo_Template_File('tmpl/knock.tpl');

// valores dinamicos que serão injetados no template
$data = array();
$data['name'] = 'Boo';
$data['punchline'] = 'Don\'t cry, it\'s only a joke';

// injeta os valores e exibe a pagina, note que o nome do indices são identicos as 
//variaveis dentro do template, o dwoo irá fazer a injeção paseado nos nomes identicos.
$dwoo->output($tpl, $data);
?>
    
06.05.2015 / 15:10
4

When you use PHP along with HTML you will somehow be merging business rules with presentation rules. You should see a way to keep this separate, either through libraries such as Smarty or Twig, or another architecture besides MVC, such as REST for example, which allows a much larger separation than the MVC VIEW.

Mixing PHP with HTML will work the same way, and if the project is small maybe you should not even study various technologies, but the question is about good practices and code architecture. At this point it is advisable to further increase your knowledge about this for use in larger projects.

    
06.05.2015 / 15:59