1. Ứng dụng realtime là gì?
Ứng dụng realtime là ứng dụng tương tác với người dùng theo thời gian thực. Ví dụ như ứng dụng chát, ứng dụng thông báo dạng như facebook….Và một trong những ngôn ngữ hỗ trợ rất tốt trong việc này đó là NodeJs bạn có thể tìm hiểu trên freetuts và một số nguồn khác.
Thế còn với php thì sao?
Đối với php bạn có thể xây dựng ứng dụng realtime bằng một vài cách sau
Sử dụng ajax request dữ liệu liên tục sau môi giây.
Ưu diểm: Nhanh gọn, dễ dùng.
Nhược điểm: Do phải request dữ liệu liên tục như thế sẽ rất tốn tài nguyên sever nhìn sẽ rất xót xa.
Sử dụng WebSockets với ratchet cái này mình không rành nên không dám chém bừa sợ gạch đá lắm nếu bạn có hứng thú cỏ thể tìm hiểu tại http://socketo.me/.
Và còn một số kỹ thuật khác nhưng trong khổ bài viết này mình sẽ giới thiệu đến các bạn bằng cách sử dụng qua sever trung gian đó là sử dụng pusher.
Xem Thêm : Hướng dẫn cài đặt sourcode share video
Bạn sẽ sử dụng ứng dụng realtime vào hệ thống của mình như thế nào?
Bạn có một website bán hàng? Bạn muốn thông báo về tình trạng đơn hàng cho khách hàng, hay xây dựng chương trình nhắn tin từ quản trị đến thành viên như thông báo khuyến mãi, biến động số dư….Hoặc bạn đang ấp ủ một website lấy kết quả xổ số,kết quả bóng đá theo thời gian thực, hoặc ứng dụng rất phổ biến là chát giữa các thanh viên với nhau. Thì lúc này bạn sẽ nghĩ đến realtime.
2. Pusher là gì?
Pusher là 1 dịch vụ cung cấp cho người dùng 1 Server ảo làm trung gian xử lý các dữ liệu với thời gian thực.Cho đến thời điểm hiện tại pusher đã có hơn 100 nghìn người sử dụng. Mình vừa mới thử qua pusher và thấy nó khá nhanh và dễ sử dụng.
Vậy pusher hoạt động như thế nào?
Quy trình hoạt động của pusher được thể hiện qua sơ đồ sau:
Client duyệt web – > dữ liệu sẽ được chuyến đến sever-> sever chuyển tiếp đến Pusher thông qua pusher API -> Pusher trả kết lại cho client (hoặc client khác).
Pusher cung cấp cho chúng ta nhiều gói dịch vụ bạn có thể tham khảo tại đây. Nhưng gói free của pusher cung đã cũng cấp cho chúng ta 200k tin nhắn và 100 kết nối mỗi ngày. Và theo mình chừng ấy cũng là quá đủ cho một website tầm trung.
Ưu điểm của pusher: Bạn chỉ mất khoảng 5 phút để có thể tạo ra 1 ứng dụng realtime sử dụng pusher mà không cần biết quá nhiều kiến thức.
Nhược điểm: Sử dụng qua sever trung gian lên tương tác sẽ chậm hơn 1 chút nhưng không đáng kể.
Đối với những hệ thống lớn lượng request trong ngày cao bạn cần phải nâng cấp. Nhưng theo mình đối với những website lớn thì bạn nên tìm hiểu các công nghệ khác.
Đầu tiên các bạn tạo file frontend để hiển thị dữ liệu và insert dữ liệu lên database
Xem Thêm : Hướng dẫn cài đặt theme TikTok miễn phí tại VNCODE
Sourcode frontend insert dữ liệu
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Stacked form</h2>
<form action="" method="POST">
<div class="form-group">
<label for="firstname">Fist Name:</label>
<input type="text" class="form-control" id="firstname" placeholder="Enter Name" name="firstname">
</div>
<div class="form-group">
<label for="lastname">Last Name:</label>
<input type="text" class="form-control" id="lastname" placeholder="Enter Last Name" name="lastname">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
Sourcode frontend hiển thị dữ liệu lên giao diện
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Bordered Table</h2>
<p>The .table-bordered class adds borders on all sides of the table and the cells:</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Bây giờ chúng ta bắt đầu với PHP trước nhé: đầu tiên chúng ta tạo file kết nối tới mysql
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "realtime";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Tiếp theo bắt đầu code insert dữ liệu vào mysql
require_once 'conn.php';
require __DIR__ . '/vendor/autoload.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$options = array(
'cluster' => 'ap1',
'useTLS' => true
);
$pusher = new PusherPusher(
'c00e39137b24e507165c',
'927d2e94a477c2f9a8ed',
'1256278',
$options
);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO username (firstname, lastname)
VALUES ('$firstname', '$lastname')";
if ($conn->query($sql) === TRUE) {
$data['message'] = $firstname .' '.$lastname;
$pusher->trigger('my-channel', 'my-event', $data);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
Tạo file autoload.php bằng cách insall composer :
composer require pusher/pusher-php-server
require __DIR__ . '/vendor/autoload.php';
$options = array(
'cluster' => 'ap1',
'useTLS' => true
);
$pusher = new PusherPusher(
'c00e39137b24e507165c',
'927d2e94a477c2f9a8ed',
'1256278',
$options
);
$data['message'] = $firstname .' '.$lastname;
$pusher->trigger('my-channel', 'my-event', $data);
Tiạo file users.php để hiển thị dữ liệu ở dạng ajax
require_once 'conn.php';
$sql = "SELECT firstname, lastname FROM Username";
$result = $conn->query($sql);
if($result->num_rows > 0 ){
while($row = $result->fetch_assoc()){
?>
<tr>
<td><?= $row['firstname'] ?></td>
<td><?= $row['lastname'] ?></td>
</tr>
<?php
}
}else{
?>
<tr><td colspan="2">No database</td></tr>
<?php
}
Code tiếp ở file hiển thị dữ liệu lên website
<?php
require_once 'conn.php';
$sql = "SELECT firstname, lastname FROM Username";
$result = $conn->query($sql);
?>
Lấy dữ liệu vừa query ra
<!DOCTYPE html>
<html lang="en">
<head>
<title>Index Realtime</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<div id="div1">
</div>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody id="result">
<?php
if($result->num_rows > 0 ){
while($row = $result->fetch_assoc()){
?>
<tr>
<td><?= $row['firstname'] ?></td>
<td><?= $row['lastname'] ?></td>
</tr>
<?php
}
}else{
?>
<tr><td colspan="2">No database</td></tr>
<?php
}
?>
</tbody>
</table>
</div>
</body>
</html>
Dùng ajax để hiển thị dữ liệu ở dạng realtime
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('c00e39137b24e507165c', {
cluster: 'ap1'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
$.ajax({url: "users.php", success: function(result){
$("#result").html(result);
}});
});
</script>
Dưới đây là toàn bộ code mà mình đã làm demo để các bạn có thể tham khảo 1 cách dễ dàng nhất. Chúc các bạn đang có nhu cầu làm realtime cho dự án của mình có một trải nghiệm mới với Pusher. Like và share bài viết để ủng hộ VNCODE nhé !!!
Nguồn: https://vncode.info
Danh mục: PHP