Introduction to Popmotion: Pointers and Physics

Welcome back to the Introduction to Popmotion tutorial series. In part 1, we discovered how to use tweens and keyframes to make precise, time-scheduled animations.

In Part 2, we’re going to look at pointer tracking and velocity-based animations.

Pointer tracking allows us to create scrollable product shelves, custom value sliders, or drag-and-drop interfaces.

Velocity-based animations are different to a time-based animation like tween in that the primary property that affects how the animation behaves is velocity. The animation itself might take any amount of time.

We’ll look at the three velocity-based animations in Popmotion, springdecay, and physics. We’ll use the velocity of the pointer tracking animation to start these animations, and that’ll demonstrate how velocity-based animations can create engaging and playful UIs in a way that time-based animations simply can’t.

First, open this CodePen to play along.

Pointer Tracking

Popmotion provides the pointer function to track and output the coordinates of either a mouse or single touch pointer.

Let’s import this along with styler, which will allow us to set the position of the ball.

For this example, we want to drag the ball. Let’s add an event that will output the pointer’s position to the ball:

We’ll also want some code to stop tracking when we release the ball:

If you try and drag the ball now, there’s an obvious problem. The ball jumps away when we touch it! Not a great user experience.

This is because, by default, pointer outputs the pointer’s position relative to the page.

To output the pointer’s position relative to another point, in this case the ball’s x/y transform, we can simply pass that position to pointer like this:

Now you’ve made the ball, in very few lines of code, draggable! However, when the user releases the ball, it stops dead.

This isn’t satisfying: Imagine a scrollable carousel of products that a user can drag to scroll. If it just stopped dead instead of momentum scrolling, it’d be less pleasurable to use.

It’d be harder, too, because the overall physical effort needed to scroll the carousel would be higher.

To enable animations like this, we first need to know the velocity of the object being thrown.

Track Velocity

Popmotion provides a function that can help us track velocity. It’s called value. Let’s import that:

To speak technically for a moment, all of Popmotion’s animations are known as actions. Actions are reactive streams of values that can be started and stopped.

A value is, conversely, a reaction. It can’t be stopped or started. It just passively responds when its update method is called. It can keep track of values and can be used to query their velocity.

So, after we define ballStyler, let’s define a new value for ballXY:

Whenever ballXY updates, we want to update ballStyler. We can pass a second argument to value, a function that will run whenever ballXY updates:

Now we can rewrite our pointer to update ballXY instead of ballStyler.set:

Now, at any pointer, we can call ballXY.getVelocity() and we’ll receive the velocities of both x and y, ready to plug into our velocity-based animations.

Velocity-Based Animations

spring

The first velocity-based animation to introduce is spring. It’s based on the same equations that govern Apple’s CASpringAnimation, the spring animation behind all that iOS springy playfulness.

Import:

Now, amend stopTracking so that instead of stopping the pointerTracker animation, it starts a spring animation like this:

We provide it with the ball’s current position, its velocity, and a target, and the simulation is run. It changes depending on how the user has thrown the ball.

The cool thing about springs is they’re expressive. By adjusting the massstiffness and damping properties, you can end up with radically different spring-feels.

For instance, if you only change the stiffness above to 1000, you can create a motion that feels like high-energy snapping. Then, by changing mass to 20, you create motion that looks almost like gravity.

There’s a combination that will feel right and satisfying for your users, and appropriate to your brand, under almost any circumstance. By playing with different spring-feels, you can communicate different feelings, like a strict out-of-bounds snap or a softer affirmative bounce.

decay

The decay animation, as the name suggests, decays the provided velocity so that the animation gradually slows to a complete stop.

This can be used to create the momentum scrolling effect found on smartphones, like this:

Import the decay function:

And replace the stopTracking function with the following:

decay automatically calculates a new target based on the provided from and velocity props.

It’s possible to adjust the feel of the deceleration by messing with the props outlined in the docs linked above but, unlike spring and physicsdecay is designed to work out of the box. 

physics

Finally, we have the physics animation. This is Popmotion’s Swiss Army knife of velocity-based animations. With it, you can simulate:

  • constant velocity
  • acceleration
  • springs
  • friction

spring and decay offer super-precise motion and a wider variety of “feels”. Soon, they’ll both also be scrubbable.

But both are immutable. Once you’ve started either, their properties are set in stone. Perfect for when we want to start an animation based on the initial from/velocity state, but not so good if we want ongoing interaction.

physics, instead, is an integrated simulation closer to that of a video game. It works by, once per frame, taking the current state and then modifying it based on the current properties at that point in time.

This allows it to be mutable, which means we can change those properties, which then changes the outcome of the simulation.

To demonstrate this, let’s make a twist on classic pointer smoothing, with elastic smoothing.

Import physics:

This time, we’re going to change the startTracking function. Instead of changing ballXY with pointer, we’ll use physics:

Here, we’re setting from and velocity as normal. friction and springStrength both adjust the properties of the spring.

restSpeed: false overrides the default behaviour of the animation stopping when motion stops. We want to stop it manually in stopTracking.

On its own, this animation won’t do anything because we set to, the spring’s target, to the same as from. So let’s reimplement the pointer tracking this time to change the spring target of physics. On the last line of startTracking, add:

Here, we’re using a similar pointer animation as before. Except this time, we’re using it to change the target of another animation. In doing so, we create this elasticated pointer tracking:

Conclusion

Velocity-based animations paired with pointer tracking can create engaging and playful interfaces.

spring can be used to create a wide-variety of spring-feels, while decay is specifically tailored for momentum scroll animations. physics is more limited than either in terms of configurability, but also provides the opportunity to change the simulation in progress, opening new interaction possibilities.

In the next and final part of this introductory series on Popmotion, we’re going to take everything we’ve learned in the first two parts and use them along with some light functional composition to create a scrubbable animation, along with a scrubber to do the scrubbing with!


Source: Nettuts Web Development

New Course: Connect to a Database With Laravel’s Eloquent ORM

Final product image
What You’ll Be Creating

In our new course, Connect to a Database With Laravel’s Eloquent ORM, you’ll learn all about Eloquent, which makes it easy to connect to relational data in a database and work with it using object-oriented models in your Laravel app. It is simple to set up, easy to use, and packs a lot of power.

What You’ll Learn

In this course, Envato Tuts+ instructor Jeremy McPeak will teach you how to use Eloquent, Laravel’s object-relational mapper (ORM). 

Connect to a Database With Laravel's Eloquent ORM screenshot

Follow along as Jeremy builds the data back-end for a simple guitar database app. You’ll learn how to create data tables with migrations, how to create data models, and how to use Eloquent for querying and mutating data.

Watch the Introduction

 

Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 580,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.


Source: Nettuts Web Development

How to Make a Real-Time Sports Application Using Node.js

Final product image
What You’ll Be Creating

In today’s article
I’m going to demonstrate how to make a web application that will display live
game scores from the NHL. The scores will update automatically as the games
progress.

This is a very
exciting article for me, as it allows me the chance to bring two of my favorite
passions together: development and sports.

The technologies
that will be used to create the application are:

  1. Node.js
  2. Socket.io
  3. MySportsFeed.com

If you don’t have
Node.js installed, visit their download
page
now and set it up before continuing.

What Is Socket.io?

Socket.io is a
technology that connects a client to a server. In this example, the client is a
web browser and the server is the Node.js application. The server can have
multiple clients connected to it at any given time.

Once the connection
has been established, the server can send messages to all of the clients or an
individual client. In return, the client can send a message to the server, allowing for bi-directional real-time communication.

Before Socket.io,
web applications would commonly use AJAX, and both the client and server would
poll each other looking for events. For example, every 10 seconds an AJAX call
would occur to see if there were any messages to handle.

Polling for messages
caused a significant amount of overhead on both the client and server as it
would be constantly looking for messages when there were none.

With Socket.io, messages are received instantaneously, without needing to look for messages, reducing the overhead.

Sample
Socket.io Application

Before we consume
the real-time sports data, let’s create an example application to demonstrate
how Socket.io works.

To begin, I am going
to create a new Node.js application. In a console window, I am going to
navigate to C:GitHubNodeJS, create a new folder for my application, and
create a new application:

I used all the
default settings.

Because we are
making a web application, I’m going use an NPM package called Express to
simplify the setup. In a command prompt, install it as follows: npm install express
--save

And of course we
will need to install the Socket.io package: npm install
socket.io --save

Let’s begin by
creating the web server. Create a new file called index.js and place the
following code within it to create the web server using Express:

If you are not
familiar with Express, the above code example includes the Express library and
creates a new HTTP server. In this example, the HTTP server is listening on
port 3000, e.g. http://localhost:3000. A
route is created at the root of the site “/”. The result of the route
returns an HTML file: index.html.

Before we create the
index.html file, let’s finish the server by setting up Socket.io. Append the
following to your index.js file to create the Socket server:

Similar to Express,
the code begins by importing the Socket.io library. This is stored in a
variable called io. Next, using the io variable, an event handler is created with
the on function. The event being
listened for is connection. This event
is called each time a client connects to the server.

Let’s now create our
very basic client. Create a new file called index.html and place the following
code within:

The HTML above loads
the Socket.io client JavaScript and initializes a connection to the server. To
see the example, start your Node application: node index.js

Then, in your browser, navigate to http://localhost:3000. Nothing
will appear on the page; however, if you look at the console where the Node
application is running, two messages are logged:

  1. HTTP server started on port
    3000
  2. Client connection received

Now that we have a
successful socket connection, let’s put it to use. Let’s begin by sending a
message from the server to the client. Then, when the client receives the
message, it can send a response back to the server.

Let’s look at the
abbreviated index.js file:

The previous io.on function has been updated to include a
few new lines of code. The first, socket.emit, sends the message to the client. The sendToClient
is the name of the event. By naming events, you can send different types of
messages so the client can interpret them differently. The second addition is
the socket.on, which also contains an
event name: receivedFromClient. This
creates a function that accepts data from the client. In this case, the data is
logged to the console window.

That completes the
server-side amendments; it can now send and receive data from any connected
clients.

Let’s complete this
example by updating the client to receive the sendToClient
event. When it receives the event, it can respond with the receivedFromClient event back to the server.

This is accomplished
in the JavaScript portion of the HTML, so in the index.html
file, I have updated the JavaScript as follows:

Using the
instantiated socket variable, we have
very similar logic on the server with a socket.on
function. For the client, it is listening to the sendToClient
event. As soon as the client is connected, the server sends this message. When
the client receives it, it is logged to the console in the browser. The client
then uses the same socket.emit that the
server used to send the original event. In this instance, the client sends back
the receivedFromClient event to the
server. When the server receives the message, it is logged to the console
window.

Try it out for
yourself. First, in a console, run your Node application: node index.js. Then load http://localhost:3000 in your browser.

Check the web
browser console and you should see the following JSON data logged: {hello:
"world"}

Then, in the command
prompt where the Node application is running, you should see the following:

Both the client and
server can use the JSON data received to perform specific tasks. We will learn
more about that once we connect to the real-time sports data.

Sports
Data

Now that we have
mastered how to send and receive data to and from the client and server, this
can be leveraged to provide real-time updates. I chose to use sports data,
although the same theory is not limited to sports. Before I began this project,
I researched different sports data. The one I settled on, because they offer
free developer accounts, was MySportsFeeds (I am not affiliated with them in any way). To access the real-time
data, I signed up for an account and then made a small donation. Donations start at
$1 to have data updated every 10 minutes. This will be good for the example.

Once your account is
set up, you can proceed to setting up access to their API. To assist with this,
I am going to use their NPM package: npm install
mysportsfeeds-node --save

After the package
has been installed, API calls can be made as follows:

In the example
above, be sure to replace the call to the authenticate
function with your username and password.

The following code
executes an API call to the get the NHL scoreboard for today. The fordate variable is what specifies today. I’ve
also set force to true so that a response is always returned, even when the data has not changed.

With the current
setup, the results of the API call get written to a text file. In the final
example, this will be changed; however, for demonstration purposes, the results
file can be reviewed in a text editor to understand the contents of the
response. The results contain a scoreboard
object. This object contains an array called gameScore.
This object stores the result of each game. Each object contains a child object
called game. This object provides the
information about who is playing.

Outside of the game
object, there are a handful of variables that provide the current state of the
game. The data changes based on the state of the game. For example, when the
game hasn’t started, there are only a few variables that tell us the game is not
in progress and has not started.

When the game is in
progress, additional data is provided about the score, what period the game is
in, and how much time is remaining. We will see this in action when we get to
the HTML to show the game in the next section.

Real-Time Updates

We have all the
pieces to the puzzle, so it is now time to put the puzzle together to reveal the
final picture. Currently, MySportsFeeds has limited support for pushing data to
us, so we will have to poll the data from them. Luckily, we know the data only
changes once every 10 minutes, so we don’t need to add overhead by polling for
changes too frequently. Once we poll the data from them, we can push those
updates from the server to all clients connected.

To perform the
polling, I will use the JavaScript setInterval
function to call the API (in my case) every 10 minutes to look for updates.
When the data is received, an event is sent to all of the connected clients.
When the clients receive the event, the game scores will be updated with
JavaScript in the web browser.

MySportsFeeds will
also be called when the Node application first starts up. This data will be
used for any clients who connect before the first 10-minute interval. This is
stored in a global variable. This same global variable is updated as part of
the interval polling. This will ensure that when any new clients connect after
the polling, they will have the latest data.

To assist with some
code cleanliness in the main index.js
file, I have created a new file called data.js.
This file will contain a function that is exported (available in the index.js file) that performs the previous call
to the MySportsFeeds API. Here are the full contents of that file:

A getData function is exported and returns the
result of the call, which in this case is a Promise
that will be resolved in the main application.

Now let’s look at
the final contents of the index.js file:

The first seven lines of
code above instantiate the required libraries and the global latestData variable. The final list of
libraries used are: Express, Http Server created with Express, Socket.io, and
the aforementioned data.js file just
created.

With the necessities
taken care of, the application populates the latestData
for clients who will connect when the server is first started:

The next few lines
set up a route for the root page of the website (http://localhost:3000/) and start the HTTP
server to listen on port 3000.

Next, the Socket.io
is set up to look for connections. When a new connection is received, the server
emits an event called data with the
contents of the latestData variable.

And finally, the
final chunk of code creates the polling interval. When the interval occurs, the
latestData variable is updated with the
results of the API call. This data then emits the same data event to all clients.

You may notice that
when the client connects and an event is emitted, it is emitting the event with
the socket variable. This approach will
send the event to that connected client only. Inside the interval, the global io is used to emit the event. This will send
the event to all clients.

That completes the
server. Let’s work on the client front-end. In an earlier example, I created a basic index.html file that
set up the client connection that would log events from the server and send one
back. I am going to extend that file to contain the completed example.

Because the server
is sending us a JSON object, I am going to use jQuery and leverage a jQuery
extension called JsRender.
This is a templating library. It will allow me to create a template with HTML
that will be used to display the contents of each NHL game in an easy-to-use, consistent manner. In a moment, you will see the power of this library. The
final code is over 40 lines of code, so I am going to break it down into
smaller chunks, and then display the full HTML together at the end.

This first part
creates the template that will be used to show the game data:

The template is
defined using a script tag. It contains
the id of the template and a special script type called text/x-jsrender. The
template defines a container div for
each game that contains a class game to
apply some basic styling. Inside this div, the templating begins.

In the next div, the
away and home team are displayed. This is done by concatenating the city and
team name together from the game object
from the MySportsFeed data.

{{:game.awayTeam.City}} is
how I define an object that will be replaced with a physical value when the
template is rendered. This syntax is defined by the JsRender library.

Once the teams are
displayed, the next chunk of code does some conditional logic. When the game is
unPlayed, a string will be outputted
that the game will start at {{:game.time}}.

When the game is not
completed, the current score is displayed: Current Score: {{:awayScore}} -
{{:homeScore}}
. And finally, some tricky little logic to identify what period
the hockey game is in or if it is in intermission.

If the variable currentIntermission is provided in the
results, then I use a function I defined called ordinal_suffix_of, which will convert the period number to read: 1st (2nd, 3rd, etc.)
Intermission.

When it is not in
intermission, I look for the currentPeriod
value. This also uses the ordinal_suffix_of  to show that the game is in the 1st (2nd, 3rd,
etc.) period.

Beneath this,
another function I defined called time_left
is used to convert the number of seconds remaining into the number of
minutes and seconds remaining in the period. For example: 10:12.

The final part of
the code displays the final score because we know the game has completed.

Here is an example
of what it looks like when there is a mix of finished games, in progress games,
and games that have not started yet (I’m not a very good designer, so it looks
as you would expect when a developer makes their own User Interface).

An example of finished games

Next up is a chunk
of JavaScript that creates the socket, the helper functions ordinal_suffix_of
and time_left, and a variable that references the jQuery template created.

The final piece of
code is the code to receive the socket event and render the template:

I have a placeholder
div with the id of data. The result of
the template rendering (tmpl.render) writes the HTML to this container. What is
really neat is that the JsRender library can accept an array of data, in this
case data.scoreboard.gameScore, that
iterates through each element in the array and creates one game per element.

Here is the final
HTML and JavaScript all together:

Start the Node
application and browse to http://localhost:3000
to see the results for yourself!

Every X minutes, the
server will send an event to the client. The client will redraw the game
elements with the updated data. So when you leave the site open and
periodically look at it, you will see the game data refresh when games are
currently in progress.

Conclusion

The final product
uses Socket.io to create a server that clients connect to. The server fetches
data and sends it to the client. When the client receives the data, it can
seamlessly update the display. This reduces load on the server because the
client only performs work when it receives an event from the server.

Sockets are not
limited to one direction; the client can also send messages to the server. When
the server receives the message, it can perform some processing.

Chat applications
would commonly work this way. The server would receive a message from the
client and then broadcast to all connected clients to show that someone has
sent a new message.

Hopefully you
enjoyed this article as I had a blast creating this real-time sports
application for one of my favorite sports!


Source: Nettuts Web Development

How to Create a Custom Settings Panel in WooCommerce

Final product image
What You’ll Be Creating

WooCommerce is by far the leading ecommerce plugin for WordPress. At the time of writing, it has over 3 million active installations and is reportedly behind over 40% of all online stores.

One of the reasons for WooCommerce’s popularity is its extendability. Like WordPress itself, WooCommerce is packed full of actions and filters that developers can hook into if they want to extend WooCommerce’s default functionality.

A great example of this is the ability to create a custom data panel.

What’s Covered in This Tutorial?

This tutorial is split into two parts. In part one, we’re going to be looking at:

  • adding a custom panel to WooCommerce
  • adding custom fields to the panel
  • sanitizing and saving custom field values

Then in part two, we’ll look at:

  • displaying custom fields on the product page
  • changing the product price depending on the value of custom fields
  • displaying custom field values in the cart and order

What Is a WooCommerce Custom Data Panel?

When you create a new product in WooCommerce, you enter most of the critical product information, like price and inventory, in the Product data section.

WooCommerce custom data panel

In the screenshot above, you can see that the Product data section is divided into panels: the tabs down the left, e.g. General, Inventory, etc., each open different panels in the main view on the right.

In this tutorial, we’re going to look at creating a custom panel for product data and adding some custom fields to it. Then we’ll look at using those custom fields on the front end and saving their values to customer orders.

In our example scenario, we’re going to add a ‘Giftwrap’ panel which contains some custom fields:

  • a checkbox to include a giftwrapping option for the product on the product page
  • a checkbox to enable an input field where a customer can enter a message on the product page
  • an input field to add a price for the giftwrapping option; the price will be added to the product price in the cart

In the back end, it’s going to look like this:

Giftwrap panel

And on the front end, it will look something like this:

Front end example

Create a New Plugin

Because we’re extending functionality, we’re going to create a plugin rather than adding our code to a theme. That means that our users will be able to retain this extra functionality even if they switch their site’s theme. Creating a plugin is out of scope for this tutorial, but if you need some help, take a look at this Tuts+ Coffee Break Course on creating your first plugin: 

Our plugin is going to consist of two classes: one to handle stuff in the admin, and one to handle everything on the front end. Our plugin file structure is going to look like this:

Project structure

Admin Class

First up, we need to create our class to handle everything on the back end. In a folder called classes, create a new file called class-tpwcp-admin.php.

This class will handle the following:

  • Create the custom tab (the tab is the clickable element down the left of the Product data section).
  • Add the custom fields to the custom panel (the panel is the element that’s displayed when you click a tab).
  • Decide the product types where the panel will be enabled.
  • Sanitize and save the custom field values.

Paste the following code into that new file. We’ll walk through it step by step afterwards.

Create the Custom Tab

To create the custom tab, we hook into the woocommerce_product_data_tabs filter using our create_giftwrap_tab function. This passes the WooCommerce $tabs object in, which we then modify using the following parameters:

  • label: use this to define the name of your tab.
  • target: this is used to create an anchor link so needs to be unique.
  • class: an array of classes that will be applied to your panel.
  • priority: define where you want your tab to appear.

Product Types

At this stage, it’s worth considering what product types we’d like our panel to be enabled for. By default, there are four WooCommerce product types: simple, variable, grouped, and affiliate. Let’s say for our example scenario, we only want our Giftwrap panel to be enabled for simple and variable product types.

To achieve this, we add the show_if_simple and show_if_variable classes to the class parameter above. If we didn’t want to enable the panel for variable product types, we’d just omit the show_if_variable class.

Add Custom Fields

The next hook we use is woocommerce_product_data_panels. This action allows us to output our own markup for the Giftwrap panel. In our class, the function display_giftwrap_fields creates a couple of div wrappers, inside which we use some WooCommerce functions to create custom fields. 

Note how the id attribute for our outer div, giftwrap_panel, matches the value we passed into the target parameter of our giftwrap tab above. This is how WooCommerce will know to display this panel when we click the Giftwrap tab.

WooCommerce Custom Field Functions

In our example, the two functions we’re using to create our fields are:

  • woocommerce_wp_checkbox
  • woocommerce_wp_text_input

These functions are provided by WooCommerce specifically for the purpose of creating custom fields. They take an array of arguments, including:

  • id: this is the ID of your field. It needs to be unique, and we’ll be referencing it later in our code.
  • label: this is the label as it will appear to the user.
  • desc_tip: this is the optional tool tip that appears when the user hovers over the question mark icon next to the label.

Note also that the woocommerce_wp_text_input function also takes a type argument, where you can specify number for a number input field, or text for a text input field. Our field will be used to input a price, so we specify it as number.

Save the Custom Fields

The final part of our admin class uses the woocommerce_process_product_meta action to save our custom field values.

In order to standardize and optimize how it stores and retrieves data, WooCommerce 3.0 adopted a CRUD (Create, Read, Update, Delete) method for setting and getting product data. You can find out more about the thinking behind this in the WooCommerce 3.0 announcement.

With this in mind, instead of the more familiar get_post_meta and update_post_meta methods that we might have used in the past, we now use the $post_id to create a WooCommerce $product object, and then apply the update_meta_data method to save data. For example:

Please note also that we’re careful to sanitize our data before saving it to the database. There’s more information on sanitizing data here: 

Main Plugin File

When you’ve created your readme.txt file and your main plugin file tutsplus-woocommerce-panel.php, you can add this code to your main file.

This will initiate your admin class.

When you activate your plugin on a site (along with WooCommerce) and then go to create a new product, you’ll see your new Giftwrap panel available, along with custom fields. You can update the fields and save them… But you won’t see anything on the front end yet.

Conclusion

Let’s just recap what we’ve looked at so far in this article.

We’ve looked at an example scenario for adding a custom ‘Giftwrap’ panel to WooCommerce. We’ve created a plugin and added a class to create the panel. Within the class, we’ve also used WooCommerce functions to add custom fields, and then we’ve sanitized and saved those field values.


Source: Nettuts Web Development

How Laravel Broadcasting Works

Today, we are going to explore the concept of broadcasting in the Laravel web framework. It allows you to send notifications to the client side when something happens on the server side. In this article, we are going to use the third-party Pusher library to send notifications to the client side.

If you have ever wanted to send notifications from the server to the client when something happens on a server in Laravel, you’re looking for the broadcasting feature.

For example, let’s assume that you’ve implemented a messaging application that allows users of your system to send messages to each other. Now, when user A sends a message to user B, you want to notify user B in real time. You may display a popup or an alert box that informs user B about the new message!

It’s the perfect use-case to walk through the concept of broadcasting in Laravel, and that’s what we’ll implement in this article.

If you are wondering how the server could send notifications to the client, it’s using sockets under the hood to accomplish it. Let’s understand the basic flow of sockets before we dive deeper into the actual implementation.

  • Firstly, you need a server that supports the web-sockets protocol and allows the client to establish a web socket connection.
  • You could implement your own server or use a third-party service like Pusher. We’ll prefer the latter in this article.
  • The client initiates a web socket connection to the web socket server and receives a unique identifier upon successful connection.
  • Once the connection is successful, the client subscribes to certain channels at which it would like to receive events.
  • Finally, under the subscribed channel, the client registers events that it would like to listen to.
  • Now on the server side, when a particular event happens, we inform the web-socket server by providing it with the channel name and event name.
  • And finally, the web-socket server broadcasts that event to registered clients on that particular channel.

Don’t worry if it looks like too much in a single go; you will get the hang of it as we move through this article.

Next, let’s have a look at the default broadcast configuration file at config/broadcasting.php.

By default, Laravel supports multiple broadcast adapters in the core itself.

In this article, we are going to use the Pusher broadcast adapter. For debugging purposes, you could also use the log adapter. Of course, if you’re using the log adapter, the client won’t receive any event notifications, and it’ll only be logged to the laravel.log file.

From the next section onward, we’ll right away dive into the actual implementation of the aforementioned use-case.

Setting Up the Prerequisites

In broadcasting, there are different types of channels—public, private, and presence. When you want to broadcast your events publicly, it’s the public channel that you are supposed to use. Conversely, the private channel is used when you want to restrict event notifications to certain private channels.

In our use-case, we want to notify users when they get a new message. And to be eligible to receive broadcast notifications, the user must be logged in. Thus, we’ll need to use the private channel in our case.

Core Authentication Feature

Firstly, you need to enable the default Laravel authentication system so that features like registration, login and the like work out of the box. If you’re not sure how to do that, the official documentation provides a quick insight into that.

Pusher SDK—Installation and Configuration

As we’re going to use the Pusher third-party service as our web-socket server, you need to create an account with it and make sure you have the necessary API credentials with your post registration. If you’re facing any trouble creating it, don’t hesitate to ask me in the comment section.

Next, we need to install the Pusher PHP SDK so that our Laravel application can send broadcast notifications to the Pusher web-socket server.

In your Laravel application root, run the following command to install it as a composer package.

Now, let’s change the broadcast configuration file to enable the Pusher adapter as our default broadcast driver.

As you can see, we’ve changed the default broadcast driver to Pusher. We’ve also added cluster and encrypted configuration options that you should have got from the Pusher account in the first place.

Also, it’s fetching values from environment variables. So let’s make sure that we do set the following variables in the .env file properly.

Next, I had to make a few changes in a couple of core Laravel files in order to make it compatible with the latest Pusher SDK. Of course, I don’t recommend making any changes in the core framework, but I’ll just highlight what needs to be done.

Go ahead and open the vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php file. Just replace the snippet use Pusher; with use PusherPusher;.

Next, let’s open the vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastManager.php file and make a similar change in the following snippet.

Finally, let’s enable the broadcast service in config/app.php by removing the comment in the following line.

So far, we’ve installed server-specific libraries. In the next section, we’ll go through client libraries that need to be installed as well.

Pusher and Laravel Echo Libraries—Installation and Configuration

In broadcasting, the responsibility of the client side is to subscribe to channels and listen for desired events. Under the hood, it accomplishes it by opening a new connection to the web-socket server.

Luckily, we don’t have to implement any complex JavaScript stuff to achieve it as Laravel already provides a useful client library, Laravel Echo, that helps us deal with sockets on the client side. Also, it supports the Pusher service that we’re going to use in this article.

You can install Laravel Echo using the NPM package manager. Of course, you need to install node and npm in the first place if you don’t have them already. The rest is pretty simple, as shown in the following snippet.

What we’re interested in is the node_modules/laravel-echo/dist/echo.js file that you should copy to public/echo.js.

Yes, I understand, it’s a bit of overkill to just get a single JavaScript file. If you don’t want to go through this exercise, you can download the echo.js file from my GitHub.

And with that, we’re done with our client libraries setup.

Back-End File Setup

Recall that we were talking about setting up an application that allows users of our application to send messages to each other. On the other hand, we’ll send broadcast notifications to users that are logged in when they receive a new message from other users.

In this section, we’ll create the files that are required in order to implement the use-case that we’re looking for.

To start with, let’s create the Message model that holds messages sent by users to each other.

We also need to add a few fields like to, from and message to our messages table. So let’s change the migration file before running the migrate command.

Now, let’s run the migrate command that creates the messages table in the database.

Whenever you want to raise a custom event in Laravel, you should create a class for that event. Based on the type of event, Laravel reacts accordingly and takes the necessary actions.

If the event is a normal event, Laravel calls the associated listener classes. On the other hand, if the event is of broadcast type, Laravel sends that event to the web-socket server that’s configured in the config/broadcasting.php file.

As we’re using the Pusher service in our example, Laravel will send events to the Pusher server.

Let’s use the following artisan command to create a custom event class—NewMessageNotification.

That should create the app/Events/NewMessageNotification.php class. Let’s replace the contents of that file with the following.

The important thing to note is that the NewMessageNotification class implements the ShouldBroadcastNow interface. Thus, when we raise an event, Laravel knows that this event should be broadcast.

In fact, you could also implement the ShouldBroadcast interface, and Laravel adds an event into the event queue. It’ll be processed by the event queue worker when it gets a chance to do so. In our case, we want to broadcast it right away, and that’s why we’ve used the ShouldBroadcastNow interface.

In our case, we want to display a message the user has received, and thus we’ve passed the Message model in the constructor argument. In this way, the data will be passed along with the event.

Next, there is the broadcastOn method that defines the name of the channel on which the event will be broadcast. In our case, we’ve used the private channel as we want to restrict the event broadcast to logged-in users.

The $this->message->to variable refers to the ID of the user to which the event will be broadcast. Thus, it effectively makes the channel name like user.{USER_ID}.

In the case of private channels, the client must authenticate itself before establishing a connection with the web-socket server. It makes sure that events that are broadcast on private channels are sent to authenticated clients only. In our case, it means that only logged-in users will be able to subscribe to our channel user.{USER_ID}.

If you’re using the Laravel Echo client library for channel subscription, you’re in luck! It automatically takes care of the authentication part, and you just need to define the channel routes.

Let’s go ahead and add a route for our private channel in the routes/channels.php file.

As you can see, we’ve defined the user.{toUserId} route for our private channel.

The second argument of the channel method should be a closure function. Laravel automatically passes the currently logged-in user as the first argument of the closure function, and the second argument is usually fetched from the channel name.

When the client tries to subscribe to the private channel user.{USER_ID}, the Laravel Echo library does the necessary authentication in the background using the XMLHttpRequest object, or more commonly known as XHR.

So far, we’ve finished with the setup, so let’s go ahead and test it.

Front-End File Setup

In this section, we’ll create the files that are required to test our use-case.

Let’s go ahead and create a controller file at app/Http/Controllers/MessageController.php with the following contents.

In the index method, we’re using the broadcast view, so let’s create the resources/views/broadcast.blade.php view file as well.

And, of course, we need to add routes as well in the routes/web.php file.

In the constructor method of the controller class, you can see that we’ve used the auth middleware to make sure that controller methods are only accessed by logged-in users.

Next, there’s the index method that renders the broadcast view. Let’s pull in the most important code in the view file.

Firstly, we load the necessary client libraries, Laravel Echo and Pusher, allowing us to open the web-socket connection to the Pusher web-socket server.

Next, we create the instance of Echo by providing Pusher as our broadcast adapter and other necessary Pusher-related information.

Moving further, we use the private method of Echo to subscribe to the private channel user.{USER_ID}. As we discussed earlier, the client must authenticate itself before subscribing to the private channel. Thus the Echo object performs the necessary authentication by sending the XHR in the background with necessary parameters. Finally, Laravel tries to find the user.{USER_ID} route, and it should match the route that we’ve defined in the routes/channels.php file.

If everything goes fine, you should have a web-socket connection open with the Pusher web-socket server, and it’s listing events on the user.{USER_ID} channel! From now on, we’ll be able to receive all incoming events on this channel.

In our case, we want to listen for the NewMessageNotification event and thus we’ve used the listen method of the Echo object to achieve it. To keep things simple, we’ll just alert the message that we’ve received from the Pusher server.

So that was the setup for receiving events from the web-sockets server. Next, we’ll go through the send method in the controller file that raises the broadcast event.

Let’s quickly pull in the code of the send method.

In our case, we’re going to notify logged-in users when they receive a new message. So we’ve tried to mimic that behavior in the send method.

Next, we’ve used the event helper function to raise the NewMessageNotification event. Since the NewMessageNotification event is of ShouldBroadcastNow type, Laravel loads the default broadcast configuration from the config/broadcasting.php file. Finally, it broadcasts the NewMessageNotification event to the configured web-socket server on the user.{USER_ID} channel.

In our case, the event will be broadcast to the Pusher web-socket server on the user.{USER_ID} channel. If the ID of the recipient user is 1, the event will be broadcast over the user.1 channel.

As we discussed earlier, we already have a setup that listens to events on this channel, so it should be able to receive this event, and the alert box is displayed to the user!

Let’s go ahead and walk through how you are supposed to test the use-case that we’ve built so far.

Open the URL http://your-laravel-site-domain/message/index in your browser. If you’re not logged in yet, you’ll be redirected to the login screen. Once you’re logged in, you should see the broadcast view that we defined earlier—nothing fancy yet.

In fact, Laravel has done a quite a bit of work in the background already for you. As we’ve enabled the Pusher.logToConsole setting provided by the Pusher client library, it logs everything in the browser console for debugging purposes. Let’s see what’s being logged to the console when you access the http://your-laravel-site-domain/message/index page.

It has opened the web-socket connection with the Pusher web-socket server and subscribed itself to listen to events on the private channel. Of course, you could have a different channel name in your case based on the ID of the user that you’re logged in with. Now, let’s keep this page open as we move to test the send method.

Next, let’s open the http://your-laravel-site-domain/message/send URL in the other tab or in a different browser. If you’re going to use a different browser, you need to log in to be able to access that page.

As soon as you open the http://your-laravel-site-domain/message/send page, you should be able to see an alert message in the other tab at http://your-laravel-site-domain/message/index.

Let’s navigate to the console to see what has just happened.

As you can see, it tells you that you’ve just received the AppEventsNewMessageNotification event from the Pusher web-socket server on the private-user.2 channel.

In fact, you can see what’s happening out there at the Pusher end as well. Go to your Pusher account and navigate to your application. Under the Debug Console, you should be able to see messages being logged.

Pusher Dashboard

And that brings us to the end of this article! Hopefully, it wasn’t too much in a single go as I’ve tried to simplify things to the best of my knowledge.

Conclusion

Today, we went through one of the least discussed features of Laravel—broadcasting. It allows you to send real-time notifications using web sockets. Throughout the course of this article, we built a real-world example that demonstrated the aforementioned concept.

Yes I know, it’s a lot of stuff to digest in a single article, so feel free to use the comment feed below should you find yourself in trouble during implementation.


Source: Nettuts Web Development

Getting Started With Redux: Why Redux?

When you’re learning React, you will almost always hear people say how great Redux is and that you should give it a try. The React ecosystem is growing at a swift pace, and there are so many libraries that you can hook up with React, such as flow, redux, middlewares, mobx, etc. 

Learning React is easy, but getting used to the entire React ecosystem takes time. This tutorial is an introduction to one of the integral components of the React ecosystem—Redux.

Basic Non-Redux Terminology

Here are some of the commonly used terminologies that you may not be familiar with, but they are not specific to Redux per se. You can skim through this section and come back here when/if something doesn’t make sense.  

Pure Function

A pure function is just a normal function with two additional constraints that it has to satisfy: 

  1. Given a set of inputs, the function should always return the same output. 
  2. It produces no side effects.

For instance, here is a pure function that returns the sum of two numbers.

Pure functions give a predictable output and are deterministic. A function becomes impure when it performs anything other than calculating its return value. 

For instance, the add function below uses a global state to calculate its output. In addition, the function also logs the value to the console, which is considered to be a side effect. 

Observable Side Effects

“Observable side effects” is a fancy term for interactions made by a function with the outside world. If a function tries to write a value into a variable that exists outside the function or tries to call an external method, then you can safely call these things side effects. 

However, if a pure function calls another pure function, then the function can be treated as pure. Here are some of the common side effects:

  • making API calls
  • logging to console or printing data
  • mutating data
  • DOM manipulation
  • retrieving the current time

Container and Presentational Components

Splitting the component architecture into two is useful while working with React applications. You can broadly classify them into two categories: container components and presentational components. They are also popularly known as smart and dumb components. 

The container component is concerned with how things work, whereas presentational components are concerned with how things look. To understand the concepts better, I’ve covered that in another tutorial: Container vs. Presentational Components in React.

Mutable vs. Immutable Objects

A mutable object can be defined as follows:

mutable object is an object whose state can be modified after it is created.

Immutability is the exact opposite—an immutable object is an object whose state cannot be modified after it is created. In JavaScript, strings and numbers are immutable, but objects and arrays are not. The example demonstrates the difference better. 

To make objects immutable, use the Object.assign method to create a new method or the all new spread operator.

What Is Redux?

The official page defines Redux as follows:

Redux is a predictable state container for JavaScript applications. 

Although that accurately describes Redux, it’s easy to get lost when you see the bigger picture of Redux for the first time. It has so many moving pieces that you need to fit together. But once you do, I promise you, you’ll start loving Redux. 

Redux is a state management library that you can hook up with any JavaScript library, and not just React. However, it works very well with React because of React’s functional nature. To understand this better, let’s have a look at the state.

Any change in the state rerenders the component and any user interaction updates the state

As you can see, a component’s state determines what gets rendered and how it behaves. The application has an initial state, and any user interaction triggers an action that updates the state. When the state is updated, the page is rerendered.

With React, each component has a local state that is accessible from within the component, or you can pass them down as props to child components. We usually use the state to store:

  1. UI state and transitionary data. This includes a list of UI elements for navigation menu or form inputs in a controlled component.
  2. Application state such as data fetched from a server, the login state of the user, etc.

Storing application data in a component’s state is okay when you have a basic React application with a few components. 

React Project with a few components
Component hierarchy of a basic application

However, most real-life apps will have lots more features and components. When the number of levels in the component hierarchy increases, managing the state becomes problematic. 

Component hierarchy of a chat application using React
Sketch of a medium-sized application

Why Should You Use Redux?

Here is a very probable scenario that you might come across while working with React.

  1. You are building a medium-sized application, and you have your components neatly split into smart and dumb components. 
  2. The smart components handle the state and then pass them down to the dumb components. They take care of making API calls, fetching the data from the data source, processing the data, and then setting the state. The dumb components receive the props and return the UI representation. 
  3. When you’re about to write a new component, it’s not always clear where to place the state. You could let the state be part of a container that’s an immediate parent of the presentational component. Better yet, you could move the state higher up in the hierarchy so that the state is accessible to multiple presentational components.
  4. When the app grows, you see that the state is scattered all over the place. When a component needs to access the state that it doesn’t immediately have access to, you will try to lift the state up to the closest component ancestor. 
  5. After constant refactoring and cleaning up, you end up with most of the state holding places at the top of the component hierarchy. 
  6. Finally, you decide that it’s a good idea to let a component at the top handle the state globally and then pass everything down. Every other component can subscribe to the props that they need and ignore the rest.

This is what I’ve personally experienced with React, and lots of other developers will agree. React is a view library, and it’s not React’s job to specifically manage state. What we are looking for is the Separation of Concerns principle. 

Redux helps you to separate the application state from React. Redux creates a global store that resides at the top level of your application and feeds the state to all other components. Unlike Flux, Redux doesn’t have multiple store objects. The entire state of the application is within that store object, and you could potentially swap the view layer with another library with the store intact.

The components re-render every time the store is updated, with very little impact on performance. That’s good news, and this brings tons of benefits along with it. You can treat all your React components as dumb, and React can just focus on the view side of things.

Now that we know why Redux is useful, let’s dive into the Redux architecture.

The Redux Architecture

When you’re learning Redux, there are a few core concepts that you need to get used to. The image below describes the Redux architecture and how everything is connected together. 

Getting started with Redux Redux Architecture
Redux in a nutshell

If you’re used to Flux, some of the elements might look familiar. If not, that’s okay too because we’re going to cover everything from the base. First, make sure that you have redux installed:

Use create-react-app or your favorite webpack configuration to set up the development server. Since Redux is an independent state management, we’re not going to plug in React yet. So remove the contents of index.js, and we’ll play around with Redux for the rest of this tutorial.

Store

The store is one big JavaScript object that has tons of key-value pairs that represent the current state of the application. Unlike the state object in React that is sprinkled across different components, we have only one store. The store provides the application state, and every time the state updates, the view rerenders. 

However, you can never mutate or change the store. Instead, you create new versions of the store. 

Because of this, you can do time travel through all the states from the time the app was booted on your browser.

The store has three methods to communicate with the rest of the architecture. They are:

  • Store.getState()—To access the current state tree of your application. 
  • Store.dispatch(action)—To trigger a state change based on an action. More about actions below.
  • Store.subscribe(listener)—To listen to any change in the state. It will be called every time an action is dispatched.

Let’s create a store. Redux has a createStore method to create a new store. You need to pass it a reducer, although we don’t know what that is. So I will just create a function called reducer. You may optionally specify a second argument that sets the initial state of the store. 

src/index.js

Now we’re going to listen to any changes in the store, and then console.log() the current state of the store.

So how do we update the store? Redux has something called actions that make this happen.

Action/Action Creators

Actions are also plain JavaScript objects that send information from your application to the store. If you have a very simple counter with an increment button, pressing it will result in an action being triggered that looks like this:

They are the only source of information to the store. The state of the store changes only in response to an action. Each action should have a type property that describes what the action object intends to do. Other than that, the structure of the action is completely up to you. However, keep your action small because an action represents the minimum amount of information required to transform the application state. 

For instance, in the example above, the type property is set to “INCREMENT”, and an additional payload property is included. You could rename the payload property to something more meaningful or, in our case, omit it entirely.  You can dispatch an action to the store like this.

While coding Redux, you won’t normally use actions directly. Instead, you will be calling functions that return actions, and these functions are popularly known as action creators. Here is the action creator for the increment action that we discussed earlier.

So, to update the state of the counter, you will need to dispatch the incrementCount action like this:

If you head to the browser console, you will see that it’s working, partially. We get undefined because we haven’t yet defined the reducer.

Browser console returns undefined for getState

So now we have covered actions and the store. However, we need a mechanism to convert the information provided by the action and transform the state of the store. Reducers serve this purpose.

Reducers

An action describes the problem, and the reducer is responsible for solving the problem. In the earlier example, the incrementCount method returned an action that supplied information about the type of change that we wanted to make to the state. The reducer uses this information to actually update the state. There’s a big point highlighted in the docs that you should always remember while using Redux:

Given the same arguments, a Reducer should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

What this means is that a reducer should be a pure function. Given a set of inputs, it should always return the same output. Beyond that, it shouldn’t do anything more. Also, a reducer is not the place for side effects such as making AJAX calls or fetching data from the API. 

Let’s fill in the reducer for our counter.

The reducer accepts two arguments—state and action—and it returns a new state.

The state accepts a default value, the initialState, which will be used only if the value of the state is undefined. Otherwise, the actual value of the state will be retained. We use the switch statement to select the right action. Refresh the browser, and everything works as expected. 

Let’s add a case for DECREMENT, without which the counter is incomplete.

Here’s the action creator.

Finally, dispatch it to the store.

That’s it!

Summary

This tutorial was meant to be a starting point for managing state with Redux. We’ve covered everything essential needed to understand the basic Redux concepts such as the store, actions, and reducers. Towards the end of the tutorial, we also created a working redux demo counter. Although it wasn’t much, we learned how all the pieces of the puzzle fit together. 

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.

In the next tutorial, we will make use of the things we’ve learned here to create a React application using Redux. Stay tuned until then. Share your thoughts in the comments. 


Source: Nettuts Web Development

How to Find and Fix Poor Page Load Times With Raygun

In this tutorial, we’ll focus on finding and fixing poor page load times with Raygun. But before we do that, let’s discuss why slightly longer page load times can be such a big deal.

One of the most important things that you can do to make a good first impression on potential customers or clients visiting your website is improve its loading speed.

Imagine a customer who just heard about your company from a friend. You sell a product online which users can purchase by visiting your website. If different website pages are taking a long time to load and you are not selling that product exclusively, there is a good chance that the customer will abandon your site and go somewhere else.

You did not just miss out on your first sale here, you also missed the opportunity to have a loyal customer who would have purchased more products in the future. 

That’s the thing with the Internet—people are just a few clicks away from leaving your website and buying something from your competitors. Faster loading pages can give you an edge over competitors and increase your revenue.

How Can Raygun Help?

Raygun relies on Real User Monitoring Insights (RUM Insights) to improve a website’s performance and page load time. The term “Real User Monitoring” is the key here. You could use tools like WebPagetest and Google Page Speed Insights to optimize individual pages, but those results will not be based on real user data. On the other hand, the data provided by Raygun is based on real users who visited your website.

Raygun also presents the information in a more organized manner by telling you things like the average page speed for the website, the most requested pages, and the slowest pages. This way, you can prioritize which page or section of the website needs to be optimized first.

You can also see how fast the website is loading for users in different countries or for users with different browsers. Similarly, you can compare the speed of your website on mobile vs. desktop. 

Another advantage of Raygun is that it will show you how the website is performing for different users. For example, the website may be loading slowly for one of your most valuable clients. In such cases, you would definitely like to know about it and do something to improve their experience before it is too late.

We will learn how to do all that with Raygun in the next few sections of this article.

Integrating Raygun Into Your Website

You need to sign up for an account before integrating Raygun into your website. This account will give you access to all Raygun features for free for 14 days.

Once you have registered successfully, you can click on the Create Application button to create a new application. You can fill out a name for your application on the next screen and then check some boxes to receive notifications about errors and real user monitoring insights.

Create Raygun Application

Now you just have to select your development platform or framework. In this case, we are using JavaScript.

Choose Raygun Language or Framework

Finally, you will get some code that you have to add on all the pages you want to monitor. Instead of placing the following code in your website, you could also download the production or development version of the library and include it yourself.

Once you have added the above code snippet before the closing </head> tag, you have to place the following snippet just before the closing <body> tag.

If you don’t add any more code, Raygun will now start collecting anonymous data. This means that you will be able to know how your website is performing for different users, but there will be no way to identify those users.

There is an easy fix for this problem. All you have to do is add the following code in your webpages and Raygun will take care of the rest.

You will have to include these three pieces of code in all the pages that you want to track. Once done, the data will start showing up in the dashboard for you to analyze.

Finding Pages With Poor Load Times

The Real User Monitoring section in the Raygun dashboard has a lot of tabs to present the data in different formats. We will briefly go over all these tabs to show you how the information presented in them can be used to find pages with poor load times.

Raygun Live Sessions - Visiting Countries

The Live tab will give you an overview of your site’s performance in real time. It has different metrics like Health Score to show you how the site is currently performing. You can read more about all these metrics in the documentation for the Live tab on the Raygun website.

It also has a world map to point out the countries of your currently
active users. You will also find a list of most recent requests to your
website by different users. Here is an image showing the most recent requests to our website.

Live Tab - Recent Requests

The performance tab has five useful metrics to give you a quick overview of the website page load times. For example, a median load time of 1.41 seconds means that 50% of your pages load before 1.41 seconds have passed. Similarly, a P90 Load Time of 6.78 seconds tells you that 90% of the time, the website loads before 6.48 seconds.

Performance Tab

This should give you a rough idea of the performance of a website and how slow it is for the slowest 10% of users.

The performance tab also has a list of the slowest and most requested pages at the bottom. Knowing the most popular and the slowest pages can be very helpful when you want to prioritize which sections of your website need to be fixed first.

Even though all pages in a website should load as quickly as possible, some of these pages are more important than others. Therefore, you might be interested in finding out the performance of a particular page on a website. You can do so by simply typing the page you are looking for in the input field. This will give you information about the median, average, and P90 load time of a particular page. Here is the data for the home page of our website.

Page load time data for a sample website

You can use the Sessions tab to see session-related information like the total number of sessions, total number of users, and median session length. The sessions table will give you a quick overview of the last 150 sessions with information like the country, duration, total page views, and the last visited page for a session.

Clicking on the magnifying glass will show you more details of a particular session like the pages the user visited, the load time of those pages, and the browser/device used during the session.

The Users tab will give you an overview of the satisfaction level of different users with your website. This can be very helpful when you want to see how a particular user is interacting with your website and if or why their page load time is more than expected.

There are three other tabs to show information about all the page views in terms of browsers, platforms, and geography. This way you will be able to know if a webpage is loading slowly only on a particular browser or platform. You will also have a rough idea of the distribution of users. For instance, knowing if most of your clients are from a particular country or use a particular browser can be very handy.

Raygun lists the percentage of visitors from a particular continent at the top of the Geo tab. After that, it provides a map with the distribution of load times. Countries with the slowest load times are filled with red, and countries with quick load times are filled with green.

Raygun Geo Tab

If you are consistently getting poor loading times from a particular country, it might be worth your time to look closely and find out the reason.

Fixing Poor Page Load Times

In the previous section, we learned how to use all the data collected by Raygun to figure out which pages are taking a long time to load or if there are any countries where our page load times are longer than usual.

Now it is time to see how we can use Raygun to discover issues which might be causing a particular page or the whole website to load slower than usual.

Improving poor page load time of a website can be pretty overwhelming, especially if the website is very complicated or if it has a lot of pages. The trouble is in finding what to improve and where to start.

Luckily, Raygun can offer you some general insights to fix your website. You can click on the Insights options under the Real User Monitoring menu, and Raygun will scan your website for any potential issues. You can find a list of all these rules in the official Raygun documentation. Fixing all the listed issues will significantly speed up your website.

Raygun Insights Rules

Besides following these general guidelines, you might also want to isolate the pages that have been loading slowly. Once you have isolated them, Raygun can show you the time they take to resolve DNS, latency, SSL handshake, etc. This will give you a good idea of the areas where you can make improvements to reduce the page load time. The following image should make it clear.

About Us Page

You can also filter the data in order to get a more accurate picture of the load time for a particular page and various factors affecting it. The above image showed you the average latency for all requests made to the “About Us” page. However, you can click on the Add Filter button at the top and only see the “About Us” loading time graph for a specific country like Italy.

About Us Italy Filter

You will also see all the requests made by a specific page at the bottom. Basically, you will be able to see the DNS, latency, SSL, server, and transfer time for every resource loaded for a specific page and see if any of them is the culprit.

About Us Requests

Once you find out which resources are taking too long to load, you can start optimizing your pages.

Final Thoughts

As you saw in this tutorial, Raygun can be of great help to organizations looking to improve their page load times. It is super easy to integrate, and after successful integration, the data will simply start showing up in the dashboard without any intervention from your side.

Raygun also has different tabs to organize the collected data so that you can analyze it more easily and efficiently. For example, it can show you load times for different countries, browsers, and platforms. It also has filters that you can use to isolate a particular set of data from the rest and analyze it closely.

If you or your company are looking for an easy-to-integrate tool which can provide great insights about how your real users are interacting with your website, you should definitely give Raygun a try. You don’t have anything to lose since it is free for the first 14 days!

And while you’re here, check out some of our other tutorials on Raygun!


Source: Nettuts Web Development

Notifications in Laravel

In this article, we’re going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we’ll discuss how you can send notifications over the mail channel.

Basics of Notifications

During application development, you often need to notify users about different state changes. It could be either sending email notifications when the order status is changed or sending an SMS about their login activity for security purposes. In particular, we’re talking about messages that are short and just provide insight into the state changes.

Laravel already provides a built-in feature that helps us achieve something similar—notifications. In fact, it makes sending notification messages to users a breeze and a fun experience!

The beauty of that approach is that it allows you to choose from different channels notifications will be sent on. Let’s quickly go through the different notification channels supported by Laravel.

  • Mail: The notifications will be sent in the form of email to users.
  • SMS: As the name suggests, users will receive SMS notifications on their phone.
  • Slack: In this case, the notifications will be sent on Slack channels.
  • Database: This option allows you to store notifications in a database should you wish to build a custom UI to display it.

Among different notification channels, we’ll use the mail channel in our example use-case that we’re going to develop over the course of this tutorial.

In fact, it’ll be a pretty simple use-case that allows users of our application to send messages to each user. When users receive a new message in their inbox, we’ll notify them about this event by sending an email to them. Of course, we’ll do that by using the notification feature of Laravel!

Create a Custom Notification Class

As we discussed earlier, we are going to set up an application that allows users of our application to send messages to each other. On the other hand, we’ll notify users when they receive a new message from other users via email.

In this section, we’ll create necessary files that are required in order to implement the use-case that we’re looking for.

To start with, let’s create the Message model that holds messages sent by users to each other.

We also need to add a few fields like to, from and message to the messages table. So let’s change the migration file before running the migrate command.

Now, let’s run the migrate command that creates the messages table in the database.

That should create the messages table in the database.

Also, make sure that you have enabled the default Laravel authentication system in the first place so that features like registration and login work out of the box. If you’re not sure how to do that, the Laravel documentation provides a quick insight into that.

Since each notification in Laravel is represented by a separate class, we need to create a custom notification class that will be used to notify users. Let’s use the following artisan command to create a custom notification class—NewMessage.

That should create the app/Notifications/NewMessage.php class, so let’s replace the contents of that file with the following contents.

As we’re going to use the mail channel to send notifications to users, the via method is configured accordingly. So this is the method that allows you to configure the channel type of a notification.

Next, there’s the toMail method that allows you to configure various email parameters. In fact, the toMail method should return the instance of IlluminateNotificationsMessagesMailMessage, and that class provides useful methods that allow you to configure email parameters.

Among various methods, the line method allows you to add a single line in a message. On the other hand, there’s the action method that allows you to add a call-to-action button in a message.

In this way, you could format a message that will be sent to users. So that’s how you’re supposed to configure the notification class while you’re using the mail channel to send notifications.

At the end, you need to make sure that you implement the necessary methods according to the channel type configured in the via method. For example, if you’re using the database channel that stores notifications in a database, you don’t need to configure the toMail method; instead, you should implement the toArray method, which formats the data that needs to be stored in a database.

How to Send Notifications

In the previous section, we created a notification class that’s ready to send notifications. In this section, we’ll create files that demonstrate how you could actually send notifications using the NewMessage notification class.

Let’s create a controller file at app/Http/Controllers/NotificationController.php with the following contents.

Of course, you need to add an associated route in the routes/web.php file.

There are two ways Laravel allows you to send notifications: by using either the notifiable entity or the Notification facade.

If the entity model class utilizes the IlluminateNotificationsNotifiable trait, then you could call the notify method on that model. The AppUser class implements the Notifiable trait and thus it becomes the notifiable entity. On the other hand, you could also use the IlluminateSupportFacadesNotification Facade to send notifications to users.

Let’s go through the index method of the controller.

In our case, we’re going to notify users when they receive a new message. So we’ve tried to mimic that behavior in the index method in the first place.

Next, we’ve notified the recipient user about a new message using the notify method on the $toUser object, as it’s the notifiable entity.

You may have noticed that we also pass the $fromUser object in the first argument of the __construct method, since we want to include the from username in a message.

On the other hand, if you want to mimic it using the Notification facade, it’s pretty easy to do so using the following snippet.

As you can see, we’ve used the send method of the Notification facade to send a notification to a user.

Go ahead and open the URL http://your-laravel-site-domain/notify/index in your browser. If you’re not logged in yet, you’ll be redirected to the login screen. Once you’re logged in, you should receive a notification email at the email address that’s attached with the user 1.

You may be wondering how the notification system detects the to address when we haven’t configured it anywhere yet. In that case, the notification system tries to find the email property in the notifiable object. And the AppUser object class already has that property as we’re using the default Laravel authentication system.

However, if you would like to override this behavior and you want to use a different property other than email, you just need to define the following method in your notification class.

Now, the notification system should look for the email_address property instead of the email property to fetch the to address.

And that’s how to use the notification system in Laravel. That brings us to the end of this article as well!

Conclusion

What we’ve gone through today is one of the useful, yet least discussed, features in Laravel—notifications. It allows you to send notifications to users over different channels.

After a quick introduction, we implemented a real-world example that demonstrated how to send notifications over the mail channel. In fact, it’s really handy in the case of sending short messages about state changes in your application.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Should you have any queries or suggestions, don’t hesitate to post them using the feed below!


Source: Nettuts Web Development

Introduction to the Stimulus Framework

There are lots of JavaScript frameworks out there. Sometimes I even start to think that I’m the only one who has not yet created a framework. Some solutions, like Angular, are big and complex, whereas some, like Backbone (which is more a library than a framework), are quite simple and only provide a handful of tools to speed up the development process.

In today’s article I would like to present you a brand new framework called Stimulus. It was created by a Basecamp team led by David Heinemeier Hansson, a popular developer who was the father of Ruby on Rails.

Stimulus is a small framework that was never intended to grow into something big. It has its very own philosophy and attitude towards front-end development, which some programmers might like or dislike. Stimulus is young, but version 1 has already been released so it should be safe to use in production. I’ve played with this framework quite a bit and really liked its simplicity and elegance. Hopefully, you will enjoy it too!

In this post we’ll discuss the basics of Stimulus while creating a single-page application with asynchronous data loading, events, state persistence, and other common things.

The source code can be found on GitHub.

Introduction to Stimulus

Stimulus was created by developers at Basecamp. Instead of creating single-page JavaScript applications, they decided to choose a majestic monolith powered by Turbolinks and some JavaScript. This JavaScript code evolved into a small and modest framework which does not require you to spend hours and hours learning all its concepts and caveats.

Stimulus is mostly meant to attach itself to existing DOM elements and work with them in some way. It is possible, however, to dynamically render the contents as well. All in all, this framework is quite different from other popular solutions as, for example, it persists state in HTML, not in JavaScript objects. Some developers may find it inconvenient, but do give Stimulus a chance, as it really may surprise you.

The framework has only three main concepts that you should remember, which are:

  • Controllers: JS classes with some methods and callbacks that attach themselves to the DOM. The attachment happens when a data-controller “magic” attribute appears on the page. The documentation explains that this attribute is a bridge between HTML and JavaScript, just like classes serve as bridges between HTML and CSS. One controller can be attached to multiple elements, and one element may be powered up by multiple controllers.
  • Actions: methods to be called on specific events. They are defined in special data-action attributes.
  • Targets: important elements that can be easily accessed and manipulated. They are specified with the help of data-target attributes.

As you can see, the attributes listed above allow you to separate content from behaviour logic in a very simple and natural way. Later in this article, we will see all these concepts in action and notice how easy it is to read an HTML document and understand what’s going on.

Bootstrapping a Stimulus Application

Stimulus can be easily installed as an NPM package or loaded directly via the script tag as explained in the docs. Also note that by default this framework integrates with the Webpack asset manager, which supports goodies like controller autoloading. You are free to use any other build system, but in this case some more work will be needed.

The quickest way to get started with Stimulus is by utilizing this starter project that has Express web server and Babel already hooked up. It also depends on Yarn, so be sure to install it. To clone the project and install all its dependencies, run:

If you’d prefer not to install anything locally, you may remix this project on Glitch and do all the coding right in your browser.

Great—we are all set and can proceed to the next section!

Some Markup

Suppose we are creating a small single-page application that presents a list of employees and loads information like their name, photo, position, salary, birthdate, etc.

Let’s start with the list of employees. All the markup that we are going to write should be placed inside the public/index.html file, which already has some very minimal HTML. For now, we will hard-code all our employees in the following way:

Nice! Now let’s add a dash of Stimulus magic.

Creating a Controller

As the official documentation explains, the main purpose of Stimulus is to connect JavaScript objects (called controllers) to the DOM elements. The controllers will then bring the page to life. As a convention, controllers’ names should end with a _controller postfix (which should be very familiar to Rails developers).

There is a directory for controllers already available called src/controllers. Inside, you will find a  hello_controller.js file that defines an empty class:

Let’s rename this file to employees_controller.js. We don’t need to specifically require it because controllers are loaded automatically thanks to the following lines of code in the src/index.js file:

The next step is to connect our controller to the DOM. In order to do this, set a data-controller attribute and assign it an identifier (which is employees in our case):

That’s it! The controller is now attached to the DOM.

Lifecycle Callbacks

One important thing to know about controllers is that they have three lifecycle callbacks that get fired on specific conditions:

  • initialize: this callback happens only once, when the controller is instantiated.
  • connect: fires whenever we connect the controller to the DOM element. Since one controller may be connected to multiple elements on the page, this callback may run multiple times.
  • disconnect: as you’ve probably guessed, this callback runs whenever the controller disconnects from the DOM element.

Nothing complex, right? Let’s take advantage of the initialize() and connect() callbacks to make sure our controller actually works:

Next, start the server by running:

Navigate to http://localhost:9000. Open your browser’s console and make sure both messages are displayed. It means that everything is working as expected!

Adding Events

The next core Stimulus concept is events. Events are used to respond to various user actions on the page: clicking, hovering, focusing, etc. Stimulus does not try to reinvent a bicycle, and its event system is based on generic JS events.

For instance, let’s bind a click event to our employees. Whenever this event happens, I would like to call the as yet non-existent choose() method of the employees_controller:

Probably, you can understand what’s going on here by yourself.

  • data-action is the special attribute that binds an event to the element and explains what action should be called.
  • click, of course, is the event’s name.
  • employees is the identifier of our controller.
  • choose is the name of the method that we’d like to call.

Since click is the most common event, it can be safely omitted:

In this case, click will be used implicitly.

Next, let’s code the choose() method. I don’t want the default action to happen (which is, obviously, opening a new page specified in the href attribute), so let’s prevent it:

e is the special event object that contains full information about the triggered event. Note, by the way, that this returns the controller itself, not an individual link! In order to gain access to the element that acts as the event’s target, use e.target.

Reload the page, click on a list item, and observe the result!

Working With the State

Now that we have bound a click event handler to the employees, I’d like to store the currently chosen person. Why? Having stored this info, we can prevent the same employee from being selected the second time. This will later allow us to avoid loading the same information multiple times as well.

Stimulus instructs us to persist state in the Data API, which seems quite reasonable. First of all, let’s provide some arbitrary ids for each employee using the data-id attribute:

Next, we need to fetch the id and persist it. Using the Data API is very common with Stimulus, so a special this.data object is provided for each controller. With its help, we can run the following methods:

  • this.data.get('name'): get the value by its attribute.
  • this.data.set('name', value): set the value under some attribute.
  • this.data.has('name'): check if the attribute exists (returns a boolean value).

Unfortunately, these shortcuts are not available for the targets of the click events, so we must stick with getAttribute() in their case:

But we can do even better by creating a getter and a setter for the currentEmployee:

Notice how we are using the this.currentEmployee getter and making sure that the provided id is not the same as the already stored one.

Now you may rewrite the choose() method in the following way:

Reload the page to make sure that everything still works. You won’t notice any visual changes yet, but with the help of the Inspector tool you’ll notice that the ul has the data-employees-current-employee attribute with a value that changes as you click on the links. The employees part in the attribute’s name is the controller’s identifier and is being added automatically.

Now let’s move on and highlight the currently chosen employee.

Using Targets

When an employee is selected, I would like to assign the corresponding element with a .chosen class. Of course, we might have solved this task by using some JS selector functions, but Stimulus provides a neater solution.

Meet targets, which allow you to mark one or more important elements on the page. These elements can then be easily accessed and manipulated as needed. In order to create a target, add a data-target attribute with the value of {controller}.{target_name} (which is called a target descriptor):

Now let Stimulus know about these new targets by defining a new static value:

How do we access the targets now? It’s as simple as saying this.employeeTarget (to get the first element) or this.employeeTargets (to get all the elements):

Great! How can these targets help us now? Well, we can use them to add and remove CSS classes with ease based on some criteria:

The idea is simple: we iterate over an array of targets and for each target compare its data-id to the one stored under this.currentEmployee. If it matches, the element is assigned the .chosen class. Otherwise, this class is removed. You may also extract the if (this.currentEmployee !== id) { condition from the setter and use it in the chosen() method instead:

Looking nice! Lastly, we’ll provide some very simple styling for the .chosen class inside the public/main.css:

Reload the page once again, click on a person, and make sure that person is being highlighted properly.

Loading Data Asynchronously

Our next task is to load information about the chosen employee. In a real-world application, you would have to set up a hosting provider, a back-end powered by something like Django or Rails, and an API endpoint that responds with JSON containing all the necessary data. But we are going to make things a bit simpler and concentrate on the client side only. Create an employees directory under the public folder. Next, add four files containing data for individual employees:

1.json

2.json

3.json

4.json

All photos were taken from the free stock photography by Shopify called Burst.

Our data is ready and waiting to be loaded! In order to do this, we’ll code a separate loadInfoFor() method:

This method accepts an employee’s id and sends an asynchronous fetch request to the given URI. There are also two promises: one to fetch the body and another one to display the loaded info (we’ll add the corresponding method in a moment).

Utilize this new method inside choose():

Before coding the displayInfo() method, we need an element to actually render the data to. Why don’t we take advantage of targets once again?

Define the target:

And now utilize it to display all the info:

Of course, you are free to employ a templating engine like Handlebars, but for this simple case that would probably be overkill.

Now reload the page and choose one of the employees. His bio and image should be loaded nearly instantly, which means our app is working properly!

Dynamic List of Employees

Using the approach described above, we can go even further and load the list of employees on the fly rather than hard-coding it.

Prepare the data inside the public/employees.json file:

Now tweak the public/index.html file by removing the hard-coded list and adding a data-employees-url attribute (note that we must provide the controller’s name, otherwise the Data API won’t work):

As soon as controller is attached to the DOM, it should send a fetch request to build a list of employees. It means that the connect() callback is the perfect place to do this:

I propose we create a more generic loadFrom() method that accepts a URL to load data from and a callback to actually render this data:

Tweak the choose() method to take advantage of the loadFrom():

displayInfo() can be simplified as well, since JSON is now being parsed right inside the loadFrom():

Remove loadInfoFor() and code the displayEmployees() method:

That’s it! We are now dynamically rendering our list of employees based on the data returned by the server.

Conclusion

In this article we have covered a modest JavaScript framework called Stimulus. We have seen how to create a new application, add a controller with a bunch of callbacks and actions, and introduce events and actions. Also, we’ve done some asynchronous data loading with the help of fetch requests.

All in all, that’s it for the basics of Stimulus—it really does not expect you to have some arcane knowledge in order to craft web applications. Of course, the framework will probably have some new features in future, but the developers are not planning to turn it into a huge monster with hundreds of tools. 

If you’d like to find more examples of using Stimulus, you may also check out this tiny handbook. And if you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available in the Envato Market

Did you like Stimulus? Would you be interested in trying to create a real-world application powered by this framework? Share your thoughts in the comments!

As always, I thank you for staying with me and until the next time.


Source: Nettuts Web Development

Single-Page React Applications With the React-Router and React-Transition-Group Modules

This tutorial will walk you through using the react-router and react-transition-group modules to create multi-page React applications with page transition animations.

Preparing the React App

Installing the create-react-app Package

If you’ve ever had the chance to try React, you’ve probably heard about the create-react-app package, which makes it super easy to start with a React development environment.

In this tutorial, we will use this package to initiate our React app.

So, first of all, make sure you have Node.js installed on your computer. It will also install npm for you.

In your terminal, run npm install -g create-react-app. This will globally install create-react-app on your computer.

Once it is done, you can verify whether it is there by typing create-react-app -V.

Creating the React Project

Now it’s time to build our React project. Just run create-react-app multi-page-app. You can, of course, replace multi-page-app with anything you want.

Now, create-react-app will create a folder named multi-page-app. Just type cd multi-page-app to change directory, and now run npm start to initialize a local server.

That’s all. You have a React app running on your local server.

Now it’s time to clean the default files and prepare our application.

In your src folder, delete everything but App.js and index.js. Then open index.js and replace the content with the code below.

I basically deleted the registerServiceWorker related lines and also the import './index.css'; line.

Also, replace your App.js file with the code below.

Now we will install the required modules.

In your terminal, type the following commands to install the react-router and react-transition-group modules respectively.

npm install react-router-dom --save

npm install react-transition-group@1.x --save

After installing the packages, you can check the package.json file inside your main project directory to verify that the modules are included under dependencies.

Router Components

There are basically two different router options: HashRouter and BrowserRouter.

As the name implies, HashRouter uses hashes to keep track of your links, and it is suitable for static servers. On the other hand, if you have a dynamic server, it is a better option to use BrowserRouter, considering the fact that your URLs will be prettier.

Once you decide which one you should use, just go ahead and add the component to your index.js file.

import { HashRouter } from 'react-router-dom'

The next thing is to wrap our <App> component with the router component.

So your final index.js file should look like this:

If you’re using a dynamic server and prefer to use BrowserRouter, the only difference would be importing the BrowserRouter and using it to wrap the <App> component.

By wrapping our <App> component, we are serving the history object to our application, and thus other react-router components can communicate with each other.

Inside <App/> Component

Inside our <App> component, we will have two components named <Menu> and <Content>. As the names imply, they will hold the navigation menu and displayed content respectively.

Create a folder named “components” in your src directory, and then create the Menu.js and Content.js files.

Menu.js

Let’s fill in our Menu.js component.

It will be a stateless functional component since we don’t need states and life-cycle hooks.

Here we have a <ul> tag with <li> tags, which will be our links.

Now add the following line to your Menu component.

import { Link } from 'react-router-dom'

And then wrap the content of the <li> tags with the <Link> component.

The <Link> component is essentially a react-router component acting like an <a> tag, but it does not reload your page with a new target link.

Also, if you style your a tag in CSS, you will notice that the <Link> component gets the same styling.

Note that there is a more advanced version of the <Link> component, which is <NavLink>. This offers you extra features so that you can style the active links.

Now we need to define where each link will navigate. For this purpose, the <Link> component has a to prop.

Content.js

Inside our <Content> component, we will define the Routes to match the Links.

We need the Switch and Route components from react-router-dom. So, first of all, import them.

import { Switch, Route } from 'react-router-dom'

Second of all, import the components that we want to route to. These are the HomeWorks and About components for our example. Assuming you have already created those components inside the components folder, we also need to import them.

import Home from './Home'

import Works from './Works'

import About from './About'

Those components can be anything. I just defined them as stateless functional components with minimum content. An example template is below. You can use this for all three components, but just don’t forget to change the names accordingly.

Switch

We use the <Switch> component to group our <Route> components. Switch looks for all the Routes and then returns the first matching one.

Route

Routes are components calling your target component if it matches the path prop.

The final version of our Content.js file looks like this:

Notice that the extra exact prop is required for the Home component, which is the main directory. Using exact forces the Route to match the exact pathname. If it’s not used, other pathnames starting with / would also be matched by the Home component, and for each link, it would only display the Home component.

Now when you click the menu links, your app should be switching the content.

Animating the Route Transitions

So far, we have a working router system. Now we will animate the route transitions. In order to achieve this, we will use the react-transition-group module.

We will be animating the mounting state of each component. When you route different components with the Route component inside Switch, you are essentially mounting and unmounting different components accordingly.

We will use react-transition-group in each component we want to animate. So you can have a different mounting animation for each component. I will only use one animation for all of them.

As an example, let’s use the <Home> component.

First, we need to import CSSTransitionGroup.

import { CSSTransitionGroup } from 'react-transition-group'

Then you need to wrap your content with it.

Since we are dealing with the mounting state of the component, we enable transitionAppear and set a timeout for it. We also disable transitionEnter and transitionLeave, since these are only valid once the component is mounted. If you are planning to animate any children of the component, you have to use them.

Lastly, add the specific transitionName so that we can refer to it inside the CSS file.

We also imported a CSS file, where we define the CSS transitions.

If you refresh the page, you should see the fade-in effect of the Home component.

If you apply the same procedure to all the other routed components, you will see their individual animations when you change the content with your Menu.

Conclusion

In this tutorial, we covered the react-router-dom and react-transition-group modules. However, there’s more to both modules than we covered in this tutorial. Here is a working demo of what was covered.

So, to learn more features, always go through the documentation of the modules you are using.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.


Source: Nettuts Web Development