Thursday, February 21, 2013

Caching website với CodeIgniter

Nội dung :
  • Tại sao cần phải caching website
  • Sự khác biệt giữa caching và không caching
  • Làm thế nào để caching trong CodeIgniter

1.Tại sao cần phải caching website: 
- Trước hết , bạn hiểu như thế nào là caching : Web caching là việc lưu trữ bản sao của những tài liệu web sao cho gần với người dùng, cả về mặt chức năng trong web client hoặc những web caching servers riêng biệt 
- Ưu điểm : 
  • Load nội dung nhanh hơn
  • Hạn chế việc truy vấn trực tiếp vào Databse


2.Sự khác biệt giữa caching và không caching 
Không sử dụng caching : 
• Kết nối MySQL Database 
• Lấy 10 item trong database 
• Sắp xếp nhửng Item theo thứ tự 
• Đọc template file cho web sau đó cho việc hiển thị 
• Trả kết quả về phía người dùng 
 

- Nếu trong 1 thời gian ngắn có 2 lượt truy cập, thì các thực thi trên không đáng để quan tâm. Nhưng nếu khoảng 500 lượt truy cập trong 1 giờ chẳng hạng thì nó vấn đề mà chúng ta cần phải quan tâm. Liệu Server của bạn có thể đảm đương 500 x (các thực thi trên) không và có thể lượt truy cập còn hơn thế nữa 
-Ở đây mình xin nói thêm "làm sao thống kê được lượt truy cập" . Các bạn có thể tìm hiểu ứng dụng miễn phí google analytics của google 

Sử dụng caching : 
Để làm giảm tải các truy vấn tới CSDL ta có thể sử dụng kĩ thuật Caching website. 
Ví dụ : 
Trong 1 ngày đó , tôi là người truy cập đầu tiên vào website :http://qhonline.info/news 
Thì webserver sẽ thực thi các bước như sau : 
• Kết nối MySQL Database 
• Lấy 10 item trong database 
• Sắp xếp nhửng Item theo thứ tự 
• Đọc template file cho web sau đó cho việc hiển thị 
• Trả kết quả về phía người dùng 

Sau đó lưu nội dung hiển thị http://qhonline.info/newsvào 1 file text đã được mã hóa trên webserver 
Kế tiếp sau tôi là các user cũng truy cập đại chỉ : http://qhonline.info/newsnhưng lần này hệ thống không truy vấn vào CSDL như các bước trên , mà nó sẽ tìm file đã được cache và đọc nó, và như thế 100 người hay 1000 người … truy cập vào http://qhonline.info/newsthì cũcng chỉ đọc nội dung file cached 
- Việc đọc nội dung 1 file text với việc truy vấn vào CSDL thì rõ ràng có sự khác biệt rất lớn về cách xử lý cũng như tốc độ load. 
Bạn có thể xem hình mô tả bên dưới 
 

3.Làm thế nào để caching trong CodeIgniter : 
- Ví dụ : tôi truy cập vào link sau : http://qhonline.info/news/bongba 
Như vậy trong ứng dụng của tôi cần có 

 class News extends Controller 

function
 __construct(){  

   parent::controller(); 
  //code here ………….   
 } 

  function
 bongda(){ //kết nối CSDL 
     //…………… 
      //loadview();

  
 

}
- Làm sao để caching website với nội dunghttp://qhonline.info/news/bongba 
- Bạn thêm hàm : 
PHP Code:
$this->output->cache($n)
dưới cùng của function bongda() với n là thời gian làm mới nội dung cache được tính bằng phút 
Xem có thể xem thêm userguide về hàm này tại :http://codeigniter.com/user_guide/general/caching.html 
Như vậy class có caching của chúng ta bây giờ là : 

PHP Code:
<?php class News extends Controller 

function
 __construct(){ parent::controller(); //code here…………


function
 bongda(){ //kết nối CSDL 
//…………… 
//loadview(); 
$this->output->cache(5) ; // thời gian làm mới là sao 5 phút nếu có lượt truy cập vào nội dung này 
}
Nếu bạn muốn caching toàn bộ cho controller news thì thêm đoạn code$this->output->cache() vào cuối của hàm : 
PHP Code:
function __construct(){..}
PHP Code:
<?php class News extends Controller 

function
 __construct(){ parent::controller(); //code here…………$this->output->cache(5) ; // thời gian làm mới là sao 5 phút nếu có lượt truy cập vào nội dung này 

function
 bongda(){ //kết nối CSDL 
//…………… 
//loadview(); 

}
Các file cache được lưu trong thư mục system/cachecủa CodeIgniter 

Ứng dụng Ajax, Json để Upload file trong CodeIgniter


Chào các bạn, hôm nay mình sẽ hướng dẫn các bạn sử dụng ajax khi chúng ta upload file trong CodeIgniter! 
Để nắm rõ dc TUT này, các bạn phải có kiến thức cơ bản về Json nha ! Tham thảo jsontại :http://www.qhonline.info/forum/showt...highlight=json. 
+++Ở đây, chúng ta sẽ nạp vào thư viện AjaxFileUpload. Các bạn có thể tải tại đây:http://www.phpletter.com/DOWNLOAD/. 

->Các bước cb đã xong !giờ chúng ta bắt tay vào viết ứng dụng nào . 

+Đầu tiên, chúng ta tạo 1 bảng cấu trúc như sau: 

Mã:


CREATE TABLE `files` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`file_name` varchar(255) NOT NULL,
`title` varchar(100) NOT NULL
);
+Tiếp theo, chúng ta có cấu trúc thư mục code như sau: 

- application/ 
--- controllers/ 
------ upload.php 
--- models/ 
------ mupload.php 
--- views/ 
------ upload_view.php 
------ files.php 
- public/ 
--- css/ 
----- style.css 
--- js/ 
----- AjaxFileUpload.js 
----- jquery.js 
- upload/ ->thư mục chứa file chúng ta upload lên. 

->Trong controller upload.php ta xử lý như sau
PHP Code:
class Upload extends CI_Controller
public function
 __construct(){ parent::__construct(); $this->load->helper(array("url","form")); 

public function
 index(){ $this->load->view("upload_view"); 
//hàm trả về các file đã upload dc lưu trong database public function files(){ $this->load->model("mupload"); $data['files'] = $this->mupload->get_all_files(); $this->load->view("files",$data); 

//hàm xử lý việc upload file và xuất thông báo dưới dạng json public function upload_file(){ $status = ""$msg = ""$tit = $this->input->post("title"); 
if(
$tit == NULL){ $status = "error"$msg = "Please enter your title"

if(
$status != "error"){ $config['upload_path'] = '.upload'$config['allowed_types'] = 'gif|jpg|png|doc|txt'$config['max_size'] = 1024 * 8$config['encrypt_name'] = TRUE$this->load->library("upload",$config); 
if(!
$this->upload->do_upload("ufile")){ $status = "error"$msg = $this->upload->display_errors('<p>','</p>'); 
echo
 $msg
}else{ 
$this->load->model("mupload"); $data = $this->upload->data(); $info = array("file_name" => $data['file_name'], "title" => $_POST['title']); $fid = $this->mupload->insert_file($info); 
if(
$fid){ $status = "Success"$msg = "File successfully uploaded"
}else{ 
$status = "error"$msg = "File uploaded fail! PLease try again!"



Echo
 json_encode(array("status" => $status"msg" => $msg)); 

//hàm xử lý xóa file upload public function delete_files($file_id){ $this->load->model("mupload"); 
if(
$this->mupload->delete_file($file_id)){ $status = 'success'$msg = 'File successfully deleted'
}else{ 
$status = 'error'$msg> = 'Something went wrong when deleting the file, please try again'

Echo
 json_encode(array('status' => $status, 'msg' => $msg)); 




->Đây là file model của chúng ta: 
mupload.php: 
PHP Code:
classMupload extends CI_Model
protected
 $_table = "files"
public function
 __construct(){ parent::__construct(); $this->load->database(); 

public function
 insert_file($data){ $this->db->insert($this->_table,$data); 
return
 $this->db->insert_id(); 

public function
 get_all_files($file_id =""){ 
if(
$file_id != ""){ $this->db->where("id",$file_id); 

return
 $this->db->get($this->_table)->result_array(); 

public function
 delete_file($file_id){ $file = $this->get_all_files($file_id); 
if(
$file == ""){ 
return
 FALSE
}else{ 
$this->db->where("id",$file_id); $this->db->delete($this->_table); unlink("./upload/" . $file[pan style="color:rgb(0,0,187);">0
]['file_name']); //xóa file upload trong thư mục chứa return TRUE



Và cuối cùng ta có 2 trang view: 

upload_view.php: 
HTML Code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="<?php echo base_url();?>public/js/jquery.js"></script>
<script src="<?php echo base_url()?>public/js/ajaxfileupload.js"></script>
<link href="<?php echo base_url()?>public/css/style.css" rel="stylesheet" />
<script language="javascript">
refresh_files();//Show ra list cac file da upload

$(document).ready(function(){
//xu ly upload file
$("#submit").click(function(){
$.ajaxFileUpload({
url : "./upload/upload_file",
secureuri : false,
fileElementId : "ufile",
dataType :"json",
data : {"title" : $("#title").val() },
success : function(data, status){
if(data.status != "error"){
$("#files").html("<p>Loading....</p>");
refresh_files();
$("#title").val("");
}
alert(data.msg);
}
});
return false;
}); //ket thuc upload file

//Xu ly delete file upload
$(".delete_file_link").live("click",function(){
if(confirm("Do you want to delete this file?")){
varlink_url = $(this);
//var files = $("#files");
//alert(files);
//alert(link_url.data("file_id"));
$.ajax({
url : "./upload/delete_files/" + link_url.data("file_id"),
dataType : "json",
success : function(data){
files = $("#files");
if(data.status == "success"){
link_url.parents("li").fadeOut("fast", function(){
$(this).remove();
if(files.find('li').length == 0){
files.html('<p>No Files Uploaded</p>');
}
});
}else{
alert(data.msg);
}
}
})
}
})//ket thuc xu ly file upload

})


function refresh_files()
{
$.get('./upload/files/').success(function (data){
$('#files').html(data);
});
}
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload_file" enctype="multipart/form-data">
<label>Title</label>
<input type="text" name="title" id="title"/>

<label>File</label>
<input type="file" name="ufile" id="ufile" size="25" />

<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<h2>Files</h2>
<div id="files"></div>
</body>
</html>
và files.php 
PHP Code:
<?php if(isset($files)){ 
echo
 "<ul>"
foreach(
$files as $items){ 
echo
 "<li class='image_wrap'>"
echo
 "<a href='' class='delete_file_link' data-file_id='$items[id]'>Delete</a>"
echo
 "<strong>$items[title]</strong><br />"
echo
 "<imgsrc='". base_url()."upload/$items[file_name]' width='150' />"
echo
 "</li>"

echo
 "</ul>"

else{ 
echo
 "<p>No Files Uploaded</p>"
?>
Trong đó upload _view.php sẽ là trang chúng ta dùng ajax để xử lý việc upload cũng như delete các file. Còn files.php sẽ là trang dùng để show ra các file chúng ta đã upload thành công. 
-->files.php sẽ dc gọi để hiển thị trong upload_view.php qua function refresh_filestrong đoạn javascript.