Implementing real-time notifications in CodeIgniter 3 requires a bit more setup because CodeIgniter 3 is a traditional PHP framework and does not natively support real-time features like WebSockets. However, you can achieve real-time notifications using one of the following approaches:
1. Using WebSockets (Recommended for true real-time)
Overview:
- Use a WebSocket server (Node.js, Ratchet PHP, or a third-party service).
- Your CodeIgniter app pushes notification events to the WebSocket server.
- Clients (browsers) maintain a WebSocket connection and receive notifications instantly.
How to do it:
Step 1: Set up a WebSocket server
- Node.js + Socket.IO is a popular choice.
- Or use Ratchet (PHP WebSocket library) if you want PHP-only.
Example: Node.js WebSocket server with Socket.IO
// server.js
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
console.log('User connected');
// You can listen for events or send notifications
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
// Function to emit notification to a specific user
function sendNotification(userId, notification) {
io.to(userId).emit('notification', notification);
}
Step 2: Modify your CodeIgniter app to send notifications to WebSocket server
You can send notifications to the WebSocket server via:
- HTTP API exposed by your Node.js server
- Redis Pub/Sub (if using Redis)
- Or directly via a WebSocket client library in PHP (less common)
Example: Send notification via HTTP POST to Node.js server
function send_real_time_notification($user_id, $notification) {
$url = 'http://localhost:3000/send-notification'; // Your Node.js API endpoint
$data = [
'user_id' => $user_id,
'notification' => $notification
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Step 3: Client-side JavaScript to receive notifications
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
var socket = io('http://localhost:3000');
// Join room or identify user (depends on your server logic)
socket.emit('join', { userId: CURRENT_USER_ID });
socket.on('notification', function(notification) {
alert('New notification: ' + notification.title);
// Or update your notification UI dynamically
});
</script>
2. Using Polling or Long Polling (Simpler but less efficient)
If you cannot set up WebSockets, you can simulate real-time notifications by:
- Using AJAX polling every few seconds to check for new notifications.
- Or using long polling to keep the connection open until a notification arrives.
Example: AJAX Polling
function checkNotifications() {
$.ajax({
url: '<?= site_url("notifications/get_unread_count") ?>',
method: 'GET',
success: function(data) {
if (data.unread_count > 0) {
// Update notification UI
$('#notification-badge').text(data.unread_count);
}
}
});
}
setInterval(checkNotifications, 5000); // every 5 seconds
Controller method in CodeIgniter:
public function get_unread_count() {
$user_id = $this->ion_auth->user()->row()->id;
$count = $this->notification_model->count_unread($user_id);
echo json_encode(['unread_count' => $count]);
}
3. Using Third-Party Services (Easiest)
You can use services like:
These services provide real-time messaging APIs and SDKs.
How to integrate Pusher with CodeIgniter 3:
- Install Pusher PHP SDK via Composer.
- Send notifications from your CodeIgniter app to Pusher.
- Use Pusher JavaScript client on frontend to receive notifications instantly.
Example:
// Load Pusher library
require_once APPPATH.'third_party/pusher/vendor/autoload.php';
$options = array(
'cluster' => 'YOUR_CLUSTER',
'useTLS' => true
);
$pusher = new Pusher\Pusher(
'YOUR_APP_KEY',
'YOUR_APP_SECRET',
'YOUR_APP_ID',
$options
);
$data['message'] = 'New school request submitted';
$pusher->trigger('notifications-channel', 'new-notification', $data);
Client-side:
var pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_CLUSTER'
});
var channel = pusher.subscribe('notifications-channel');
channel.bind('new-notification', function(data) {
alert(data.message);
// Update notification UI
});
Summary
| Approach | Pros | Cons | Use Case |
|---|
| WebSockets (Node.js) | True real-time, scalable | Requires extra server setup | Best for full real-time apps |
| AJAX Polling | Easy to implement | Not truly real-time, inefficient | Simple apps, low traffic |
| Third-party (Pusher) | Easy, scalable, reliable | Cost, dependency on external service | Fastest way to add real-time |
If you want, I can help you with a step-by-step example for any of these approaches — just let me know!