Is it good practice to mix Php and Html?

Asked

Viewed 2,700 times

18

I see that in python, has the Bottle for example that does the same thing of what I intend to do then...

I am new to web practices, student indeed and would like to know if I can use php and html in the same place,I wonder if this is a standard, not recommended, or whatever. 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>
  • Related question (possibly duplicate): http://answall.com/questions/7703/utilizo-php-dentro-de-um-html-ou-um-html-dentro-de-um-php

  • It has nothing to do with this question there. I want to know if the php developers currently develop in this way, or if there is another way. That question didn’t answer my question.

  • OK Asura, that’s why I said "related" and "possibly". I didn’t signal, nor did I vote to close, it was just a suggestion. I had already given +1 in your question, because I thought it was well done, in what weight to have thought that it could be duplicate.

  • 1

    In my opinion, 'No', many of the programmers I know also do not prefer this mixture. It is preferable to use an MVC Project, which separates the content, in which a view receive the variables to be used. After studying MVC, a good example is cakephp'

  • Not recommended. Look for some engine and template. If you are using some framework they already indicate a pattern.

8 answers

18


Is a pattern.

Is not recommended.

It’s not a good practice.

In many cases it doesn’t matter.

There is a principle in software design called Separation of Concerns, that determines that each part of the system cares about one thing only.

In your case, the principle would determine that a separate part of your code should take care of the presentation, another part must take care of the structure what is being presented, another party should take care of the contents presented, and you can still have distinct parts to take care of the presentation logic and of 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 lack of observation in large or complex applications causes difficulty (increase in cost) maintenance and system evolution and reduction of software quality.

10

Whether or not it is a good practice depends very much on opinion.

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

SHOULD files either declare symbols (classes, functions, constants, etc.) or cause side effects (e.g. generate output, modify settings in php.ini, etc.), but SHOULD NOT do both.

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

More information on http://www.php-fig.org/ (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 responses.

  • I didn’t know this PSR. I appreciate you showing it to me.

7

I think it is totally normal to use these "web practices", but this depends on the way the programmer thinks it is easier to develop and make future maintenance. Or you can make a function for every thing the application does (which is easier to do 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 widely used practice by programmers is MVC: In which a view receives the variables to be used, and the functions are usually in the Model class separate from the view. http://www.tutsup.com/2014/09/17/mvc-em-php-parte-1/

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. Take 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>
  • To my ignorant student view on the subject, it seems a non-obvious mix. It’s kind of the Bottle.py .

6

This may and should vary depending on the tipo de arquivo that you are working. If you follow the padrão MVC, your point should be the last. Try to keep 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>

5

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

4

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

Examples of templates:

Smarty: Download link and documentation

Dwoo: Download link and documentation

Example of use (in the documentation more examples for other functionalities are provided):

<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);
?>

4

When you use PHP together with HTML you will somehow be mixing business rules with presentation rules. You should see a way to keep this separate, whether through libraries such as Smarty or Twig, or from another architecture other than MVC, such as REST, which enables much greater separation than MVC VIEW.

Mixing PHP with HTML will work the same way, and if the project is small you might not want to study several technologies, but the question is about good practices and the architecture of the code. At this point it is recommended to further increase your knowledge about this to be used in larger projects.

Browser other questions tagged

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