You will need PHP 7.1 and Composer installed on your machine.
Note: We're going to be working with YAML files quite a bit in this article. In YAML, indentation matters, so be careful to stick to what is shown!
You'll notice we're calling the non-existent method getVisitorCount() to get the current visitor count before rendering the page. We'll come back to that in a bit.
An existing channel (let's call this visitor-updates). This is the channel where it will receive updates on the number of visitors.
A new channel with a randomly generated name. The purpose of this channel is to trigger a Pusher event called channel_occupied, which will be sent via a webhook to our backend. Also, when the user leaves the page, the Pusher connection will be terminated, resulting in a channel_vacated notification.
It broadcasts the new value on the visitor-updates channel. Pages subscribed to this channel can then update their UI to reflect the new value.
It records this new value in a cache so that when rendering a new page, it can retrieve the number from the cache (in the getVisitorCount method).
We're referencing a few variables here in the view (pusherKey, pusherCluster) which we haven't defined in the controller. We'll get to that in a moment. First, let's configure Pusher on our backend.
Note: When installing this, Symfony Flex will ask you if you want to execute the recipe. Choose 'yes'. You can read more about Symfony Flex here.
The saveVisitorCount method is where we store the new visitor count in the cache. We'll implement that now.
We're using a cache to store the current visitor count so we can track it across sessions. To keep this demo simple, we'll use a file on our machine as our cache. Let's do this.
We need to do a few things before our webhook is ready for use.
Copy the second Forwarding URL (the one using HTTPS). Your webhook URL will then be <your-ngrok-url>/webhook (for instance, for the screenshot above, my webhook URL is https://fa74c4e1.ngrok.io/webhook).
Next, you'll need to enable channel existence webhooks for our Pusher app. On your Pusher app dashboard, click on the Webhooks tab and select the Channel existence radio button. In the text box, paste the URL of the webhook you obtained above, and click Add. Good to go!
Now visit http://localhost:8000/home in a browser. Open it in multiple tabs and you should see the number of visitors go up or down as you open and close tabs.
This has the same effect as telling the app to use a new cache folder.
In this article, we've built a simple demo showing how we can add realtime capabilities to a Symfony app. We could go on to display the number of actual users by filtering by factors such as their IP address. If our app involved signing in, we could even use presence channels to know who exactly was viewing the page. I hope you enjoyed this tutorial. You can check out the source code of the completed application on GitHub.