How to Create Realtime Notifications Using Pusher in Php

in utopian-io •  7 years ago  (edited)

Screenshot_14.png
This tutorial I will share how to give realtime notification in your application by using php programming language, and surely we need a third party library, namely pusher. so just start our tutorial this time .

What Will I Learn?

  • Use Pusher , Register and Setting .
  • Use Pusher in Php to Handle Backend (Add Event and Channel) and Configuration settings.
  • Use Pusher in Javascript to Handle Frontend (Use event and Connect to Channel).

Requirements

  • Internet Connection
  • Php >= 5.6
  • Install Composer
  • Install Pusher
  • Localhost

Difficulty

  • Intermediate

Use Pusher

Before we actually make our realtime application notification. you must have a pusher account first, so you can do some setting in it. After you login to pusher, you can choose "create my app".
You can named the project, here I give the name "notification" . And you can also select the cluster closest to your location . You can also choose what technology you will use in the frontend and backend, I use javascript in frontend, and php in the backend .

Screenshot_6.png

After you create new app. you will be instructed to install the composer and import the javascript pusher library .

Screenshot_7.png

We can open the command prompt and do the composer install on your project .
Composer install

composer require pusher/pusher-php-server

Screenshot_8.png

After the installl is complete then you will see the vendor folder and composer.json has been made.

Create Pusher Application on the Serverside

We will configure the server section, which will use the Php programming language .
I will create a new folder under the folder pusher, and that folder I will name the notification and in the folder I create a file with the name index.php. "Pusher ->notification->index.php"

index.php


<?php
require('../vendor/autoload.php'); // load all functions in vendor
//Define Key pusher
define('APP_KEY','87cca8e5e7ea3ac15812');
define('APP_SECRET','73c94da408ce6bcb8ad1');
define('APP_ID','486604');
//make object of pusher
$pusher = new Pusher(
    APP_KEY,
    APP_SECRET,
    APP_ID,
    [
        'cluster'   =>'ap1',
        'encrypted' => true
    ]
);
$data['message'] = "Hello World , I'm Realtime Notification";
$pusher->trigger('my-channel','my-event',$data);

  • Import Vendor
  • Because we are using third-party libraries, we have to import all function functions in the vendor folder with autoload.php
    require('../vendor/autoload.php');


  • Initialization of the pusher object in a variable
  • We will create a pusher object that we initialize in suati variable, create new object in pusher with new pusher (). In that object we have some key which I will explain .
    
    $pusher = new Pusher(
        APP_KEY,
        APP_SECRET,
        APP_ID,
        [
            'cluster'   =>'ap1',
            'encrypted' => true
        ]
    );
    
    
  • APP_KEY
  • : Contains the key of our application that we will use in the client as a link between the server and client
  • APP_SECRET
  • : APP_SECRET will only be used on the server side, not on the client side.
  • APP_ID
  • : This is the app_id we have on the pusher application we created earlier.
  • ['cluster' =>'ap1', 'encrypted' => true]
  • : These are options. in the form of arrays. 'cluster' and encrypted.


  • Define Key
  • 
    define('APP_KEY','87cca8e5e7ea3ac15812');
    define('APP_SECRET','73c94da408ce6bcb8ad1');
    define('APP_ID','486604');
    
    
    Where do we get the key? we can see it in our dashboar pusher, in tab "app keys" .

    Screenshot_9.png

  • Add Channel
  • I will create a notification function, I will run with the method of $pusher->trigger().
    
    $data['message'] = "Hello World , I'm Realtime Notification";
    $pusher->trigger('my-channel','my-event',$data);
    
    
    in the trigger method , We pass three parameters, 1 .'my-channel' is thename of chanel. 2. 'my-event' is the name of event. 3. $data is the message we will show there is the client side.

    Use Pusher in Clientside

    in the client side we will create a simple html file with the name index.html under the folder pusher. pusher->index.html

    index.html

    <!DOCTYPE html>
    <html>
    <head>
        <title>Tutorial Pusher</title>
        <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            Pusher.logToConsole = true;
            var pusher = new Pusher('87cca8e5e7ea3ac15812',{
                cluster     :'ap1',
                encrypted   : true
            });
            var channel = pusher.subscribe('my-channel');
            channel.bind('my-event', function(data){
                alert(data.message)
            });
        </script>
    </body>
    </html>
    


  • Import Library Pusher
  • We need to import the library pusher in the client. We can see the import script in dashboard pusher section in get started tab .

    Screenshot_10.png

    < script src="https://js.pusher.com/4.1/pusher.min.js" >< /script >

  • initialization of pusher in client
  • Not just initialization on the server, We also need to initialize in the client, but the difference we just need it the APP_KEY : 87cca8e5e7ea3ac15812
    
    var pusher = new Pusher('87cca8e5e7ea3ac15812',{
                cluster     :'ap1',
                encrypted   : true
            });
    
    
  • Subscribe Channel
  • We will subscribe to the subscribe() method from pusher. and initialize in one variable var channel.
    var channel = pusher.subscribe('my-channel'); : 'my-channel' is the name of the channel we define in the server side. So if we have some different applications during dy run this script, dy will automatically subscribe this channel.
  • Binding Event
  • Here we will user bind() method from pusher to bind or we combine with the event we named in its serveside as 'my-event'. channel.bind('my-event', function(data){} : We receive the callback in the data. and i will alert(data.message) to see what's inside the data .

    To see the results I will run two browser tabs that one will run on the server and another to see the results of the notification . run the server on your localhost .

    Browser Server

    Screenshot_11.png

    in the server browser we just do reload, make sure every time reload, index.php managed to send notif.

    Browser Clientside

    in the client, we can see the alert that we put on the client side, we can see it by opening our index.html file in the browser.

    Screenshot_12.png

    If we change again in chanel message section, then we will get new message. I change the key of $data['message']in the index.php section. $data['message'] = "I have been changed in the server side"; , the result will be like this.

    Screenshot_13.png

    Even i also get the same notif though i open a different browser as an example i will use two browser, chrome and mozilla.

    Screenshot_14.png

    Finally we have completed this tutorial, we have made realtime notification that we often see in social media, hopefully from this tutorial can give you idea or picture about realtime notification, enough of me thank you already follow this tutorial



    Posted on Utopian.io - Rewarding Open Source Contributors

    Authors get paid when people like you upvote their post.
    If you enjoyed what you read here, create your account today and start earning FREE STEEM!
    Sort Order:  

    Thank you for the contribution. It has been approved.

    You can contact us on Discord.
    [utopian-moderator]

    Hey @alfarisi94 I am @utopian-io. I have just upvoted you!

    Achievements

    • WOW WOW WOW People loved what you did here. GREAT JOB!
    • You have less than 500 followers. Just gave you a gift to help you succeed!
    • Seems like you contribute quite often. AMAZING!

    Community-Driven Witness!

    I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

    mooncryption-utopian-witness-gif

    Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x