我正在開發一個網站,150個文件,大量的代碼;至少對我來說,是一個先行者。在PHP網站中包含代碼的正確方法
有許多地方我會重複輸出HTML的PHP回聲,每個PHP都有很多PHP變量。我正在考慮不重複這部分內容的最佳方式。
鑑於這種HTML:
<main>
<section>
<?php
$query = "SELECT a, b, c, d, e FROM table1";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$table1_a = $row['a'];
$table1_b = $row['b'];
$table1_c = $row['c'];
$table1_d = $row['d'];
$table1_e = $row['e'];
echo 'This code is thirty lines long and appears
identical in many places in the website.
It uses many variables, like '.$table1_a.','.$table1_b.',
'.$table1_c.','.$table1_d.','.$table1_e.', and others';
}
?>
</section>
<section>
<?php
$query = "SELECT a, b, c, d, e FROM table2";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$table2_a = $row['a'];
$table2_b = $row['b'];
$table2_c = $row['c'];
$table2_d = $row['d'];
$table2_e = $row['e'];
echo 'This second code is different to the other,
but is thirty lines long as well and is repeated
in many other places of the website.
It uses many variables, like'.$table2_a.',
'.$table2_b.','.$table2_c.','.$table2_d.',
'.$table2_e.' and others';
}
?>
</section>
</main>
我想象的方式有兩種:與包括與功能
隨着包括我會寫-without的querys迴響,因爲它們是分開所有不同 - 文件夾/ includes中的文件,然後我在頁面中調用它們。
在一個文件中包括/ echo_1.php爲包括將像:
<?php
echo 'This second code is different to the other,
but is thirty lines long as well and appears identical in
many other places of the website.
It uses many variables, like '.$table2_a.','.$table2_b.','.$table2_c.',
'.$table2_d.','.$table2_e.' and others';
?>
而在功能的功能/ echo_1.php將是:
<?php
function echo_1($table1_a,$table1_b,$table1_c,$table1_d,$table1_e){
echo 'This second code is different to the other, but is thirty lines
long as well and appears identical in many other places of the website.
It uses many variables, like
'.$table1_a.','.$table1_b.','.$table1_c.','.$table1_d.',
'.$table1_e.' and others';
}
?>
而調用:
<main>
<section>
<?php
$query = "SELECT a, b, c, d, e FROM table1";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$table1_a = $row['a'];
$table1_b = $row['b'];
$table1_c = $row['c'];
$table1_d = $row['d'];
$table1_e = $row['e'];
//Calling the include from the file echo_1.php
include 'includes/echo_1.php';
}
?>
</section>
<section>
<?php
$query = "SELECT a, b, c, d, e FROM table2";
$result = mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($result)) {
$table2_a = $row['a'];
$table2_b = $row['b'];
$table2_c = $row['c'];
$table2_d = $row['d'];
$table2_e = $row['e'];
//Using the function echo_1 to create the echo
echo_1($table1_a,$table1_b,$table1_c,$table1_d,$table1_e);
}
?>
</section>
</main>
此外,還有可能是回聲有部分代碼 - 帶查詢 - 重複在其他不同的回聲之間,我認爲不重複它們是很棒的,也許在另一個包含或其他函數內部。
With includes我打算撥打很多電話給另一個文件,這可能會減慢網站。有了函數,我只打一個電話,但我不知道這是否會更好。哪個選項是最有效的方法,包含或包含函數?任何關於編寫可維護代碼的建議都會受到歡迎!
N.
我建議你看看進入mvc框架 –
是的,羅伯特是對的。從Laravel這樣的事情開始,它已經在這方面採取了一些最佳實踐。 – ceejayoz
最好使用一個框架,否則你必須遵循mvc架構,你也可以使用一個像twig的模板引擎 –