Better or more efficient practice in php

0

I have two templates: header.php and footer.php. And some other pages: index.php, menu.php, page_1.php, page_2.php

What is the best (or most efficient) option?

OPTION ONE

Index.php:

  

require 'header.php'

     

require $ page; // Assigned in menu.php; $ page = page_1.php

     

require 'footer.php'

page_1.php:

  

/ * ... Contents of page_1.php ... * /

OPTION TWO

On each page, include the templates header.php and footer.php.

page_1.php:

  

require 'header.php'

     

/ * ... Contents of page_1.php ... * /

     

require 'footer.php'

page_2.php:

  

require 'header.php'

     

/ * ... Content of page_2.php ... * /

     

require 'footer.php'

    
asked by tecno 27.10.2016 в 17:30
source

1 answer

1

It all depends on how you want to implement it and the utility that you will give to the first option (in particular). The difference of time between one and another solution is negligible compared to the loading time of the script itself, so using one or the other will not drastically (or appreciably) affect performance.

I have tried to measure the time of 500 executions in one way and another and even without doing anything PHP and this is the result (not conclusive):

$ time ( i=500; while [ $i -gt 0 ] ; do php pr1.php ; i=$((i-1)) ; done )
real    0m9.151s
user    0m6.104s
sys 0m2.440s

$ time ( i=500; while [ $i -gt 0 ] ; do php pr2.php ; i=$((i-1)) ; done )
real    0m9.248s
user    0m6.260s
sys 0m2.288s

$ time ( i=500; while [ $i -gt 0 ] ; do php pr3.php ; i=$((i-1)) ; done )
real    0m9.028s
user    0m6.080s
sys 0m2.284s

The pr1.php example contains an empty PHP file (only with <?php ) and pr2.php makes require of two additional files, inc1.php e inc2.php , also empty.

As you can see, the difference between doing nothing and including two files is barely 1%.

The example pr3.php loads 8 files from inc1.php to inc8.php and, if I let myself be carried away by the results, we would have to deduce that the more files you need the faster PHP runs:)

That said, the working time with files is negligible with the overload of the execution of the PHP script itself.

Everyone who uses MVC (as is my case) will agree that the first one has more possibilities because you could concentrate the routing effort in a single file (a single entry point).

As a project grows it is more difficult to maintain PHP files, their security, etc. You should think about starting to use a framework that solves the whole issue of MVC and what surrounds the processing of HTTP requests.

You have to choose many options:

  • Laravel
  • Symfony
  • Slim
  • etc

Loss of performance is acceptable (and not as great as many think) with respect to the gain in terms of organization and structure of the project, security, readability, etc.

    
answered by 28.10.2016 в 14:37