Bài giảng PHP (Hypertext Preprocessing) - Chương 6: Tổ chức ứng dụng PHP trình bày các nội dung chính sau: Hệ thống template, quản lý output, quản lý lỗi, tối ưu hóa,... Mời các bạn cùng tham khảo để nắm nội dung chi tiết.
Trang 1VI Tổ chức ứng dụng PHP
VI.2 Hệ thống template
VI.3 Quản lý output
VI.4 Quản lý lỗi
VI.5 Tối ưu hóa
Trang 2VI.2 Hệ thống template
quan trọng
người thiết kế giao diện và người lập trình làm việc với
(.HTML – được thiết kế từ các chương trình: DW,
FrontPage ) Các file template này thường không chứa
mã PHP mà chỉ có các thông tin dưới dạng quy ước
(thường là các tên gọi, giá trị được đặt theo 1 quy ước nhất định, các giá trị này sẽ được thay thế khi chạy
chương trình bằng PHP)
Trang 3VI.2 Hệ thống template (2)
<?php
$templatePath = "./templates/" ;
function MakeWebPageFromTemplate($templateName, $params) {
global $templatePath;
$templateName = $templatePath $templateName;
if ($f = fopen ($templateName, "rt" )) {
$templateContent = fread ($f, filesize ($templateName));
fclose ($f);
}
$templateContent = str_replace (
" \" /" , " \" " $templatePath, $templateContent);
foreach ($params as $paramName=>$paramVal) {
$templateContent = str_replace (
$paramName, $paramVal, $templateContent);
}
return $templateContent;
}
?>
Trang 4VI.3 Quản lý output
chúng ta không muốn như vậy
liệu lên đó
ob_flush(), ob_end_flush(); ob_end_clean()
<?php
ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_clean();
if (strpos($phpinfo, "module_pdf") === FALSE) {
echo "You do not have PDF support in your PHP, sorry."; } else {
echo "Congratulations, you have PDF support!";
}
?>
Trang 5VI.4 Quản lý lỗi
VI.4.1 Thông báo lỗi VI.4.2 Giấu lỗi
VI.4.3 Phát sinh lỗi VI.4.4 Hàm xử lý lỗi
Trang 6VI.4.1 Thông báo lỗi
output
sẽ được in ra browser, bạn có thể thay đổi trong PHP.INI hoặc trong thời gian chạy bằng hàm
error_reporting() (các tham số E_ERROR |
E_PARSE | E_CORE_ERROR |
E_COMPILE_ERROR | E_USER_ERROR)
Trang 7VI.4.1 Thông báo lỗi (2)
E_COMPILE_WARNING Warnings generated internally by the Zend scripting engine
Trang 8VI.4.2 Giấu lỗi
$php_errormsg
error_reporting(0)
<?php
ini_set("track_errors", "1");
$value = 2/0;
$value = @(2/0);
echo "$php_errormsg";
ini_restore("track_errors");
?>
<?php
error_reporting(0);
ini_set("track_errors", "1");
$value = 2/0;
echo "$php_errormsg";
ini_restore("track_errors");
?>
Trang 9VI.4.3 Phát sinh lỗi
trigger_error
E_USER_NOTICE (default)
<?php
function divider($a, $b) {
if($b == 0 ) {
return($a / $b);
}
?>
Trang 10VI.4.4 Hàm xử lý lỗi
Giấu tất cả các lỗi không phải là một phương án hay, để quản
lý lỗi tốt hơn, bạn nên dùng hàm xử lý lỗi (error handler)
Error handler được thiết lập bằng hàm set_error_handler(), khôi phục lại bằng hàm restore_error_handler()
<?php
function my_handler($error, $errorstring,
$filename, $line, $symbol)
{
echo " $error | $errorstring | $filename | $line\n " ;
}
set_error_handler ( 'my_handler' );
echo 4 / 0 ;
$f = file ( "linhtinh" );
?>