Laravel event broadcast based on pusher driver (top)

Source: Internet
Author: User
Description: This article is mainly derived from Building real-time Laravel Apps with pusher.

This article mainly introduces the use of pusher package to develop the Laravel APP with real-time communication function, the entire tutorial only takes two hours to go through. At the same time, the author will be in the development process of some and code to stick up, improve reading efficiency.

1. Tutorial Related

Conditions required for this tutorial:

    • Composer already installed

    • Basic knowledge of PHP

    • Basic understanding of Laravel

    • Basic understanding of jquery

    • Have a GitHub account

Note: Laravel is a popular PHP full stack framework, composer is a PHP package manager, and jquery is a JavaScript framework for manipulating the DOM tree. If you do not know, you can spend half an hour before watching the tutorial Google these basic content is better. By the wall to do, to GitHub on the search lantern, you know.

What is 1.1 pusher?

Pusher is a real-time middle tier between the client and the server, with WebSocket or HTTP to enable persistent linking to the client, so that the service can send data to the client in real time. In short, it is a package that implements persistent chaining.

1.2 Pusher uses

(i) notification (Notification)/signal (Signal)

Notifications are the simplest examples and are most often used. Signals can also be seen as a form of notification, except that the signal has no UI.

(ii) Activity streamsactivity Streams (feeds) is at the heart of social networking. such as the point of the circle of friends like and comment, a can see in real-time B's likes, B can see a in real-time comments.

(c) Real-time data visualization such as real-time display of polls in the dashboard data panel, or real-time display of weather conditions, etc.

(iv) Chat

Real-time display of chat information, such as.

Wait a minute. Specific to see pusher use Cases

2. Pusher main content This part mainly includes registering pusher account, registering pusher ID and key in PHP program, integrating pusher PHP package and JavaScript package into Laravel, and how to debug pusher program.

2.1 Register Pusher Account

Registered Pusher account: can register here: Pusher registration, registered account is mainly to obtain Appid,secret and key three authentication key, and after registering to enter the personal page, you can use pusher pusher Debug Console to view the interface invocation situation. You can sign in with your GitHub account.

After successful registration into the personal background panel, you can create a new application name, there will be a key to the new program, and the Second tab on the right side of the debug console, to debug the View interface calls, etc. will be used:

2.2 Laravel Program installation first global installation composer:

    Curl-ss Https://getcomposer.org/installer | PHP    MV Composer.phar/usr/local/bin/composer

Create a new empty folder, under Folders, and then use composer to install the Laravel project:

Composer Create-project Laravel/laravel Mylaravelapp--prefer-dist

2.3 Configure the Pusher authentication key to add a key in the. env file of the project root, replace the key you just acquired with your own,. env file is a Laravel Project profile:

Pusher_app_id=your_app_idpusher_key=your_app_keypusher_secret=your_app_secret

The pusher is then integrated into the laravel back end, in two ways: using Laravel pusher Bridge, using laravel Event broadcaster.

2.4 Laravel Pusher Bridge find pusher in the PHP package repository, install:

Composer require Vinkla/pusher

After the installation of services, service provider is mainly to just download the service (package) registered in the Laravel container, each service (package) has a corresponding service Privider:

Vinkla\pusher\pusherserviceprovider::class,

At the same time, the configuration file of this package is copied to the Config folder, and a pusher.php file is added to the Config folder:

PHP Artisan Vendor:publish

Update the following configuration file in the config/pusher.php file:

' Connections ' = [    ' main ' = ' = '        auth_key ' + env (' Pusher_key '),        ' secret ' = env (' Pusher_ SECRET '),        ' app_id ' = env (' pusher_app_id '),        ' options ' = [],        ' host ' = null,        ' port ' = NULL,        ' timeout ' = null,    ],

There is an installation bug: If you also configure facade in config/app.php, you will get an error, so don't configure it. You can use \illuminate\support\facades\app::make (' pusher ') to remove the pusher service from the Laravel container container. You can generally use facade to remove the service from the container, but this package does not work, there are bugs. The following sentence does not need to be added to the config/app.php aliases[] array.

' Pusher ' = Vinkla\pusher\facades\pusher::class

After configuring and installing this package, you can use it to detect:

Get ('/bridge ', function () {    $pusher = \illuminate\support\facades\app::make (' pusher ');    $pusher->trigger (' Test-channel ',                      ' test-event ',                       [' text ' = ' I love China!!! ']                    );    Return ' This is a Laravel pusher Bridge test! ';});

In the Mamp pro environment, the Apache port is 8888, the Http://laravelpusher.app:8888/bridge route is entered in the browser, and the correct return is a Laravel pusher bridge test! , stating that pusher has been triggered. You can view the trigger in Pusher Debug console background:

Indeed, it is working! It's simple, isn't it.

2.5 Laravel Event Broadcaster

Laravel5.1 later provides the event broadcaster feature, the profile is config/broadcasting.php, and the default driver is pusher: ' Default ' = env (' Broadcast_ DRIVER ', ' pusher '), if it is not possible to add broadcast_driver=pusher in the. env file. In short, you do not need to modify what configuration. Broadcasting.php is also the key to read the pusher:

' Connections ' = [        ' pusher ' + ['            driver ' = ' pusher ',            ' key ' = ' env ' (' Pusher_key '),            ' Secret ' + env (' Pusher_secret '),            ' app_id ' + env (' pusher_app_id '),            ' options ' = [                //            ],        ],        ...

Now that the event is broadcast, it is necessary to generate events and corresponding listeners, write any one event name such as Someevent in app/providers/eventserviceprovider.php, and the corresponding listener such as EventListener:

protected $listen = [        ' app\events\pusherevent ' = [            ' App\listeners\pushereventlistener ',        ],    ];

Then generate the event and the corresponding listener in the project root directory:

PHP Artisan Event:generate

In Laravel events, if a broadcast is required, the Illuminatecontractsbroadcastingshouldbroadcast interface must be implemented, and the public property in the event is serialized into the broadcast data. That is, the public property data is sent. Also, you need to write a broadcast channel of any character in the Broadcaston () function:

Class Pusherevent extends Event implements shouldbroadcast{use    serializesmodels;    Public $text, $id;    /**     * Create A new event instance.     *     * @return void     *    /Public Function __construct ($text, $id)    {        $this->text = $text;        $this->id   = $id;    }    /**     * Get The channels the event should is broadcast on.     *     * @return Array     *    /Public Function Broadcaston ()    {        return [' Laravel-broadcast-channel '];    }}

OK, and then trigger this event, in order to be simple, trigger directly in the route:

Route::get ('/broadcast ', function () {    event (new \app\events\pusherevent (' Great Wall is great ', ' 1 '));    Return ' This is a Laravel broadcaster test! ';});

To view the trigger results in the pusher Debug console:

It is working!.

Where ' Laravel-broadcast-channel ' is the channel property, Appeventspusherevent is the event property, and the public property of Pusherevent is the data being broadcast, In order to verify that only the public property is broadcast:

Class Pusherevent extends Event implements shouldbroadcast{use    serializesmodels;    Public $text, $id;    Private $content;    protected $title;    /**     * Create A new event instance.     *     * @return void     *    /Public Function __construct ($text, $id, $content, $title)    {        $this->text< c12/>= $text;        $this->id      = $id;        $this->content = $content;        $this->title   = $title;    }    /**     * Get The channels the event should is broadcast on.     *     * @return Array     *    /Public Function Broadcaston ()    {        return [' Laravel-broadcast-channel '];    }}//routes.php in Route::get ('/broadcast ', function () {    event (new \app\events\pusherevent Attribute ', ' 2 ', ' This was a private attribute ', ' This is a protected attribute ');    Return ' This is a Laravel broadcaster Test, and private/protected attribute was not fired! ';});

Re-trigger View pusher Debug Console, it is true that only the public property data is broadcast:

2.6 Laravel Pusher Bridge vs Laravel Event Broadcaster

Using Laravel Pusher bridge can not be bound by some rules of the event broadcaster, and can be obtained through the pusher instance to obtain other services provided by pusher such as verifying channel subscriptions, querying program status, and so on. With Laravel Event broadcaster, however, you can decouple the module and switch services quickly when there are other better push packages. You can choose the appropriate method.

2.7 Debugging Pusher server-side Integration Pack This section mainly covers debugging using the Laravel Pusher Bridge method as an event broadcast. Use the log module of the pusher PHP package and debug it with the Laravel log module:

Use Illuminate\support\facades\app;use illuminate\support\facades\log;class laravelloggerproxy{public    function log ($msg)    {        log::info ($msg);    }} Class Appserviceprovider extends serviceprovider{    /**     * Bootstrap any application services.     *     * @return void     *    /Public Function boot ()    {        $pusher = app::make (' pusher ');        $pusher->set_logger ();    }    ...

The author in the personal environment, input http://laravelpusher.app:8888/bridge, in the Storage/logs/laravel.log will appear similar to the following debugging information, you can first empty the next Laravel.log file and then view:

[2016-04-25 02:25:10] Local.INFO:Pusher:->trigger received string channel "Test-channel". converting to array.  [2016-04-25 02:25:10] Local.INFO:Pusher:curl_init (http://api.pusherapp.com:80/apps/200664/events?auth_key= ae93fbeaff568a9223d3&auth_signature=ff8ce0b76038aea6613b4849ddda1b2bd0b14976738e8751264bf8f3cab3bc41& AUTH_TIMESTAMP=1461551110&AUTH_VERSION=1.0&BODY_MD5=BDE7265F1C9DA80CE0A3E0BDE5886B5A)  [2016-04-25 02:25:10] Local.INFO:Pusher:trigger POST: {"name": "Test-event", "Data": "{\" text\ ": \" I love China!!! \ "}", "Channels": ["Test-channel"]}  [2016-04-25 02:25:11] Local.INFO:Pusher:exec_curl response:array (    [body ] = = {}    [status] = 200)

Debug information can be seen, using pusher is toward this interface http://api.pusherapp.com:80/apps/200664/events?auth_key=&auth_signature=&auth_ Timestamp=&auth_version=&body_md5= post data, the data is mainly 3: Channel channels (such as: Test-channel), event events (such as: test-event) Data (such as: I love China). Finally returns the response, State 200, which indicates that the send was successful. Debug messages are not printed in Laravel.log if the input route http://laravelpusher.app:8888/broadcast.

There is time to see Laravel debug Bar, is a package for Laravel debugging, Address: Laravel Debug Bar, this Daniel also wrote a Laravel IDE helper is also very useful: Laravel IDE Helper. It is highly recommended that you install both packages into your project, and each new Laravel project can be installed.

2.8 Using pusher JavaScript packages

OK, now that the server is working properly, start by studying the client to receive the data sent by the server when the event is triggered.

You can create a new view, or use the view of an existing welcome.blade.php, but first write off the file so that it is slow to load each time. Write the code in the file:

Load the Pusher JS packet, then use the Pusher object to subscribe to the channel, and then use the channel binding trigger event, the closure returns the received data. Subscribe here to the Test-channel channel written in Laravel Pusher bridge, bind Test-event event, print the data of the Text property, we know above we write data for [' text ' = ' I love Chinese!!! '] , that the client printing data should be ' I love the China!!! ' to see if it is. Enter Http://laravelpusher.app:8888/bridge in the route to see what happens to pusher Debug console:

Then open a new tab and enter the route to see the console window printing information:

It is working!

You can refresh the route multiple times and switch between two tab pages to see the printed data. A page trigger Event B page can receive data, B page trigger event a page receives data.

2.9 Debugging pusher JavaScript clients can use the Pusher Debug Console Control Panel to view the triggering situation and, of course, to print debug information on the client:

  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.