Monday, July 31, 2017

How to Add a Backdrop in Your DIY Video Studio

What Are Android Instant Apps?

New Course: Animating Icons With Adobe Illustrator and After Effects

10 Elegant CSS Pricing Tables for Your Latest Web Project

Best of the Design Web: July 2017

How to Quickly Make Simple PowerPoint Presentations

Getting Started With the Flux Architecture in React

Using Keyboard Maestro to Create Custom Keyboard Shortcuts

How to Glitterbomb a Photo in Adobe Photoshop (With an Action)

How to Create a Wooden Window Frame With Curtains in Adobe Illustrator

Thursday, July 27, 2017

Universal Panel for Adobe Photoshop: Is It For You?

Top 20 (Most Popular) Premium WordPress Themes of 2017

How to Create a Mobile Phone Icon Pack in Adobe Illustrator

35 Best Calligraphy Fonts

How to Make Modern Websites With Clean WordPress Themes

Getting Started With Matter.js: The Composites and Composite Modules

Getting Started With Matter.js: The Composites and Composite Modules

In the third tutorial of the series, you learned about different methods and properties of the Body module in Matter.js. The Body module enables you to manipulate simple bodies like circles, rectangles, and trapeziums. Matter.js also has other modules to help you create and manipulate some complex but common composite bodies like cars, chains, pyramids, stacks, and soft bodies. 

All these composites and the methods to manipulate them are available in the Composite and Composites modules in Matter.js. In this tutorial, you will begin by learning about different composites like pyramids and cars etc. that can be created using the Composites module. After that, we will go over some important methods and properties available in the Composite module.

Creating a Stack and a Pyramid

A stack and a pyramid are both very similar to each other. A stack can be created by using the stack(xx, yy, columns, rows, columnGap, rowGap, callback) function. Similarly, you can create a pyramid with the help of the pyramid(xx, yy, columns, rows, columnGap, rowGap, callback) function. As you can see, all the parameters are the same in both cases. In fact, the pyramid formation is derived from the stack formation. 

The names of all the parameters are self-explanatory. The xx and yy parameters used in this function are used to specify the starting point of the composite. The columns and rows parameters determine the number of columns and rows in the composite. The gap between different rows and columns can be controlled using the columnGap and rowGap parameters. 

Under the influence of gravity, the rowGap generally vanishes in most cases without changing the composite. However, sometimes the resulting momentum of individual bodies can move the bodies under them. This can change the shape of the composite.

The callback function is used to create bodies that can be arranged in either a grid arrangement or a pyramid arrangement based on the function used. This means that you can use it to create a stack or pyramid of rectangular boxes or trapezoids. You should keep in mind that using a circle will make the arrangements unstable. Here is the code to create a stack of rectangles:

You can make the callback function as complex as you wish. In this case, I have used the render options that we learned about in the Body module tutorial to create only orange rectangles with black outlines.

Here is some very similar code to create pyramid shapes in Matter.js:

When you start creating a lot of pyramids with different parameters, you will notice that the number of rows created is sometimes less than the number of rows you specified. This is because the library uses the following formula to calculate the number of rows:

You can carefully place a stack or another pyramid over a pyramid to create interesting patterns. For example, you could place a smaller pyramid over the red one to create a complete pyramid with two colors.

Creating a Car and a Chain

A car in Matter.js is a structure consisting of two wheels and a body. The wheels are created with a friction of 0.8 and density equal to 0.01. You can create a car using the function car(xx, yy, width, height, wheelSize). The xx and yy parameters are used to specify the position of the car. 

The width and height determine the dimensions of the main body of the car. The wheelSize parameter is used to specify the radius of the wheels. There is no need for a callback function as the type of bodies needed to create a car is predetermined.

You can use the chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) function in Matter.js to chain all the bodies in a given composite together using constraints. The offset parameters in the function are used to determine the relative position of the constraints connecting different boxes. 

You will also need additional constraints to hang the chain from a point in the world. Here is the code to create a chain and hang it to the ceiling of our world. 

The boxes in our chain have been created using the stack() function that you learned about earlier. The constraints created by the chain() function have a stiffness of 1. 

This prevents the length of rope between different boxes from changing at all. The additional constraint that we have created here keeps our boxes hanging from the ceiling. 

Here is a demo with a car and the chain created from the above code. You can move the car forward and backward using the orange buttons. Each click applies a force at the center of the first wheel, moving the whole car.

Creating a Soft Body and Newton's Cradle

A soft body is similar to a stack, with two major differences. The individual elements of the soft body are held together by constraints, and a soft body can only have circles as its constituent elements. You can consider a soft body to be a cross between a mesh and a stack. Creating a soft body is as simple as calling softBody(xx, yy, columns, rows, colGap, rowGap, crossBrace, pRadius, pOptions, cOptions) with the appropriate parameter values. 

You are already familiar with the first six parameters of the function. The crossBrace parameter is a Boolean value that determines if the cross braces should be rendered or not. The pRadius parameter determines the radius of circles, and the pOptions parameter can be used to control other properties of the particles, like mass and inertia. 

The cOptions parameter specifies various options for the constraints that bind the particles together. The following code will create a soft body for our Matter.js world.

Creating a Newton's cradle is also very straightforward using the built-in newtonsCradle(xx, yy, number, size, length) function. The number parameter determines the number of balls in the cradle. The size parameter determines their radius, and the length parameter determines the length of the rope to which the balls are attached. The library sets the restitution and friction values to zero so that they can continue their motion for a long time.

The following code creates the cradle and moves the first ball to a higher position so that it has some velocity when it falls down and strikes other balls. The position specified by the translate() function is relative to the current position of the body. All these functions and properties of the Body module have been discussed in more detail in the previous tutorial of the series.

Important Methods and Properties in Composite Module

Now that you have learned how to create different kinds of composite bodies, it is time for you to learn about different methods and properties available in the Composite module to manipulate these composites. You can use rotate(composite, rotation, point, [recursive=true]), scale(composite, scaleX, scaleY, point, [recursive=true]) and translate(composite, translation, [recursive=true]) to rotate, scale and translate any composite. These functions are very similar to their Body module counterparts.

You can also add or remove one or more body(s), constraint(s) and composite(s) from a given composite using the add(composite, object) and remove(composite, object, [deep=false]) functions respectively. If you want to move some bodies from one composite to another, you can do so with the help of the move(compositeA, objects, compositeB) function. This function will move the given objects from composite A to composite B.

If you ever want to access all the bodies, composites and constraints that are direct children of the given composite, you can use the composite.bodies, composite.composites and composite.constraints properties to get access to all of them in the form of an array. 

We have already seen how to use the bodies property to translate a ball from the Newton's cradle to the left and apply a force on the wheel of our car composite. Once you have a reference to individual bodies from the composite, you can use all the methods and properties of the Body module to manipulate them.

Final Thoughts

In this tutorial, you learned how to create some complex composites using the Composite and Composites modules in Matter.js. You also learned about different methods and properties that you can use to manipulate these composites. 

This series was aimed at getting people started with the Matter.js library in a beginner-friendly way. Keeping that in mind, we have covered important functions and properties of the most common modules in the library. 

Matter.js also has a lot of other modules, which we briefly discussed in the first tutorial of the series. If you want to use this library to its full potential, you should read the documentation of all these modules on the official website.

If you have used Matter.js in any of your projects, please tell us about your experience in the comments.


Mobile-first Indexing is Coming: What This Means for Web Design

Mobile-first Indexing is Coming: What This Means for Web Design

Every business wants to meet its customer's needs as best it can. Having happy customers means higher customer loyalty and more revenue. It’s as simple as that.

Google isn’t any different. Google’s mission is to organize the world’s information, making it universally accessible and useful. Simply put: they want to help you find the best answer to your question as fast as possible.

Finding the best answer means ranking web pages. Google takes more than 200 factors into account, ranging from the text on a page to the links pointing to that domain. Engineers are constantly tweaking this algorithm to reflect the needs of its users; needs which have changed drastically over the years. Just take a look at smartphone use: research suggests that nearly 60 percent of searches now come from mobile devices.

For this reason Google announced mobile-first indexing last year.

In this article I’ll explain the mobile-first concept (as it pertains to search engines) and take a look at the implications for web design.

Mobile Searches, Desktop Ranking

More and more people are using their mobile device–a smartphone or a tablet–to search for information, products and services online. Yet Google’s ranking system still looks at the desktop version of a page to evaluate its relevance to the user.

This might cause some issues. Especially when the desktop version differs from the mobile version. For example:

Company X has two websites: companyx.com, which is the main site, and m.companyx.com, which is the mobile site. The main site provides a great user experience and is completely optimized for search engines. It’s no surprise then, that it receives great rankings. The mobile site on the other hand, isn’t as great. It has outdated information and is difficult to use. In the old days, the mobile site would benefit from the main site and show up high in the search results. Nowadays, with 60% of visitors having a sub-par experience, that’s an issue.

Mobile-first indexing wants to fix this problem. Once fully implemented, Google will primarily consider the mobile version of your site for ranking purposes. This approach has an effect on desktop searches as well:

  • Optimized for mobile = will rank well on mobile and desktop
  • Not optimized for mobile = will see worse ranking on both mobile and desktop

Note: Google started experimenting with mobile-first indexing in November 2016 but it hasn’t yet been rolled out completely. As Gary Illyes stated in March:

“We’re still experimenting. We don’t have a timeline. It could be a few months or quarters, but it’s definitely not weeks [away]. Don’t freak out, especially if you have a responsive site.” – Gary Illyes

Saying that, it’s a good idea to start making some changes based on an imminent algorithm update. Preparation can give you a competitive edge.

The Solution: Responsive Design

Google recommends a responsive design:

“If you have a responsive site or a dynamic serving site where the primary content and markup is equivalent across mobile and desktop, you shouldn’t have to change anything.” – Doantam Phan

Responsive websites adjust themselves according to viewport size, bandwidth, screen resolution and so on. They show the same core information, but presented differently. 

Things to Consider

Beyond having a squishy website, however, there are plenty of factors to take into account.

Site Speed

Page speed plays a vital role on mobile. Although 4G peak download speeds are approaching a normal broadband connection, it’s still a constriction for web designers. Mobile speeds vary from location to location and from provider to provider.

It’s important to reduce loading times as much as possible. At the moment, it’s more of an indicator than a ranking factor. But this will probably change when mobile-first indexing is released.

Expandable Content

A couple of years ago, Google said that expandable content (tabs, accordions, etc) would not be weighted as high as standard content.

That’s no longer the case. According to Gary Illyes, said content will be given full weight in the mobile-first world. The idea is that expandable content makes sense on mobile and not so much on desktop.

Test Your robots.txt File

You might remember that the robots.txt file is used to prevent crawlers from accessing certain parts of your website. Some website owners accidentally block their mobile site from search engines, so use the robots.txt testing tool to verify that your mobile version is accessible to Googlebot.

Consider AMP

Accelerated Mobile Pages or AMP are stripped down versions of pages that help (you guessed it) speed up loading times. They are useful for those who are on slower connections or don't want to wait for the regular, heavier page to load.

AMP content is shown in the search results, identified by a grey lightning-bolt icon.  

For certain websites that want to focus on mobile-first indexing, it might be a good idea to implement this technology.

Is AMP useful for every website? No. Pages that rely heavily on third-party Javascript, cookies, etc. can’t be translated to AMP.

Above All: Don’t Rush

Don’t have a mobile site or responsive design at the moment? Don’t rush the development process! A functional desktop-oriented site will always be better than a broken or incomplete mobile version of the site. Built, test and launch when ready.

If you only have a desktop site, Google will continue to index your desktop site just fine.


8 Ways to Sell Your Drone Video Services

How to Create a Sign Language Digital Painting in Adobe Photoshop

Wednesday, July 26, 2017

How to Create a Newspaper Ransom Note Text Effect in Adobe Photoshop

How to Create an App Prototype Using CSS and JavaScript

How to Create a Pencils Text Effect in Adobe Illustrator

Get Started With Firebase Authentication for iOS

How to Change Your Microsoft Office Theme in 60 Seconds

Getting Started With Matter.js: The Body Module

Getting Started With Matter.js: The Body Module

In the previous tutorial of the series, you learned about the World and Engine modules in Matter.js. The methods available in these two modules are meant to control the behavior of multiple bodies or the whole world at once. However, at some point it will become necessary to have control over the properties of individual bodies in your world. 

For example, you may want to apply some force on a particular object or change its friction coefficient. In such cases, the Body module in Matter.js can be of great help. This module contains a lot of methods and properties to let you specify values for all kinds of physical attributes, from mass to coefficient of restitution. In this tutorial, you will learn about all these methods and properties and how to use them properly.

Scaling, Rotating and Translating a Body

You can rotate any rigid body in the Matter.js world by using the rotate(body, rotation) method. The rotation is relative to the current angle of the body, and it will not impart any angular velocity to it. The rotation angle is specified in radians.

You can also scale a body by using the scale(body, scaleX, scaleY, [point]) method. The parameters scaleX and scaleY specify the amount of scaling in the horizontal and vertical directions respectively. Keep in mind that any such scaling will also update the physical properties of the body like its mass, area, and inertia. The fourth parameter specifies the point around which the scaling occurs. When not specified, the default value of the scaling point is assumed to be the center of the body.

It is possible to move a body by a given vector relative to its current position using the translate(body, translation) method. The translation parameter specifies the new position of the object relative to its current position. Here is the portion of code from the demo that scales, rotates and moves the box around.

Setting Velocities and Applying Forces

You can also impart linear velocity to an object using the setVelocity(body, velocity) method. Applying a velocity in this manner does not change the angle, applied force or position of the concerned object. The position of the object or its angle will probably change, but the library does not specifically set them to any value. Their values are determined by other forces that are acting on the object, like friction. 

Just like the linear velocity, you can also change the angular velocity of an object using the setAngularVelocity(body, velocity) method. In this case, too, the position, angle and force applied on the object remain unchanged.

One thing that you should keep in mind is that the velocity is a vector in setVelocity() and a number in setAngularVelocity().

In addition to imparting velocities to objects, you can also apply a force vector on them. The applyForce(body, position, force) method can be used to apply a force vector on a body from a given position. This force may or may not result in the application of torque on a given body. 

The following code applies a force right at the center of the body. The force vector is {x: 0, y: -0.05}. This means that the applied force will be purely vertical and in an upward direction. You should keep in mind that vertical forces in an upward direction have a negative sign in Matter.js. Another thing worth noticing is how small the number that specifies the vertical force is. The gravitation force itself has a value of just 1 in Matter.js.

The motion of the ball after applying the forces seems natural as long as that ball does not collide with any of the walls or the floor. Normally, when things collide with something, we expect them to bounce back. The energy with which an object bounces back is determined by the coefficient of restitution. 

In Matter.js, its value is set to zero by default. This means that any object which has restitution set to zero and collides with something else will not bounce back at all. A value of 1 will mean that the object will bounce back with kinetic energy equal to what it had before collision. A value like 0.5 means that the object will bounce back only with 50% of its previous kinetic energy. The value of restitution for an object can be controlled using the restitution key.

In certain simulations, it might become necessary for you to change the friction between different bodies. This can be achieved using the friction, frictionAir and frictionStatic keys.

  • The friction key specifies the value of kinetic friction for a body. It can have a value between 0 and 1. A value of 0 implies that a body may keep moving indefinitely once it has been set in motion. The only way to stop it will be to apply some other external force. The final value of friction between two objects is determined using the formula Math.min(bodyA.friction, bodyB.friction)
  • The frictionStatic key specifies the value of friction when a body is at rest. The default value for static friction is 0.5. A higher value means that a larger amount of force will be required to get the body moving.
  • The frictionAir key is used to specify the value of friction between a body and the surrounding air. A higher value means that the body will slow down very quickly when moving through the air. The effect of air friction is non-linear.

Control the Rendering of Bodies

Up to this point, we have not specified the color, outline width or stroke style to use when rendering a body. All these properties are nested inside the render key. The fillStyle property accepts a string to specify the fill style rendering the body. The lineWidth property accepts a number that defines the line width to use when creating the outline of a body. 

A value of zero means that no line will be rendered at all. The strokeStyle property can be used to specify the stroke style to use when rendering the body outline. You can prevent a body from rendering at all by setting the visible key to false. The opacity of the body that you want to render can be controlled using the opacity key.

You can also use an image instead of simple colors and outlines to render a body. The parameters for rendering a body using sprites are specified using a different set of properties. The texture property defines the path of the image that should be used as a sprite texture. 

The xOffset and yOffset properties can be used to define the offset in the respective axes for the sprite. Similarly, you can use the xScale and yScale properties to define the scaling in the x-axis and y-axis for the sprite. Here is some code that replaces the light blue background of our ball with a soccer sprite from the Open Game Art website.

Changing Physical Properties

You have already seen how to specify the friction or coefficient of restitution for an object in Matter.js. There are a lot of other properties whose values can be specified in the same manner. On the other hand, there are properties which are read-only and cannot be changed by you.

You can set the position of a body in the world by using the position key, which accepts a vector as its value. You can also specify the mass of a body using the mass property, but then you will also have to set a value for the inverseMass property, which is calculated using 1/mass. A better way of controlling the mass of a body is with the help of the density property. 

Once you change the density of a body, its mass will be calculated automatically based on its area. This way you can also differentiate between different objects based on their density. For example, a body that uses a rock as its sprite should have higher density than a body of the same size that uses a soccer ball as its sprite.

Some properties like speed, velocity and angularVelocity are read-only, but their values can be set using appropriate methods like setAngularVelocity() and setVelocity(). You can read more about different properties of the Body module in the documentation.

Conclusion

In this tutorial, you have learned about all the important methods and properties in the Body module of the Matter.js library. Knowing about these different properties and what they do can help you create more realistic simulations of real-life physics. In the next and final tutorial of the series, you will learn about the Composite module in Matter.js.

If you have any questions related to this tutorial or some tips for using the library, please share them with us.


22 Unique Photoshop Text Effects That Grab Your Attention!

How to Draw a Bird Step by Step

How to Work With Scopes in DaVinci Resolve

Rigging of Hulk: Part 6

Tuesday, July 25, 2017

What Are GitHub Pull Requests?

How to Create a Dreamy, Emotional Photo Manipulation Scene With Photoshop

How to Loop a PowerPoint Presentation in 60 Seconds

How to Negotiate a Higher Salary After a New Job Offer (With Scripts)

Getting Started With Matter.js: The Engine and World Modules

Getting Started With Matter.js: The Engine and World Modules

In the introductory tutorial of this series, you were briefly introduced to different modules in Matter.js. The library contains a lot of modules, so it was impractical to write in detail about each of them in a single tutorial. After reading the first part of the series, you should now have a general idea of the library and its features.

In this tutorial, we will just focus on the World module and the Engine module in Matter.js. The World module provides us with the necessary methods and properties to create and manipulate the world composite. You can use it to add or remove different bodies from the world. The Engine module contains methods for creating and manipulating the engines that are responsible for creating the simulation of your world.

The World Module

In this section, you will learn about different methods, properties and events of the World module. World is actually a Composite with additional properties like gravity and bounds added to it. Here is a list of important methods available in this module:

  • add(composite, object): This method is inherited from the Composite module and allows you to add one or more body(s), composite(s) or constraint(s) to the given composite or world. 
  • addBody(world, body): This method allows you to add individual body elements to the given world. There are also addComposite() and addConstraint() methods that allow you to add a composite or constraint to the world.

The code below uses both these methods to add different bodies to the world. The add() method adds three static rectangles that act as walls. The addBody() method adds a circle, square or rectangle based on the button clicked by the user.

You can see that the isStatic key has been set to true for the three walls in our world. Setting this key to true for any object makes that object completely static. The object will never change its position or angle now. There are a lot of other properties that can be specified to control the behavior of different objects. You will learn about all of them in the Body module tutorial of this series.

  • remove( composite, object, [deep=false]): This is a generic method to remove one or more body(s), composite(s) or constraint(s) from the given composite or world. For example, you could use the following line to remove the top and left walls from the world.
  • clear( world, keepStatic): This method is an alias for its Composite counterpart. You can use it to remove all the elements from the world at once. The second parameter is a Boolean which can be used to prevent static elements from being cleared. Its value is false by default. This means that calling World.clear( world) will remove all the elements from that particular world.
  • rotate( composite, rotation, point, [recursive=true]): This method can be used to rotate all the children in a given world or composite by a specific angle around the provided point. The angle given here is in radians. The point parameter determines the point for rotation.
  • scale( composite, scaleX, scaleY, point, [recursive=true]): You can use this method to scale all the children of your composite or world by the given values. This method scales everything from width, height and area to mass and inertia.
  • translate(composite, translation, [recursive=true]): The translate method is useful when you want to translate or move all the children of a world or composite by a given vector relative to their current positions. 

One thing you should keep in mind is that neither translate() nor rotate() imparts any kind of velocity to the bodies in the world. Any motion that occurs is just the result of changes in the shape or position of different bodies. Here is some code to scale, rotate and translate a world based on button clicks:

You should note that the above code applies a different scale on the x and y axis. This turns the circle in our Matter.js world into an oval. The oval then topples to go to a more stable state with lower potential energy.

Try pressing the Scale button in the above demo. After that, press the Rotate button to see how closely Matter.js simulates the real-life motion of an oval.

Besides all these methods, the World module has a lot of useful properties as well. For example, you can get an array of all the bodies that are direct children of the world composite using world.bodies. Similarly, you can get an array of all the composites and constraints using world.composites and world.constraints

You can also specify the bounds of the world within which Matter.js should detect collisions using world.bounds. One interesting thing that you can change with the world properties is gravity. The gravity along the x and y axis is set to 0 and 1 by default. You can change these values using world.gravity.x and world.gravity.y respectively.

You should visit the Matter.World documentation page to read more about this module.

The Engine Module

The Engine module is necessary for properly updating the simulation of the world. Here is a list of some important methods of the Engine module.

  • create([options]): This method is useful when you want to create a new engine. The options parameter in this method is actually an object with key-value pairs. You can use options to override the default values for different properties of the engine. For example, you can use the timeScale property to slow down or speed up the simulation. 
  • update(engine, [delta=16.666], [correction=1]): This method will move the simulation forward in time by delta ms. The value of the correction parameter specifies the time correction factor to apply after the update. This correction is usually only necessary when the delta is changing between each update.
  • merge(engineA, engineB): This method will merge two engines specified by the given parameters. While merging, the configuration is applied from engineA and the world is taken from engineB.

The Engine module also has a lot of other properties to help you control the quality of the simulation. You can set a value for constraintIterations, positionIterations or velocityIterations to specify the number of constraint, position and velocity iterations to perform during each update. A higher value in each case will provide a better simulation. However, a higher value will also adversely affect the performance of the library.

You can set a value for the timing.timeScale property to control the speed at which the simulation occurs. Any value below 1 will result in a slow-motion simulation. Setting this property to zero will completely freeze the world. The following example should make it clear.

You might have noticed that the balls are bouncing off the ground this time. Every rigid body has a coefficient of restitution set to 0 by default. This gives them clay-like properties, and they don't bounce back on collision. I have changed the restitution value to 1 so that the balls can easily bounce back. 

You will learn about all these properties of rigid bodies in the next tutorial of the series. For now, add some circles or balls to the world and try pressing the slow motion and fast motion buttons to notice the difference.

You should visit the Matter.Engine documentation page to read more about this module.

Conclusion

This tutorial discussed two very important modules in Matter.js that you need to know about in order to run any simulations. After reading this tutorial, you should be able to scale, rotate, slow down or speed up your world. Now, you also know how to remove or add bodies to a world. This can be helpful when you are developing 2D games.

In the next tutorial of the series, you will learn about the different methods, properties and events available in the Bodies module.


15 YouTube Promo Packs to Engage More Viewers

How to Create a Post Box Illustration in Adobe Illustrator

Monday, July 24, 2017

27 Restaurant Menu Templates With Creative Designs

A Guitarist’s Guide to Playing Festival Gigs: Part 1

A Guitarist’s Guide to Playing Festival Gigs: Part 1

You’ve been offered a festival gig. You picture a huge stage, a massive PA system and thousands of people revering you like the rock god you know you are.

If you’re a big headline act, this is true. If you’re an unknown band, however, this first festival experience may come as a shock.

Fear not, these tutorials will provide you with ways of being prepared and help you to enjoy it. In this tutorial, I'll show you what you need to consider before playing the event.

Playing a Festival

Whilst the idea seems attractive, you should moderate enthusiasm with practical considerations, such as:

Distance

Consider how far away the venue is. If it’s reasonably local to you, that’s fine. Remember, as the distance increases so does the cost.

Time

Consider the travel time versus time onstage. Following on from the previous point, if you’re going to spend many hours travelling just to play a 40 minute set, ask yourself whether it’s really worth it.

Travel

Consider the means of travel, together with any instruments and kit, in getting there. It's probably possible if you can drive. If you're travelling a long distance, or travelling abroad, this becomes and important consideration.

Cost

Consider whether you reasonably justify the expense of attending the venue. 

Getting Paid

Getting paid is one thing. Making it worthwhile is another. Consider whether its worthwhile and ensure that you can cover the costs otherwise it will be costing you and you'll be, effectively, financing the festival venue.

Pay to Play

Perhaps you've been asked to pay to play and are wondering about that. Ordinarily, you should never pay to play. The only exception would be if you know that this gig could change your life, such as a record label A&R person being in attendance.

Even so, be mindful and consider whether the exposure will offset the financial outlay. As per the previous comment the answer is that it rarely will. However, sometimes it can generate more work.

Festival Horrors

In terms of the day itself, at its worst, you can experience the following:

  • No soundcheck
  • Terrible monitoring
  • Awful sound
  • Cramped conditions
  • Technical difficulties
  • The shortest set you’ve ever played
  • Being hustled rapidly on and offstage

If you are still interested in taking the gig, suitably warned, check the details…

Need To Know

Having confirmed that you’re definitely playing the event, you should ask for:

  • Venue address
  • Date and time you need to arrive. Arrive a little earlier and factor time into the journey for unforeseen delays
  • To where you need report. Bigger events can have more than one entrance
  • For whom you should ask upon arrival
  • Should you bring your own gear, or is any provided, such as amps, mics, stands
  • If gear is being provided, find out what’s on offer; it may not suit your requirements
  • Are there complimentary tickets, for non-band members, or any other entitlements such as food and drink
  • How much you're being paid. If it’s a charity event, probably nothing, though some do, so it’s worth asking.

Get this all in writing, and have it with you upon arrival, just in case you’re challenged.

Travel

If you’re playing a local event, a little driving or catching a lift may be all that’s involved.

That changes, however, if it’s a significant distance. Suddenly, the entire day, or maybe even weekend, could revolve around this one event. You need therefore to plan accordingly.

If you’re driving, do the following:

  • Ensure your vehicle is both legally and mechanically in good order. It's a no-brainer, but it has to be said. Spare wheel, breakdown cover, these are all important considerations
  • Check your licence and insurance allows you to drive under these circumstances, especially important if you’re hiring a van
  • Check everything and everyone fits into the vehicle. Check before the day of departure
  • If it’s a long trip, fuel up before leaving. If you can’t make it on one tank of fuel, check where en route you can top up; don't leave it to chance
  • Check the route prior to leaving and don’t rely solely on sat-nav
  • Build extra time into the journey; you won’t win any fans by breezing in late
  • Have a contact telephone number; if you run into difficulties, you need to let the organisers know, as they may have to adjust their running order

If you’re flying to the gig:

  • Find out whether your travel costs are being covered by the organisers, unlikely if you’re a relatively unknown band
  • If staying overnight, book flights and accommodation once you’ve written confirmation that you’re definitely playing. There are any number of comparison websites for this. Try to find deals that allow you to make changes without further charge
  • Find out what the luggage allowance is, because most of it will be your gear
  • You’ll need flight cases for your gear; gig bags are only suitable for your carry-on luggage
  • Organise insurance for both yourself and your equipment
  • Check the validity of passports. If not, get onto that immediately, as most Passport Offices process applications with little urgency
  • Foreign currency; look into whether you’ll be better off organising it before you leave, or once you arrive
  • Have a budget which covers everything; remember, you have to eat
  • Check your mobile phone provider, that there is coverage where you’re going, and what the charges are

Conclusion

Taking on a festival gig takes a lot of preparation, and that’s before you’ve even arrived. To summarise, bear in mind:

  • the travel, the cost, the fee (if any), and your time
  • Only pay to play if it’s a life-changing opportunity
  • Check the event’s details in advance, such as address, date and arrival time, gear required and/or supplied, fee (if any), plus policies on guests and sustenance
  • If driving, checked you’re insured, your vehicle is legal and roadworthy, can accommodate people and gear, and that you know where you’re going
  • If flying, budget for flights, accommodation, insurance, food. Check your passport’s current, that your mobile will work and not cost you a fortune.

In the next tutorial I'll look at how a gigging rig may not be suitable for the festival experience.


How to Modify PowerPoint Templates With Slide Design Variants

How to Make Snappy 5-Minute Presentations (+Quick Ideas & Tips)

Take Our New Short Course on Logo Design

Getting Started With Matter.js: Introduction

Getting Started With Matter.js: Introduction

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in the browser. It offers a lot of features like the ability to create rigid bodies and assign physical properties like mass, area or density to them. You can also simulate different kinds of collisions and forces like gravity and friction.

Matter.js supports all major browsers including IE8+. Additionally, it is suitable for use on mobile devices as it can detect touch and has responsiveness. All these features make it worth investing your time to learn how to use the engine as you will then be able to create physics-based 2D games or simulations easily. In this tutorial, I will cover the basics of this library, including its installation and usage, and I'll provide a working example.

Installation

You can install Matter.js by using package managers like Bower or NPM with the help of the following commands:

You can also get a link to the library from a CDN and directly include it in your projects like this:

A Basic Example

The best way to learn about Matter.js is to see some actual code and understand how it works. In this section, we will create a few bodies and go through the required code line by line.

We begin by creating aliases for all the Matter.js modules that we might need in our project. The Matter.Engine module contains methods for creating and manipulating engines. Engines are required in a project to update the simulation of the world. The Matter.Render module is a basic HTML5 canvas-based renderer. This module is required to visualize different engines. 

The Matter.World module is used to create and manipulate the world in which the engine runs. It is similar to the Matter.Composite module, but it lets you tweak a few additional properties like gravity and bounds. The last module in our code, called Matter.Bodies, allows you to create rigid body objects. Another similar module called Matter.Body allows you to manipulate individual bodies.

The next line uses the create([settings]) method of the Matter.Engine module to create a new engine. The settings parameter in the above method is actually an object with key-value pairs to override the default values of a few properties related to the engine. 

For example, you can control the global scaling factor of time for all the bodies in the world. Setting a value less than 1 will result in the world interacting in slow motion. Similarly, a value greater than 1 will make the world fast-paced. You will learn more about the Matter.Engine module in the next tutorial of the series.

After that, we use the create([settings]) method of the Matter.Render module to create a new renderer. Just like the Engine module, the settings parameter in the above method is an object used to specify different options for the parameter. You can use the element key to specify the element where the library should insert the canvas. Similarly, you can also use the canvas key to specify the canvas element where the Matter.js world should be rendered. 

There is an engine key that you can use to specify the engine that should be used to render the world. There is also an options key that actually accepts an object as its value. You can use this key to set values for different parameters like the width or height of the canvas. You can also turn the wireframes on or off by setting the value of wireframe key to true or false respectively.

The next few lines create different bodies that will interact in our world. The bodies are created with the help of the Matter.Bodies module in Matter.js. In this example, we have just created two circles and a rectangle using the circle() and rectangle() method. Other methods are available as well to create different polygons.

Once we have created the bodies, we need to add them to a world of our choice using the add() method from the Matter.World module. After adding the necessary bodies to our world, we just need to run the engine and the renderer using the run() method from the respective modules. That is basically all the code you need to create and render a world in Matter.js.

The code at the beginning of this section creates the following result.

Common Matter.js Modules

There are more than 20 different modules in Matter.js. All these modules provide different methods and properties that are useful for creating different kinds of simulations and allow you to interact with them. Some of these modules handle collisions, while others handle rendering and simulation. 

The example in the previous section used four different modules to handle the rendering, simulation and creation of bodies. In this section, you will learn about the roles of some common modules available in Matter.js.

  • Engine: You need engines to update the simulations of your Matter.js world. The Engine module provides different methods and properties that allow you to control the behavior of different engines.
  • World: This module provides you with methods and properties to create and manipulate whole worlds at once. The World is actually a Composite body with additional properties like gravity and bounds.
  • Bodies: The Bodies module contains different methods to help you create rigid bodies with common shapes like a circle, rectangle or trapezium.
  • Body: This module provides you different methods and properties to create and manipulate the rigid bodies that you have created using the functions from the Bodies module. This module allows you to scale, rotate or translate individual bodies. It also has functions to let you specify the velocity, density or inertia of different bodies. Because of so many functions, the third tutorial in this series only discusses the methods and properties available in the Body module.
  • Composites: Just like the Bodies module, this module contains different methods that you can use to create composite bodies with common configurations. For example, you can create a stack or pyramid of rectangular boxes using just a single method with the help of Composites module.
  • Composite: The Composite module has methods and properties that allow you to create and manipulate composite bodies. You can read more about the Composite and Composites modules in the fourth tutorial of the series.
  • Constraint: This module allows you to create and manipulate constraints. You can use a constraint to make sure that two bodies or a fixed world-space point and a body maintain a fixed distance. It is similar to connecting two bodies through a steel rod. You can modify the stiffness of these constraints so that the rod starts acting more like springs. Matter.js uses constraints when creating a Newton's cradle or a chain composite.
  • MouseConstraint: This module provides you with methods and properties that let you create and manipulate mouse constraints. This is helpful when you want different bodies in the world to interact with the user. 

Final Thoughts

This tutorial was meant to introduce you to the Matter.js library. Keeping that in mind, I have provided a quick overview of the features and installation of the library. The basic example involving two circles and a box shows how easy it is to create simple simulations using the library. 

Since Matter.js has a lot of modules each of which adds its own unique methods to the engine, I have written a brief summary of few common modules. The rest of the series will focus on teaching you about these common modules in more detail.  


10 More Popular HTML5 Projects for You to Use and Study

Best Photography Portfolio Themes for WordPress

Mobile Development Languages

Mobile Development Languages

If you want to code a mobile app, you need to know a programming language. But it can be hard to choose the best language (or languages) for a project. There are a lot of options out there, and in this post I'll help you narrow them down so that you can pick the best.

It all depends on what you're building. For certain apps, mobile developers may not need all the available features of a particular language. In other situations, a single app may require more than one language. In this tutorial, I'll go through various mobile development languages and highlight some of the details that can help you make a decision. 

Let's start with some languages which you may already be familiar with.

Android Languages

Java

According to the TIOBE Index, Java is the most popular programming language as of June 2017. If you want to develop Android apps, you'll most likely to stick to Java. It has a large and established developer community, and that means you can easily get technical support and help. 

So, when you're developing for mobile with Java, you are free to come up with any type of app you can think of. The only limits will be your imagination and the level of your Java knowledge.

  • Android
    Android From Scratch: An Overview of Android Application Development
    Ashraff Hathibelagal
  • Java
    Learn Java for Android
    Sue Smith

Kotlin

Kotlin was designed and developed by JetBrains, the Czech company known for their popular IDE, IntelliJ IDEA. Google's Android team has recently announced that they are officially adding support for the Kotlin programming language. 

Kotlin was developed to address some of the issues in Java. According to the language's fans, Kotlin syntax is simpler, cleaner, and leads to less code bloat. This helps you focus more on solving the actual problem, rather than struggling with verbose syntax. Also, you can use Kotlin and Java together in the same project, and that makes it really powerful.

  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby

iOS Languages

Swift

If you want to develop for iOS, Swift might be the language for you. Introduced in 2014 and declared open source in 2015, Swift is swiftly catching up with mobile developers. It's very popular, especially among new iOS development startups. 

Apple has added some great features to the language, such as simplified syntax, the ability to easily pinpoint programmer errors, etc. Apple's huge efforts to promote Swift clearly indicate that it wants this new language to become the mainstream programming language for its app ecosystem.

  • Swift
    Create iOS Apps With Swift 3
    Markus Mühlberger
  • Swift
    Swift From Scratch: Introduction
    Bart Jacobs

Objective-C

Objective-C was the original development language for iOS. While the recently introduced Swift language is the future of iOS development, many advanced projects still rely on Objective-C. So the transition from Objective-C to Swift is expected to be somewhat slow, and you may need both of them for some projects, at least for the time being.

Cross-Platform Languages

JavaScript

JavaScript has a long history going back to the early days of the World Wide Web. A very popular front-end and server-side language, it lets web developers do everything from enhancing the user experience of their websites to building complete web apps. 

Today, there are several JavaScript frameworks that specifically target mobile development platforms, such as Ionic 2 and React Native. It's very easy to develop cross-platform mobile apps using these frameworks and libraries. This means you only have to write a single version of your app, and it will run on iOS or Android.

  • JavaScript
    JavaScript Fundamentals
    Dan Wellman
  • Ionic 2
    Introduction to Ionic 2
    Wernher-Bel Ancheta
  • React Native
    Get Started With React Native
    Markus Mühlberger

TypeScript

TypeScript is a superset of JavaScript and offers better safety by adding optional static typing. It also provides better support for developing large-scale applications. Developed and maintained by Microsoft, TypeScript allows developers to write cross-platform mobile apps using frameworks such as NativeScript.

  • Web Development
    Getting Started with TypeScript
    Sayanee Basu
  • NativeScript
    Code a Mobile App With NativeScript
    Keyvan Kasaei

Other Languages

C#

C# is the language of Windows Mobile. It's very similar to C++ and Java. Microsoft has adopted some of the features of Java to simplify its architecture, while maintaining the C++ like design. It also has a large and active community of developers who are always friendly and helpful.

C

C is the second most popular language on the TIOBE index, and just like Java, its community is full of seasoned developers who could offer you valuable advice on how to write bug-free code. 

Created by Dennis Ritchie, while working for Bell Labs, C is a widely adopted and powerful language that allows you to directly manipulate low-level operations of a computer. If you want to use Android NDK (Native Development Kit), you'll need to get familiar with the C language.

C++

If you are familiar with C, then you'll really enjoy reading and writing C++ code. C++ is an extension of C, with more high-level features and support for object-oriented programming. C++ is also a favorite language of Android NDK developers. You can use C++ to develop Windows Mobile apps too. C++ goes head to head with Java in the field of software development, and it's really worth mastering.

Python

Python is another popular language that's easy to learn and easy to read. The creators of the language have made extra efforts to keep the syntax as simple and clear as possible. This really helps novice developers maintain high levels of productivity, from day one. If you are comfortable with writing Python code, then you can use frameworks such as Kivy to develop cross-platform mobile apps.

  • Python
    Learn to Code With Python
    Derek Jensen

Ruby

Ruby is an object-oriented scripting language, influenced by Ada, C++, Perl, Python, and Lisp. RubyMotion is a great framework for developing native and cross-platform mobile apps in Ruby. It's fairly easy to learn Ruby, thanks to its elegant syntax that focuses on simplicity and productivity.

  • Programming Fundamentals
    Learn to Code With Ruby
    José Mota

How to Classify the Languages?

Mobile apps can be grouped into three categories, namely native, hybrid, and native cross-platform. Native apps can fully utilize all the OS facilities and features, and they are the fastest when it comes to performance. However, you need to maintain different codebases for different mobile platforms, as each platform uses different programming languages.

For example, Android platform makes use of Java plus C/C++ to develop native apps. Apple's iOS platform relies on Objective-C and Swift as its native languages. C# is used by Windows Mobile platform to code its native apps. All of these native app programming languages are compiled, rather than interpreted.

Hybrid mobile apps are actually websites that are designed to work with mobile devices too. A user can access them via a mobile browser as if they are visiting a website on a desktop computer. The combination of HTML5, CSS and JavaScript is the obvious choice, if you want to develop web apps.

Recently, a new batch of mobile cross-platform frameworks has emerged. These frameworks combine the best features of native apps and hybrid apps—they're fast and light and can access the full power of the native device, but they also are coded with JavaScript and other web languages, so a lot of code can be reused between platforms.

React Native and NativeScript are popular native cross-platform frameworks. If you want to learn more about these, check out our comprehensive beginner course or some of our many tutorials.

Comparison of Features

Before getting deeper into the detailed language features, you must select a platform. You can refer to the article Mobile Development Platforms to get an idea of various platforms and how to pick the one that suits you best. Assuming that you've already selected a mobile development platform, let's see how these languages compare in terms of their features.

  • Mobile Development
    Mobile Development Platforms
    Bala Durage Sandamal Siripathi

Native Android

If you want to develop for native Android, Java and Kotlin are your obvious choices. So let's have a look at them.

Null Safety

Kotlin has better control over Null references so that the famous NullPointerException bugs (common in Java) are much easier to eliminate. This reduces development time and improves programmer productivity.

Concurrency

Although Java supports concurrent operations, the relevant code may suffer heavily from readability and maintainability issues. Kotlin addresses these issues by using Coroutines. The resulting code is easily readable and easily understandable too.

Type System

Java's type system isn't consistent, and this can sometimes lead to confusion. In particular, the primitive types such as integer, boolean, and so on need to be handled as special cases. By contrast, Kotlin has a relatively simple and more versatile type system that minimizes programmer errors and mistakes.

Supported Programming Styles

Although Java can theoretically support various programming styles, some developers believe that it overly promotes OOP (Object-Oriented Programming). Kotlin doesn't seem to enforce any particular style of programming, so developers have more freedom to choose an approach that fits best. However, Kotlin developers need to have a thorough knowledge of software architecture and development principles.

Which One to Choose?

In a nutshell, it seems that Kotlin is better than Java, but it may take some time for a complete transformation. One challenge is that programmers are used to the thinking patterns enforced by Java. Another is that Kotlin is a new language, and certain features are still experimental.

Anyway, Google has clearly announced that they will offer complete support for Kotlin. In fact, Android Studio, the official Android IDE, now comes with full support for Kotlin. New features and capabilities are constantly added to Kotlin. Over the next few years, we are going to experience a transition period from Java to Kotlin, at least in native Android development.

Native iOS

Objective-C and Swift are the two options you have for iOS development. So let's have a look at each one's features.

Code Syntax

Swift has simpler and clearer syntax to help programmers achieve their goals with the minimum number of LOC (Lines Of Code). This also helps reduce programmer errors and eases bug fixing.

Memory Management

Swift clearly beats Objective-C, when it comes to memory management. Swift enforces more robust and reliable control mechanisms, allowing programmers to avoid undesirable memory leaks.

Performance

Execution of Swift code is much faster than that of Objective-C. This clearly leads to faster app performance and better user experience.

Supported Programming Styles

Unlike Objective-C, Swift has built-in support for functional programming too. So developers don't have to limit themselves to any pre-defined programming styles. That helps developers understand the problem clearly and come up with a better solution.

Which One to Choose?

Just as Kotlin is slowly replacing Java in native Android development, Swift seems sure to thrive in native iOS development, forcing Objective-C to retire. Apple has already started extensive support for Swift, and that's going to get even better in the future. Like Android developers, iOS developers are also experiencing a transition period at the moment. 

While there are several code migration tools available, it may not be possible to fully convert Objective-C projects to Swift without issues. Sometimes, specific workarounds may be required, and that might need a fair knowledge of Objective-C. So the best strategy is to give priority to Swift and learn a bit of Objective-C only when it's absolutely necessary. Also, you need to keep an eye on the latest Swift developments and trends.

Cross-Platform Apps

JavaScript (coupled with other HTML5 technologies) is the most used cross-platform mobile development language. There are also other languages, such as Python and Ruby, but JavaScript has the broadest range of support and adoption. 

Unless you are already a big Ruby or Python fan and you want to try out the cutting-edge of mobile development with those languages, you should stick with JavaScript or its type-augmented sibling, TypeScript.

Conclusion

Choosing a mobile development language can be tricky if you don't understand the features of each one, along with the current industry trends. With this knowledge, though, it's easy to see that choosing a language heavily depends on the particular mobile development platform too.

I'm sure now you have a clearer picture of mobile app development languages and are able to match the relevance of their features to the latest development trends. So just get started coding your next app with confidence!

If you want some help getting started with a new language, check out some of the tutorials and video courses linked throughout this post, or some of our other posts on mobile development!

  • Mobile Development
    Mobile Development Platforms
    Bala Durage Sandamal Siripathi
  • React Native
    Get Started With React Native Layouts
    Wernher-Bel Ancheta
  • NativeScript
    Create Your First NativeScript App
    Wernher-Bel Ancheta
  • Android Studio
    Coding Functional Android Apps in Kotlin: Getting Started
    Jessica Thornsby
  • Swift
    Swift From Scratch: An Introduction to Functions
    Bart Jacobs
  • Java
    What's the Difference Between Java and JavaScript?
    Tom McFarlin
  • Ionic 2
    Code Your First Ionic 2 App: Getting Set Up
    Wernher-Bel Ancheta

10 Easy Pieces: Analog Transitions for Final Cut Pro X

How to Create Khaleeji Woman Emoji iMessage Stickers in Adobe Illustrator

Friday, July 21, 2017

How to Create a Sloth Illustration in Vector

How to Make an Animated Parallax Video from a Photo (With a Photoshop Action)

Understand the Basics of Laravel Middleware

Understand the Basics of Laravel Middleware

In this article, we'll dive deep into the Laravel framework to understand the concept of middleware. The first half of the article begins with an introduction to middleware and what it's actually used for.

As we move on, we'll cover how to create custom middleware in a Laravel application. After creation of your custom middleware, we'll explore the options available to register it with Laravel so that it could be actually invoked during the request processing flow.

I hope that you consider yourself familiar with basic Laravel concepts and the Artisan command-line tool to generate the scaffolding code. Of course, a working installation of the latest Laravel application allows you to run the examples provided in this article straight away.

What Is Middleware in Laravel?

We could think of middleware as a mechanism that allows you to hook into the typical request processing flow of a Laravel application. A typical Laravel route processing goes through certain stages of request processing, and the middleware is one of those layers an application has to pass through.

So what exactly is the point of hooking into the Laravel request processing flow? Think of something that requires an execution at the early stages of bootstrapping of an application. For example, it's necessary to authenticate users at the early stages to decide whether they're allowed to access the current route.

A few things I could think of that you could achieve through middleware are:

  • logging of requests
  • redirecting users
  • altering/sanitizing the incoming parameters
  • manipulating the response generated by the Laravel application
  • and many more

In fact, the default Laravel application already ships a couple of important pieces of middleware with it. For example, there's middleware that checks if the site is in maintenance mode. On the other hand, there's middleware to sanitize the input request parameters. As I mentioned earlier, the user authentication is also achieved by the middleware itself.

I hope that the explanation so far helps you to feel more confident about the term middleware. If you're still confused, don't worry about it as we're going to build a piece of custom middleware from the next section onwards that should help you understand exactly how middleware could be used in the real world.

How to Create Custom Middleware

In this section, we'll create our custom middleware. But what exactly is our custom middleware going to accomplish?

Recently, I came across a custom requirement from my client that if users access the site from any mobile device, they should be redirected to the corresponding sub-domain URL with all the querystring parameters intact. I believe this is the perfect use case to demonstrate how Laravel middleware could be used in this particular scenario.

The reason why we would like to use middleware in this case is the need to hook into the request flow of the application. In our custom middleware, we'll inspect the user agent, and users are redirected to the corresponding mobile URL if they are using a mobile device.

Having discussed all that theory, let's jump into the actual development, and that's the best way to understand a new concept, isn't it?

As a Laravel developer, it's the Artisan tool that you'll end up using most of the time to create basic template code should you wish to create any custom functionality. Let's use it to create a basic template code for our custom middleware.

Head over to the command line and go the document root of your project. Run the following command to create the custom middleware template MobileRedirect.

And that should create a file app/Http/Middleware/MobileRedirect.php with the following code.

More often than not, you'll notice the implementation of the handle method that acts as the backbone of the middleware, and the primary logic of the middleware you're looking to implement should go here.

Let me grab this opportunity to introduce the types of middleware that Laravel comes with. Mainly, the are two types—before middleware and after middleware.

As the name suggests, the before middleware is something that runs before the request is actually handled and the response is built. On the other hand, the after middleware runs after the request is handled by the application and the response is already built at this time.

In our case, we need to redirect the user before the request is handled, and hence it'll be developed as a before middleware.

Go ahead and modify the file app/Http/Middleware/MobileRedirect.php with the following contents.

For the sake of simplicity, we just check the existence of the mobile querystring parameter, and if it's set to TRUE, the user will be redirected to the corresponding mobile site URL. Of course, you would like to use the user agent detection library should you wish to detect it in real time.

Also, you would like to replace the mobile-site-url-goes-here route with the proper route or URL as it's just a placeholder for demonstration purposes.

Following our custom logic, there's a call to $next($request) that allows the request to be processed further in the application chain. The important thing to note in our case is that we've placed the mobile detection logic prior to the $next($request) call, effectively making it a before middleware.

And with that, our custom middleware is almost ready to be tested. At the moment, there's no way Laravel knows about our middleware. To make that happen, you need to register your middleware with the Laravel application, and that's exactly the topic of our next section.

Before heading into the next section, I would like to demonstrate how the after middleware looks, just in case someone out there is curious about it.

As you would already have noticed, the custom logic of the middleware gets executed after the request is processed by the Laravel application. At this time, you have access to the $response object as well, which allows you to manipulate certain aspects of it if you wish to.

So that was the story of after middleware.

Our Custom Middleware in Action

This section describes the process of registering the middleware with the Laravel application so that it could actually be invoked during the request processing flow.

Go ahead and open the file app/Http/Kernel.php and look for the following snippet.

As you can see, the $middleware holds the array of middleware that comes with the default installation of Laravel. The middleware listed here will be executed upon every Laravel request, and thus it's an ideal candidate to place our own custom middleware.

Go ahead and include our custom middleware as shown in the following snippet.

Now, try to access any of your Laravel routes with the querystring mobile=1, and that should trigger our middleware code!

So that's how you're supposed to register your middleware that needs to be run on every request. However, sometimes you wish to run your middleware for the specific routes only. Let's check how to achieve that by using the $routeMiddleware.

In the context of our current example, let's assume that the users will be redirected to a mobile site if they access any specific route on your site. In this scenario, you don't want to include your middleware in the $middleware list.

Instead, you would like to attach the middleware directly to the route definition, as shown below.

In fact, we could go one step further and create an alias for our middleware so that you don't have to use inline class names.

Open the file app/Http/Kernel.php and look for the $routeMiddleware that holds the mappings of aliases to middleware. Let's include our entry into that list, as shown in the following snippet.

And the revised route definition looks like this.

And that's the story of registering middleware with the Laravel application. That was pretty straightforward, wasn't it?

In fact, we've reached the end of this article, and I hope you've thoroughly enjoyed it.

Conclusion

Exploring the architectural concept in any framework is always exciting stuff, and that's what we did in this article as we explored middleware in the Laravel framework.

Starting with a basic introduction to middleware, we shifted our attention to the topic of creating custom middleware in a Laravel application. And it was the latter half of the article that discussed how to register your custom middleware with Laravel, and that was also the opportunity to explore the different ways you could attach your middleware.

Hopefully the journey was fruitful and the article has helped you enrich your knowledge. Also, if you want me to come up with specific topics in the upcoming articles, you could always drop me a line about that.

That's it for today, and don't hesitate to shoot your queries, if any, using the feed below!


How to Write an Employee Handbook (For Your Small Business)

International Artist Feature: Switzerland

New Course: Getting Started With Foundation Building Blocks

How to Get Aviation Insurance for Your Drone

Thursday, July 20, 2017

25 Professional Modern Letterhead Templates

Creating a Blogging App Using React, Part 4: Update & Delete Posts

How to Create a Trendy Marble and Rose Gold Text Effect in Adobe Photoshop

Basic 2D Platformer Physics, Part 8: Slopes

How to Define and Implement a Go Interface

How to Define and Implement a Go Interface

Go's object-oriented model revolves around interfaces. I personally believe that interfaces are the most important language construct and all design decisions should be focused on interfaces first. 

In this tutorial, you'll learn what an interface is, Go's take on interfaces, how to implement an interface in Go, and finally the limitations of interfaces vs. contracts.

What Is a Go Interface?

A Go interface is a type that consists of a collection of method signatures. Here is an example of a Go interface:

The Serializable interface has two methods. The Serialize() method takes no arguments and returns a string and an error, and the Deserialize() method takes a string and returns an error. If you've been around the block, the Serializable interface is probably familiar to you from other languages, and you can guess that the Serialize() method returns a serialized version of the target object that can be reconstructed by calling Deserialize() and passing the result of the original call to Serialize().

Note that you don't need to provide the "func" keyword at the beginning of each method declaration. Go already knows that an interface can only contains methods and doesn't need any help from you telling it it's a "func".

Go Interfaces Best Practices

Go interfaces are the best way to construct the backbone of your program. Objects should interact with each other through interfaces and not through concrete objects. This means that you should construct an object model for your program that consists only of interfaces and basic types or data objects (structs whose members are basic types or other data objects). Here are some of the best practices you should pursue with interfaces.

Clear Intentions

It's important that the intention behind every method and the sequence of calls is clear and well defined both to callers and to implementers. There is no language-level support in Go for that. I'll discuss it more in the "Interface vs. Contract" section later.

Dependency Injection

Dependency injection means that an object that interacts with another object through an interface will get the interface from the outside as a function or method argument and will not create the object (or call a function that returns the concrete object). Note that this principle applies to standalone functions too and not just objects. A function should receive all its dependencies as interfaces. For example:

Now, you call function foo() with different implementations of SomeInterface, and it will work with all of them.

Factories

Obviously, someone has to create the concrete objects. This is the job of dedicated factory objects. Factories are used in two situations:

  1. At the beginning of the program, factories are used to create all the long-running objects whose lifetime typically matches the lifetime of the program.
  2. During the program runtime, various objects often need to instantiate objects dynamically. Factories should be used for this purpose too.

It is often useful to provide dynamic factory interfaces to objects to sustain the interface-only interaction pattern. In the following example, I define a Widget interface and a WidgetFactory interface that returns a Widget interface from its CreateWidget() method. 

The PerformMainLogic() function receives a WidgetFactory interface from its caller. It is now able to dynamically create a new widget based on its widget spec and invokes its Widgetize() method without knowing anything about its concrete type (what struct implements the interface).

Testability

Testability is one of the most important practices for proper software development. Go interfaces are the best mechanism to support testability in Go programs. To thoroughly test a function or a method, you need to control and/or measure all inputs, outputs and side-effects to the function under test. 

For non-trivial code that communicates directly with the file system, the system clock, databases, remote services and user interface, it is very difficult to achieve. But, if all interaction goes through interfaces, it is very easy to mock and manage the external dependencies. 

Consider a function that runs only at the end of the month and runs some code to clean up bad transactions. Without interfaces, you would have to go to extreme measures such as changing the actual computer clock to simulate the end of the month. With an interface that provides the current time, you just pass a struct that you set the desired time to.

Instead of importing time and directly calling time.Now(), you can pass an interface with a Now() method that in production will be implemented by forwarding to time.Now(), but during testing will be implemented by an object that returns a fixed time to freeze the test environment.

Using a Go Interface

Using a Go interface is completely straightforward. You just call its methods like you call any other function. The big difference is that you can't be sure what will happen because there may be different implementations.

Implementing a Go Interface

Go interfaces can be implemented as methods on structs. Consider the following interface:

Here are two concrete implementations of the Shape interface:

The square and rectangle implement the calculations differently based on their fields and geometrical properties. The next code sample demonstrates how to populate a slice of the Shape interface with concrete objects that implement the interface, and then iterate over the slice and invoke the GetArea() method of each shape to calculate the total area of all the shapes.

Base Implementation

In many programming languages, there is a concept of a base class that can be used to implement shared functionality used by all sub-classes. Go (rightfully) prefers composition to inheritance. 

You can get a similar effect by embedding a struct. Let's define a Cache struct that can store the value of previous computations. When a value is retrieved from the case, it also prints to the screen "cache hit", and when the value is not in the case, it prints "cache miss" and returns -1 (valid values are unsigned integers).

Now, I'll embed this cache in the Square and Rectangle shapes. Note that the implementation of GetPerimeter() and GetArea() now checks the cache first and computes the value only if it is not in the cache.

Finally, the main() function computes the total area twice to see the cache effect.

Here is the output:

Interface vs. Contract

Interfaces are great, but they don't ensure that structs implementing the interface actually fulfill the intention behind the interface. There is no way in Go to express this intention. All you get to specify is the signature of the methods. 

In order to go beyond that basic level, you need a contract. A contract for an object specifies exactly what each method does, what side effects are performed, and what the state of the object is at each point in time. The contract always exists. The only question is if it's explicit or implicit. Where external APIs are concerned, contracts are critical.

Conclusion

The Go programming model was designed around interfaces. You can program in Go without interfaces, but you would miss their many benefits. I highly recommend that you take full advantage of interfaces in your Go programming adventures.