Home  >  Article  >  Backend Development  >  Real-time notification and reminder of online voting system developed by PHP

Real-time notification and reminder of online voting system developed by PHP

WBOY
WBOYOriginal
2023-08-08 08:13:581015browse

Real-time notification and reminder of online voting system developed by PHP

Real-time notifications and reminders of the online voting system developed by PHP

In modern society, online voting systems are widely used in various scenarios, such as internal company decision-making, student unions Elections etc. In order to improve the user experience and efficiency of the voting system, we often need to add real-time notification and reminder functions to the system to promptly notify voting participants of voting results or important information. This article will introduce how to use PHP to develop an online voting system and add real-time notification and reminder functions.

First, we need to build a basic online voting system. You can use a PHP framework such as Laravel or write PHP code yourself. In this article, we will use the Laravel framework to demonstrate.

  1. Create a voting system database

First, we need to create a voting system database. You can use phpMyAdmin or other database management tools to create a new database and create corresponding voting tables and user tables.

  1. User registration and login

In the voting system, users need to register and log in before they can participate in voting. We can use the authentication system that comes with the Laravel framework to quickly build user registration and login functions. When registering, we need to obtain the user's mobile phone number or email address as contact information.

  1. Create a poll

In the voting system, the administrator needs to create a poll and set voting options. We can create a data table named vote to store voting information. The table can contain fields as follows:

  • id: Voting ID
  • title: Voting title
  • description: Voting description
  • options: Voting options
  • status: Voting status (in progress, ended, etc.)

You can use Laravel's data migration function to create database tables and models.

  1. Initiate a voting notification

After the administrator creates a poll, we need to send a notification to all logged in users to inform them that there is a new poll to participate in. The voting notification function can be implemented using events and listeners in Laravel.

First, we need to create a new event, such as VoteCreatedEvent. The event can contain voting information, as well as other relevant information needed to send notifications. We can then create an event listener, VoteCreatedListener, in which notifications are sent to all logged in users.

The following is a sample code:

// VoteCreatedEvent.php
namespace AppEvents;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;
class VoteCreatedEvent
{
    use Dispatchable, SerializesModels;
    public $vote;
    public function __construct($vote)
    {
        $this->vote = $vote;
    }
}

// VoteCreatedListener.php
namespace AppListeners;
use AppEventsVoteCreatedEvent;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use Notification;
use AppNotificationsNewVoteNotification;
class VoteCreatedListener implements ShouldQueue
{
    use InteractsWithQueue;
    public function handle(VoteCreatedEvent $event)
    {
        $vote = $event->vote;
        $users = User::all();
        Notification::send($users, new NewVoteNotification($vote));
    }
}

// NewVoteNotification.php
namespace AppNotifications;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateNotificationsMessagesMailMessage;
use IlluminateNotificationsNotification;

class NewVoteNotification extends Notification
{
    use Queueable;
    protected $vote;
    public function __construct($vote)
    {
        $this->vote = $vote;
    }
    public function via($notifiable)
    {
        return ['mail'];
    }
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->line('新投票已发布,请尽快参与投票')
            ->line('投票标题:' . $this->vote->title)
            ->action('立即参与', url('/vote/' . $this->vote->id))
            ->line('感谢您的参与!');
    }
}

In the above code, VoteCreatedEvent represents the vote creation event, VoteCreatedListener is the listener for the voting event, and NewVoteNotification is the notification information sent. We use Laravel's Notification class in VoteCreatedListener to send email notifications to all logged in users. The notification content includes the voting title and participation link.

  1. Visit the voting page

After users receive the voting notification, they can visit the voting page by clicking the link in the notification to perform voting operations. We can add a real-time update function to the voting page to display the current voting results in a timely manner.

You can use Laravel's Broadcasting function to achieve real-time update functionality. First, we need to configure Laravel's broadcast driver and channel. We can then use Laravel's Echo library to subscribe to the voting channel and use JavaScript code in the page to update the voting results in real time.

The following is a sample code:

// resources/js/app.js
import Echo from 'laravel-echo';
window.io = require('socket.io-client');
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://localhost:6001',
});
// routes/channels.php
use IlluminateSupportFacadesBroadcast;
Broadcast::channel('vote.{voteId}', function ($user, $voteId) {
    return true;
});
// VoteController.php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsVote;
class VoteController extends Controller
{
    public function show($id)
    {
        $vote = Vote::findOrFail($id);
        return view('vote.show', ['vote' => $vote]);
    }
}
<!-- resources/views/vote/show.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>投票</title>
    <script src="{{ asset('js/app.js') }}"></script>
</head>
<body>
    <h1>{{ $vote->title }}</h1>
    <p>{{ $vote->description }}</p>
    <ul>
    @foreach($vote->options as $option)
        <li>{{ $option }}</li>
    @endforeach
    </ul>
    <script>
        window.Echo.channel('vote.{{ $vote->id }}')
            .listen('.vote.updated', (data) => {
                console.log(data);
                // 更新投票结果的显示
            });
    </script>
</body>
</html>

In the above code, we compile the JavaScript code in the voting page through Laravel Mix and introduce it into the page. When the page loads, we use the Echo library to subscribe to the voting channel (vote.{voteId}) and listen to the .vote.updated event. When the voting results are updated, the page will receive the updated data and display it accordingly.

Through the above steps, we have successfully added the real-time notification and reminder functions of the online voting system. Users can get voting notifications in real time in the system and view voting results instantly. Such a system not only improves the user experience, but also improves the efficiency and fairness of voting.

To sum up, we have successfully added real-time notification and reminder functions to the online voting system developed using PHP, and provided corresponding code examples. This function not only allows users to keep up to date with the latest voting information, but also obtains voting results in real time, bringing convenience and fairness to the voting process.

The above is the detailed content of Real-time notification and reminder of online voting system developed by PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn