Laravel Reverb
is a new first-party WebSocket server for Laravel applications, bringing
real-time communication between client and server. Some of the features
of Reverb include.
Blazing Fast
Reverb is fine-tuned for speed. A single server can support thousands
of connections and piping data without the delay and inefficiency of
HTTP polling.
Seamless Integration
Develop with Laravel’s broadcasting capabilities. Deploy with Reverb’s first-party Laravel Forge integration. Monitor with baked-in support for Pulse.
Built for Scale
Infinitely increase capacity by utilizing Reverb’s built-in support
for horizontal scaling using Redis, allowing you to manage connections
and channels across multiple servers.
Pusher
Reverb utilizes the Pusher protocol for WebSockets, making it immediately compatible with Laravel broadcasting and Laravel Echo.
Currently, Laravel includes nine middleware and many you would never
customize. However, if you do want to customize them, that is moved to
the App/ServiceProvider. For example:
public function boot(): void{ EncryptCookies::except(['some_cookie']);}
Model casts are now defined as a method instead of a property. When
defined as a method we can do other things, like call other methods
directly from the casts. Here is an example using a new Laravel 11 AsEnumCollection:
This aims to streamline the core of the framework since multiple
classes currently have “dd” or “dump” methods. Plus you can use this Dumpable trait in your own classes:
class Stringable implements JsonSerializable, ArrayAccess{ use Conditionable, Dumpable, Macroable, Tappable; str('foo')->dd(); str('foo')->dump();
Laravel has a lot of config files, and Laravel 11 removes these, and all config options cascade down. The .env has been expanded to include all the options you’d want to set.
Laravel 11 includes a new once helper method
that ensures you’ll always get the same value no matter how many times
you call an object method. The once function is helpful when you have
some code that you want to ensure only ever runs one time.
When you start a new Laravel app, it comes with some default
migrations from 2014 and 2019. These now will come with the dates
removed and moved into just two files.
By default, there will be only two route files, console.php and web.php. API routes will now become opt-in via php artisan install:api, giving you the API routes file and Laravel Sanctum.
The same with websocket broadcasting, php artisan install:broadcasting.
In older versions of Laravel, if you changed your APP_KEY
it could lead to broken data in the database. Laravel 11 has a new
graceful rotation which will NOT break old encrypted data, using an APP_PREVIOUS_KEYS comma-delimited list .env variable. It will auto re-encrypt the data using new key.
Named arguments
are not covered by Laravel’s backwards compatibility guidelines. They
may choose to rename function arguments when necessary in order to
improve the Laravel codebase. When calling Laravel methods using named
arguments should be done cautiously and with the understanding that the
parameter names may change in the future.
This was an early decision, but Laravel 11 apps require a minimum of
PHP 8.2. If you are running an older version of PHP, now is a good time
to get that upgraded.
Laravel is no longer dependent on the Doctrine DBAL and registering
custom Doctrines types is no longer necessary for the proper creation
and alteration of various column types that previously required custom
types.
For all Laravel releases, bug fixes are provided for 18 months and
security fixes are provided for 2 years. For all additional libraries,
including Lumen, only the latest major release receives bug fixes.
So far, all these features are considered beta for Laravel 11 and are
designed to improve your workflow. Things can and probably change, and
we will keep this post updated as new features are announced.
The ultimate guide to the most useful design patterns
UPDATE NOTE: Updated the Proxy Pattern example to use ES6 Proxy and Reflect. Replaced images of source code snippets with GitHub gists.
In
this article, we are going to talk about design patterns that can be
and should be used to write better, maintainable JavaScript code. I
assume you have a basic understanding of JavaScript and concepts like
classes (classes in JavaScript can be tricky), objects, prototypal
inheritance, closures, etc.
This article is a long read as a whole because of the nature of the subject matter, so I have tried to keep the sections self-contained. So you as a reader can pick and choose specific parts (or, in this case, specific patterns) and ignore the ones you are not interested in or are well versed with. Now, let’s get started.
Note: Source code for the implementation of all the design patterns explained here is on GitHub.
Introduction
We write code to solve problems. These problems usually have many similarities, and, when trying to solve them, we notice several common patterns. This is where design patterns come in.
A design pattern is a term used in software engineering for a general, reusable solution to a commonly occurring problem in software design.
The underlying concept of design patterns has been around in the software engineering industry since the very beginning, but they weren’t really so formalised. Design Patterns: Elements Of Reusable Object-Oriented Software written by Erich Gamma, Richard Helm, Ralph Johnson,and John Vlissides — the famous Gang of Four (GoF)—was instrumental in pushing the formalised concept of design patterns in software engineering. Now, design patterns are an essential part of software development and have been so for a long time.
There were 23 design patterns introduced in the original book.
Design
patterns are beneficial for various reasons. They are proven solutions
that industry veterans have tried and tested. They are solid approaches
that solve issues in a widely accepted way and reflect the experience
and insights of the industry-leading developers that helped define them.
Patterns also make your code more reusable and readable while speeding
up the development process vastly.
Design patterns are by no means finished solutions. They only provide us with approaches or schemes to solve a problem.
Note:
In this article, we will mainly talk about design patterns from an
object-oriented point of view and in the context of their usability in
modern JavaScript. That is why many classic patterns from GoF may be
omitted, and some modern patterns from sources like Addy Osmani’s Learn JavaScript Design Patterns
will be included. The examples are kept simple for easier understanding
and are hence not the most optimised implementation of their respective
design patterns.
Categories of Design Patterns
Design patterns are usually categorized into three major groups.
Creational Design Patterns
As
the name suggests, these patterns are for handling object creational
mechanisms. A creational design pattern basically solves a problem by
controlling the creation process of an object.
We will discuss the following patterns in detail: Constructor Pattern, Factory Pattern, Prototype Pattern, and Singleton Pattern.
Structural Design Patterns
These patterns are concerned with class and object composition. They help structure or restructure one or more parts without affecting the entire system. In other words, they help obtain new functionalities without tampering with the existing ones.
We will discuss the following patterns in detail: Adapter Pattern, Composite Pattern, Decorator Pattern, Façade Pattern, Flyweight Pattern, and Proxy Pattern.
Behavioral Design Patterns
These patterns are concerned with improving communication between dissimilar objects.
We will discuss the following patterns in detail: Chain of Responsibility Pattern, Command Pattern, Iterator Pattern, Mediator Pattern, Observer Pattern, State Pattern, Strategy Pattern, and Template Pattern.
Constructor Pattern
This
is a class-based creational design pattern. Constructors are special
functions that can be used to instantiate new objects with methods and
properties defined by that function.
It
is not one of the classic design patterns. In fact, it is more of a
basic language construct than a pattern in most object-oriented
languages. But in JavaScript, objects can be created on the fly without
any constructor functions or “class” definition. Therefore, I think it
is important to lay down the foundation for other patterns to come with
this simple one.
Constructor pattern is one of the most commonly used patterns in JavaScript for creating new objects of a given kind.
In this example, we define a Hero class with attributes like name and specialAbility and methods like getDetails. Then, we instantiate an object IronMan by invoking the constructor method with the new keyword passing in the values for the respective attributes as arguments.
// traditional Function-based syntax
function Hero(name, specialAbility) {
// setting property values
this.name = name;
this.specialAbility = specialAbility;
// declaring a method on the object
this.getDetails = function() {
return this.name + ‘ can ‘ + this.specialAbility;
};
}
// ES6 Class syntax
class Hero {
constructor(name, specialAbility) {
// setting property values
this._name = name;
this._specialAbility = specialAbility;
// declaring a method on the object
this.getDetails = function() {
return `${this._name} can ${this._specialAbility}`;
};
}
}
// creating new instances of Hero
const IronMan = new Hero(‘Iron Man’, ‘fly’);
console.log(IronMan.getDetails()); // Iron Man can fly
Factory Pattern
Factory
pattern is another class-based creational pattern. In this, we provide a
generic interface that delegates the responsibility of object
instantiation to its subclasses.
This
pattern is frequently used when we need to manage or manipulate
collections of objects that are different yet have many similar
characteristics.
In this example, we create a factory class named BallFactory that has a method that takes in parameters, and, depending on the parameters, it delegates the object instantiation responsibility to the respective class. If the type parameter is "football" or "soccer" object instantiation is handled by Football class, but if it is "basketball" object instantiation is handled by Basketball class.
class BallFactory {
constructor() {
this.createBall = function(type) {
let ball;
if (type === ‘football’ || type === ‘soccer’) ball = new Football();
else if (type === ‘basketball’) ball = new Basketball();
ball.roll = function() {
return The ${this._type} is rolling.;
};
return ball;
};
}
}
class Football {
constructor() {
this._type = ‘football’;
this.kick = function() {
return ‘You kicked the football.’;
};
}
}
class Basketball {
constructor() {
this._type = ‘basketball’;
this.bounce = function() {
return ‘You bounced the basketball.’;
};
}
}
// creating objects
const factory = new BallFactory();
console.log(myFootball.roll()); // The football is rolling. console.log(myBasketball.roll()); // The basketball is rolling. console.log(myFootball.kick()); // You kicked the football. console.log(myBasketball.bounce()); // You bounced the basketball.
Prototype Pattern
This
pattern is an object-based creational design pattern. In this, we use a
sort of a “skeleton” of an existing object to create or instantiate new
objects.
This
pattern is specifically important and beneficial to JavaScript because
it utilizes prototypal inheritance instead of a classic object-oriented
inheritance. Hence, it plays to JavaScript’s strength and has native
support.
In this example, we have a car object that we use as the prototype to create another object myCar with JavaScript’s Object.create feature and define an extra property owner on the new object.
// using Object.create as was recommended by ES5 standard
const car = {
noOfWheels: 4,
start() {
return ‘started’;
},
stop() {
return ‘stopped’;
},
};
Singleton
is a special creational design pattern in which only one instance of a
class can exist. It works like this — if no instance of the singleton
class exists then a new instance is created and returned, but if an
instance already exists, then the reference to the existing instance is
returned.
A perfect real-life example would be that of mongoose (the famous Node.js ODM library for MongoDB). It utilizes the singleton pattern.
In this example, we have a Database class that is a singleton. First, we create an object mongo by using the new operator to invoke the Database class constructor. This time an object is instantiated because none already exists. The second time, when we create the mysql object, no new object is instantiated but instead, the reference to the object that was instantiated earlier, i.e. the mongo object, is returned.
// usage
const mongo = new Database(‘mongo’);
console.log(mongo.getData()); // mongo
const mysql = new Database(‘mysql’); console.log(mysql.getData()); // mongo
Adapter Pattern
This
is a structural pattern where the interface of one class is translated
into another. This pattern lets classes work together that could not
otherwise because of incompatible interfaces.
This
pattern is often used to create wrappers for new refactored APIs so
that other existing old APIs can still work with them. This is usually
done when new implementations or code refactoring (done for reasons like
performance gains) result in a different public API, while the other
parts of the system are still using the old API and need to be adapted
to work together.
In this example, we have an old API, i.e. OldCalculator class, and a new API, i.e. NewCalculator class. The OldCalculator class provides an operationmethod for both addition and subtraction, while the NewCalculator provides separate methods for addition and subtraction. The Adapter class CalcAdapterwraps the NewCalculator to add the operation method to the public-facing API while using its own addition and subtraction implementation under the hood.
// old interface
class OldCalculator {
constructor() {
this.operations = function(term1, term2, operation) {
switch (operation) {
case ‘add’:
return term1 + term2;
case ‘sub’:
return term1 – term2;
default:
return NaN;
}
};
}
}
// Adapter Class
class CalcAdapter {
constructor() {
const newCalc = new NewCalculator();
this.operations = function(term1, term2, operation) {
switch (operation) {
case 'add':
// using the new implementation under the hood
return newCalc.add(term1, term2);
case 'sub':
return newCalc.sub(term1, term2);
default:
return NaN;
}
};
const newCalc = new NewCalculator();
console.log(newCalc.add(10, 5)); // 15
const adaptedCalc = new CalcAdapter(); console.log(adaptedCalc.operations(10, 5, ‘add’)); // 15;
Composite Pattern
This is a structural design pattern that composes objects into tree-like structures to represent whole-part hierarchies. In this pattern, each node in the tree-like structure can be either an individual object or a composed collection of objects. Regardless, each node is treated uniformly.
It
is a bit complex to visualize this pattern. The easiest way to think
about this is with the example of a multi-level menu. Each node can be a
distinct option, or it can be a menu itself, which has multiple options
as its child. A node component with children is a composite component,
while a node component without any child is a leaf component.
In this example, we create a base class of Component that implements the common functionalities needed and abstracts the other methods needed. The base class also has a static method that utilises recursion to traverse a composite tree structure made with its subclasses. Then we create two subclasses extending the base class — Leaf that does not have any children and Composite that can have children—and hence have methods handling adding, searching, and removing child functionalities. The two subclasses are used to create a composite structure—a tree, in this case.
class Component {
constructor(name) {
this._name = name;
}
getNodeName() {
return this._name;
}
// abstract methods that need to be overridden
getType() {}
addChild(component) {}
removeChildByName(componentName) {}
removeChildByIndex(index) {}
getChildByName(componentName) {}
getChildByIndex(index) {}
noOfChildren() {}
static logTreeStructure(root) {
let treeStructure = ”;
function traverse(node, indent = 0) {
treeStructure += ${'--'.repeat(indent)}${node.getNodeName()}\n;
indent++;
for (let i = 0, length = node.noOfChildren(); i < length; i++) {
traverse(node.getChildByIndex(i), indent);
}
}
This
is also a structural design pattern that focuses on the ability to add
behaviour or functionalities to existing classes dynamically. It is
another viable alternative to sub-classing.
The
decorator type behaviour is very easy to implement in JavaScript
because JavaScript allows us to add methods and properties to object
dynamically. The simplest approach would be to just add a property to an
object, but it will not be efficiently reusable.
In fact, there is a proposal to add decorators to the JavaScript language. Take a look at Addy Osmani’s post about decorators in JavaScript.
In this example, we create a Book class. We further create two decorator functions that accept a book object and return a “decorated” book object — giftWrap that adds one new attribute and one new function and hardbindBook that adds one new attribute and edits the value of one existing attribute.
class Book {
constructor(title, author, price) {
this._title = title;
this._author = author;
this.price = price;
}
getDetails() {
return ${this._title} by ${this._author};
}
}
This
is a structural design pattern that is widely used in the JavaScript
libraries. It is used to provide a unified and simpler, public-facing
interface for ease of use that shields away from the complexities of its
consisting subsystems or subclasses.
The use of this pattern is very common in libraries like jQuery.
In this example, we create a public facing API with the class ComplaintRegistry. It exposes only one method to be used by the client, i.e. registerComplaint. It internally handles instantiating required objects of either ProductComplaint or ServiceComplaint based on the type argument. It also handles all the other complex functionalities like generating a unique ID, storing the complaint in memory, etc. But, all these complexities are hidden away using the façade pattern.
let currentId = 0;
class ComplaintRegistry {
registerComplaint(customer, type, details) {
const id = ComplaintRegistry._uniqueIdGenerator();
let registry;
if (type === ‘service’) {
registry = new ServiceComplaints();
} else {
registry = new ProductComplaints();
}
return registry.addComplaint({ id, customer, details });
}
replyMessage({ id, customer, details }) {
return Complaint No. ${id} reported by ${customer} regarding ${details} have been filed with the Products Complaint Department. Replacement/Repairment of the product as per terms and conditions will be carried out soon.;
}
}
replyMessage({ id, customer, details }) {
return Complaint No. ${id} reported by ${customer} regarding ${details} have been filed with the Service Complaint Department. The issue will be resolved or the purchase will be refunded as per terms and conditions.;
}
}
// usage
const registry = new ComplaintRegistry();
const reportService = registry.registerComplaint(‘Martha’, ‘service’, ‘availability’);
// ‘Complaint No. 1 reported by Martha regarding availability have been filed with the Service Complaint Department. The issue will be resolved or the purchase will be refunded as per terms and conditions.’
const reportProduct = registry.registerComplaint(‘Jane’, ‘product’, ‘faded color’); // ‘Complaint No. 2 reported by Jane regarding faded color have been filed with the Products Complaint Department. Replacement/Repairment of the product as per terms and conditions will be carried out soon.’
Flyweight Pattern
This
is a structural design pattern focused on efficient data sharing
through fine-grained objects. It is used for efficiency and memory
conservation purposes.
This
pattern can be used for any kind of caching purposes. In fact, modern
browsers use a variant of a flyweight pattern to prevent loading the
same images twice.
In this example, we create a fine-grained flyweight class Icecream for sharing data regarding ice-cream flavours and a factory class IcecreamFactory to create those flyweight objects. For memory conservation, the objects are recycled if the same object is instantiated twice. This is a simple example of flyweight implementation.
// flyweight class
class Icecream {
constructor(flavour, price) {
this.flavour = flavour;
this.price = price;
}
}
// factory for flyweight objects
class IcecreamFactory {
constructor() {
this._icecreams = [];
}
createIcecream(flavour, price) {
let icecream = this.getIcecream(flavour);
if (icecream) {
return icecream;
} else {
const newIcecream = new Icecream(flavour, price);
this._icecreams.push(newIcecream);
return newIcecream;
}
}
const chocoVanilla = factory.createIcecream(‘chocolate and vanilla’, 15);
const vanillaChoco = factory.createIcecream(‘chocolate and vanilla’, 15);
// reference to the same object console.log(chocoVanilla === vanillaChoco); // true
Proxy Pattern
This
is a structural design pattern that behaves exactly as its name
suggests. It acts as a surrogate or placeholder for another object to
control access to it.
It
is usually used in situations in which a target object is under
constraints and may not be able to handle all its responsibilities
efficiently. A proxy, in this case, usually provides the same interface
to the client and adds a level of indirection to support controlled
access to the target object to avoid undue pressure on it.
The
proxy pattern can be very useful when working with network
request-heavy applications to avoid unnecessary or redundant network
requests.
In this example, we will use two new ES6 features, Proxy and Reflect.
A Proxy object is used to define custom behaviour for fundamental
operations of a JavaScript object (remember, function and arrays are
also object in JavaScript). It is a constructor method that can be used
to create a Proxy object. It accepts a target object that is to be proxied and a handler object that will define the necessary customisation. The handler object allows for defining some trap functions like get, set, has, apply, etc. that are used to add custom behaviour attached to their usage. Reflect,
on the other hand, is a built-in object that provides similar methods
that are supported by the handler object of Proxy as static methods on
itself. It is not a constructor; its static methods are used for
intercept-able JavaScript operations.
Now, we create a function that can be thought of as a network request. We named it as networkFetch.
It accepts a URL and responds accordingly. We want to implement a proxy
where we only get the response from the network if it is not available
in our cache. Otherwise, we just return a response from the cache.
The cache global variable will store our cached responses. We create a proxy named proxiedNetworkFetch with our original networkFetch as the targetand use apply method in our handler object to proxy the function invocation. The apply method gets passed on the target object itself. This value as thisArg and the arguments are passed to it in an array-like structure args.
We check if the passed url argument is in the cache. If it exists in the cache, we return the response from there, never invoking the original target function. If it does not, then we use the Reflect.apply method to invoke the targetfunction with thisArg (although it’s not of any significance in our case here) and the arguments it passed.
// Target
function networkFetch(url) {
return ${url} - Response from network;
}
// Proxy
// ES6 Proxy API = new Proxy(target, handler);
const cache = [];
const proxiedNetworkFetch = new Proxy(networkFetch, {
apply(target, thisArg, args) {
const urlParam = args[0];
if (cache.includes(urlParam)) {
return ${urlParam} - Response from cache;
} else {
cache.push(urlParam);
return Reflect.apply(target, thisArg, args);
}
},
});
// usage console.log(proxiedNetworkFetch(‘dogPic.jpg’)); // ‘dogPic.jpg – Response from network’ console.log(proxiedNetworkFetch(‘dogPic.jpg’)); // ‘dogPic.jpg – Response from cache’
Chain of Responsibility Pattern
This
is a behavioural design pattern that provides a chain of loosely
coupled objects. Each of these objects can choose to act on or handle
the request of the client.
A
good example of the chain of responsibility pattern is the event
bubbling in DOM in which an event propagates through a series of nested
DOM elements, one of which may have an “event listener” attached to
listen to and act on the event.
In this example, we create a class CumulativeSum, which can be instantiated with an optional initialValue. It has a method add that adds the passed value to the sum attribute of the object and returns the object itself to allow chaining of add method calls.
This is a common pattern that can be seen in jQuery as well, where almost any method call on a jQuery object returns a jQuery object so that method calls can be chained together.
// usage
const sum1 = new CumulativeSum();
console.log(sum1.add(10).add(2).add(50).sum); // 62
const sum2 = new CumulativeSum(10); console.log(sum2.add(10).add(20).add(5).sum); // 45
Command Pattern
This
is a behavioural design pattern that aims to encapsulate actions or
operations as objects. This pattern allows loose coupling of systems and
classes by separating the objects that request an operation or invoke a
method from the ones that execute or process the actual implementation.
The clipboard interaction API somewhat resembles the command pattern. If you are a Redux
user, you have already come across the command pattern. The actions
that allow the awesome time-travel debugging feature are nothing but
encapsulated operations that can be tracked to redo or undo operations.
Hence, time-travelling made possible.
In this example, we have a class called SpecialMath that has multiple methods and a Command class that encapsulates commands that are to be executed on its subject, i.e. an object of the SpecialMath class. The Command class also keeps track of all the commands executed, which can be used to extend its functionality to include undo and redo type operations.
class SpecialMath {
constructor(num) {
this._num = num;
}
It
is a behavioural design pattern that provides a way to access the
elements of an aggregate object sequentially without exposing its
underlying representation.
Iterators have a special kind of behaviour where we step through an ordered set of values one at a time by calling next()
until we reach the end. The introduction of Iterator and Generators in
ES6 made the implementation of the iterator pattern extremely
straightforward.
We have two examples below. First, one IteratorClass uses iterator spec, while the other one iteratorUsingGenerator uses generator functions.
The Symbol.iterator ( Symbol—a
new kind of primitive data type) is used to specify the default
iterator for an object. It must be defined for a collection to be able
to use the for...of looping construct. In the first example, we define the constructor to store some collection of data and then define Symbol.iterator, which returns an object with next method for iteration.
For the second case, we define a generator function passing it an array of data and returning its elements iteratively using next and yield. A generator function is a special type of function that works as a factory for iterators and can explicitly maintain its own internal state and yield values iteratively. It can pause and resume its own execution cycle.
// using Iterator
class IteratorClass {
constructor(data) {
this.index = 0;
this.data = data;
}
It
is a behavioural design pattern that encapsulates how a set of objects
interact with each other. It provides the central authority over a group
of objects by promoting loose coupling, keeping objects from referring
to each other explicitly.
In this example, we have TrafficTower as Mediator that controls the way Airplane objects interact with each other. All the Airplane objects register themselves with a TrafficTower object, and it is the mediator class object that handles how an Airplane object receives coordinates data of all the other Airplane objects.
class TrafficTower {
constructor() {
this._airplanes = [];
}
It
is a crucial behavioural design pattern that defines one-to-many
dependencies between objects so that when one object (publisher) changes
its state, all the other dependent objects (subscribers) are notified
and updated automatically. This is also called PubSub
(publisher/subscribers) or event dispatcher/listeners pattern. The
publisher is sometimes called the subject, and the subscribers are
sometimes called observers.
Chances are, you’re already somewhat familiar with this pattern if you have used addEventListener or jQuery’s .on to write even-handling code. It has its influences in Reactive Programming (think RxJS) as well.
In the example, we create a simple Subject class that has methods to add and remove objects of Observer class from subscriber collection. Also, a firemethod to propagate any changes in the Subject class object to the subscribed Observers. The Observer
class, on the other hand, has its internal state and a method to update
its internal state based on the change propagated from the Subject it has subscribed to.
class Subject {
constructor() {
this._observers = [];
}
subscribe(observer) {
this._observers.push(observer);
}
unsubscribe(observer) {
this._observers = this._observers.filter(obs => observer !== obs);
}
fire(change) {
this._observers.forEach(observer => {
observer.update(change);
});
}
}
class Observer {
constructor(state) {
this.state = state;
this.initialState = state;
}
update(change) {
let state = this.state;
switch (change) {
case ‘INC’:
this.state = ++state;
break;
case ‘DEC’:
this.state = –state;
break;
default:
this.state = this.initialState;
}
}
}
// usage
const sub = new Subject();
const obs1 = new Observer(1);
const obs2 = new Observer(19);
sub.subscribe(obs1);
sub.subscribe(obs2);
sub.fire(‘INC’);
console.log(obs1.state); // 2
console.log(obs2.state); // 20
State Pattern
It
is a behavioural design pattern that allows an object to alter its
behaviour based on changes to its internal state. The object returned by
a state pattern class seems to change its class. It provides
state-specific logic to a limited set of objects in which each object
type represents a particular state.
We will take a simple example of a traffic light to understand this pattern. The TrafficLight class changes the object it returns based on its internal state, which is an object of Red, Yellow, or Green class.
class TrafficLight {
constructor() {
this.states = [new GreenLight(), new RedLight(), new YellowLight()];
this.current = this.states[0];
}
It
is a behavioural design pattern that allows encapsulation of
alternative algorithms for a particular task. It defines a family of
algorithms and encapsulates them in such a way that they are
interchangeable at runtime without client interference or knowledge.
In the example below, we create a class Commute for encapsulating all the possible strategies for commuting to work. Then, we define three strategies namely Bus, PersonalCar, and Taxi. Using this pattern we can swap the implementation to use for the travel method of the Commute object at runtime.
// encapsulation
class Commute {
travel(transport) {
return transport.travelTime();
}
}
class Vehicle {
travelTime() {
return this._timeTaken;
}
}
// strategy 1
class Bus extends Vehicle {
constructor() {
super();
this._timeTaken = 10;
}
}
// strategy 2
class Taxi extends Vehicle {
constructor() {
super();
this._timeTaken = 5;
}
}
// strategy 3
class PersonalCar extends Vehicle {
constructor() {
super();
this._timeTaken = 3;
}
}
// usage
const commute = new Commute();
console.log(commute.travel(new Taxi())); // 5
console.log(commute.travel(new Bus())); // 10
Template Pattern
This
is a behavioural design pattern based on defining the skeleton of the
algorithm or implementation of an operation, but deferring some steps to
subclasses. It lets subclasses redefine certain steps of an algorithm
without changing the algorithm’s outward structure.
In this example, we have a Template class Employee that implements workmethod partially. It is for the subclasses to implement responsibilities method to make it work as a whole. We then create two subclasses Developer and Tester that extend the template class and implement the required method to fill the implementation gap.
Design
patterns are crucial to software engineering and can be very helpful in
solving common problems. But this is a very vast subject, and it is
simply not possible to include everything about them in a short piece.
Therefore, I made the choice to shortly and concisely talk only about
the ones I think can be really handy in writing modern JavaScript. To
dive deeper, I suggest you take a look at these books:
Today, February 24, CodeIgniter 4 was officially launched. The long-awaited update, which is actually a new framework, was launched today in honor of James Perry, who was responsible for conducting this new project and who died a few weeks ago victim lung cancer.
Version 4 has been completely rewritten and has no backwards compatibility, it brings PHP’s minimum version to run at 7.2, while Version 3 brings PHP 5.6 (discontinued).
Completely written in PHP 7, the new version has a leaner coding than
the previous ones, besides being more performative and giving
developers more productivity and performance in the web application
development process.
With a more organized and current code structure in relation to other
frameworks on the market, such as Laravel, the use of new features in
PHP 7 and other libraries is possible, sometimes requiring minimal
configurations.
The migration process from version 3 to 4 is very easy to do, as long
as the application to be migrated is within the standard architecture
model of CodeIgniter 3.
One of the great novelties of the new version, and which had been
highly demanded over the years, is the possibility of creating Rest APIs
without the need to use third party libraries to complement the
nonexistent functionalities until version 3.
Now that the stable version has been officially launched it is time
to start creating the projects and take advantage of all that
CodeIgniter 4 can offer in terms of performance and productivity in the
web application development process.
And remember, if you encounter problems or bugs, report through issues on GitHub and if you have questions about the use and operation, share on the Forum.
Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser’s video limits to pushing ads through WebSocket so ad blockers don’t detect them, you have to be clever to innovate at the bleeding edge of the web.
I was recently lucky enough to interview a Web Developer at the web’s largest adult website: Pornhub. I wanted to learn about the tech, how web APIs can improve, and what it’s like working on adult websites. Enjoy!
Note: The adult industry is very competitive so there were a few questions they could not answer. I respect their need to keep their tricks close to the vest.
Adult sites obviously display lots of graphic content. During the development process, are you using lots of placeholder images and videos? How far is the development content and experience from the end product?
We actually don’t use placeholders when we are developing the sites! In the end, what matters is the code and functionality, the interface is something we are very used to at this point. There’s definitely a little bit of a learning curve at first, but we all got used to it pretty quickly.
When it comes to cam streams and third party ad scripts, how do you mock such important, dynamic resources during site and feature development?
For development, the player is broken into two components. The basic player implements the core functionality and fires events. Development is done in a clean room. For integration on the sites, we want those third-party scripts and ads running so we can find problems as early in the process as possible. For special circumstances we’ll work with advertisers to allow us to manually trigger events that might normally be random.
An average page probably has at least one video, GIF advertisements, a few cam performer previews, and thumbnails of other videos. How do you measure page performance and how do you keep the page as performant as possible? Any tricks you can share?
We use a few measurement systems.
Our player reports metrics back to us about video playback performance and general usage
A third-party RUM system for general site performance.
WebpageTest private instances to script tests in the available AWS data centers. We use this mostly for seeing what might have been going on at a given time. It also allows us to view the “waterfall” from different locations and providers.
I have to assume the most important and complex feature on the front-end is the video player. From incorporating ads before videos, marking highlight moments of the video, changing video speed, and other features, how do you maintain the performance, functionality, and stability of this asset?
We have a dedicated team working strictly on the video player, their first priority is to constantly monitor for performance and efficiency. To do so we use pretty much everything that is available to us; browsers performance tools, web page tests, metrics etc. The stability and quality is assured by a solid QA round for any updates we do.
How many people are on the dedicated video team? How many front-end developers are on the team?
I’d say given the size of the product the team size is lean to average.
During your time working on adult websites, how have you seen the front-end landscape change? What new Web APIs have made your life easier?
I’ve definitely seen a lot of improvements on every single aspect of the frontend world;
From plain CSS to finally using LESS and Mixins, to a flexible Grid system with media queries and picture tags to accommodate different resolutions and screen sizes
jQuery and jQueryUI are slowly moving away, so we are going back to more efficient object oriented programming in vanilla JS. The frameworks are also very interesting in some cases
We love the new IntersectionObserver API, very useful for a more efficient way to load images
We started playing with the Picture-in-Picture API as well, to have that floating video on some of our pages, mainly to get user feedback about the idea.
Looking forward, are there any Web APIs that you’d love changed, improved, or even created?
Some of them that we would like changed or improved; Beacon, WebRTC, Service Workers and Fetch:
Beacon: some IOS issues where it doesn’t quite work with pageHide events
Fetch: No download progress and doesn’t provide a way to intercept requests
WebRTC: Simulcast layers are limited even for screenshare, if the resolution is not big enough
Service Workers: Making calls to navigator.serviceWorker.register isn’t intercepted by any service worker’s Fetch event handlers
WebVR is has been improving in the past few years — how useful is WebVR in its current state and how much of an effort are adult sites putting into support for VR content? Do haptics have a role in WebVR on your sites?
We’re investigating webXR and how to best adapt to emerging spatial
computing use cases, and as the largest distribution platform we need to
support creators and users however they want to experience our content.
But we’re still exploring what content and platforms should be like in
these new mediums.
We were the first major platform to support VR, computer vision, and virtual performers, and will continue to push new technology and the open web.
With so many different types of media and content on each page, what are the biggest considerations when it comes to desktop vs. mobile, if any?
Functionality restricted by operating system and browsers type
mainly. iOS vs Android is the perfect example when it comes to a
completely different set of access and features.
For example, some iOS Mobile devices don’t allow us to have a custom
video player while in Fullscreen, they force the native QuickTime
player. That has to be considered when we develop new ideas. Android on
the other hand gives us complete control and we can push our features to
the Fullscreen mode.
Adaptive streaming in HLS is also another example, IE and Edge are picky when it comes to HLS streaming quality, in that we need to prevent certain of the higher qualities, otherwise the video would constantly stutter and have artifacts.
What is the current minimum browser support for the adult sites you work on? Is Internet Explorer phased out?
We supported IE for a very long time but recently dropped support for anything older than IE11. With it we also stopped working with Flash for the video player. We are focusing on Chrome, Firefox and Safari mainly.
More broadly, can you share a little about the typical adult site’s stack? Server and/or front-end? Which libraries are you using?
Most of our sites use the following as a base:
Nginx
PHP
MySQL
Memcached and/or Redis
Other technologies like Varnish, ElasticSearch, NodeJS, Go, Vertica are used where appropriate.
For frontend, we run mostly vanilla Javascript, we’re slowly getting
rid of jQuery and we are just beginning to play with frameworks, mostly
Vue.js
From an outsider’s perspective, adult sites generally seem to
be very much alike: lots of video thumbnails, aggregated video
content, cam performers, adverts. As someone who works on them, what
are the differentiating features that make adult sites unique?
We work very hard to give each brand some uniqueness at different
levels; content library, UX and features sets, and across a lot of
different algorithms.
Before applying and interviewing for your current employer, what were your thoughts on potentially working on adult sites? Did you have any hesitations? If so, how were your fears to put rest?
It never really bothered me, in the end the challenge was so
appealing. The idea of millions of people potentially interacting with
features I worked on was really motivating. That proved to be true very
quickly, the first time something I worked on went live, I was super
proud, and I indeed told all my friends to go check it out! The fact
that porn will never die is reassuring for job stability as well!
In as far as end product, sharing that you work on adult
sites may not be the same as working at a local web agency. Is there a
stigma attached to telling friends, family, and acquaintances you work
on adult sites? Is there any hesitance in telling people you work on
adult sites?
I’m very proud to work on these products, those close to me are aware
and fascinated by it. It’s always an amazing source of conversation,
jokes and is genuinely interesting.
Having worked at agencies outside the adult industry, is there a difference in atmosphere when working on adult sites?
The atmosphere here is very relaxed and friendly. I don’t notice any
major differences with respect to work culture at other agencies, other
than the fact that it’s much bigger here than anywhere I have worked
previously.
Being a front-end developer, which teams do you work most closely with? What are the most common daily communication methods?
We work equally with backend developers, QA testers and product
managers – most of the time we simply go up to each other’s desk and
talk. If not, chat (MS Teams) is very common. Then come emails.
Lastly, is there anything you’d like to share as a front-end developer working on adult sites?
It’s really exciting being a part of creating how users experience
such a widely used product. We are generally at the forefront of trends
and big changes in tech as they roll out, which keeps it fun and
challenging.
Interview end
I found our interview really enlightening. I was a bit surprised they
didn’t use images while developing features and designs. It’s exciting
to see that Pornhub continues to push the bleeding edge of the web with
WebXR, WebRTC, and Intersection Observer. I was also happy to see that
they consider the current set of web APIs sufficient to start dropping
jQuery.
I really wish I’d have been able to get more specific tech tips out
of them; performance and clever hacks especially. I’m sure there’s a
wealth of knowledge to be learned behind their source code! What
questions would you have asked?
PHP Spellchecker is a library providing a way to spellcheck multiple sources of text by many spellcheckers. The library provides an abstraction layer with a unified interface for various spellcheckers with support for the following out of the box:
Here’s a quick example from the documentation using the Aspell spellchecker:
<?php
use PhpSpellcheck\SpellChecker\Aspell;
// if you made the default aspell installation on you local machine
$aspell = Aspell::create();
$misspellings = $aspell->check('mispell', ['en_US'], ['from_example']);
foreach ($misspellings as $misspelling) {
$misspelling->getWord(); // 'mispell'
$misspelling->getLineNumber(); // '1'
$misspelling->getOffset(); // '0'
$misspelling->getSuggestions(); // ['misspell', ...]
$misspelling->getContext(); // ['from_example']
}
Here’s an example from the documentation for checking spelling in a file:
The modern internet has become obsessed with tracking, analytics, and targeted advertising. Almost all of your browsing activity is tracked: sometimes by your network provider, and frequently by the hosts of the websites you visit (and anyone they choose to share data with). If you host a website—and many of us do—chances are good you’re running analytics software on it, collecting metadata about your users’ devices and browsing activity.
You may not even know it, but some of your users are likely ghosts: running tracker-blocking software that blocks analytics scripts before they load. Unless you’re also running analytics on your server-side logs, these users will be silently absent from your stats. I can’t say I blame them; the tracking epidemic has gotten out of control and is still spreading like wildfire. However, by opting out of tracking, these users may unwittingly have a degraded experience on your website when third-party scripts your code depends on fail to load.
You can choose to leave these ghost users to suffer the consequences, or you can take a few simple precautions to ensure everyone has a good experience using your website, even when your third-party services don’t load. As a bonus, following these steps will harden your website, make it resilient to downtime you have no control over, and make it more easily accessible to a wider range of people. It may even improve your SEO, since search index crawlers that ignore JavaScript will predictably experience the same fallback mechanisms as users with blocker software.
Keep third-party scripts to a minimum
The easiest thing you can do is avoid loading third-party resources (anything not hosted on your primary domain) as much as possible. In addition to introducing security and privacy concerns, they can be a huge drag on your site performance, and can be unpredictable: they can easily change without you knowing, which is scary for something that has direct access to your site.
Limiting your exposure to third-party resources might mean hosting JavaScript libraries on your own site instead of a CDN, making your own social network “share” buttons using self-hosted images, or just using fewer third-party libraries. In addition to improving your users’ security and privacy, limiting your third-party scripts will almost certainly improve your site performance—often drastically. JavaScript downloading and parsing occupies a huge chunk of the loading time on most websites.
If you’re unable to host your scripts locally, use async or defer to speed up the time until a user can interact with your website. Keep in mind that deferring script loads means that regular users may interact with your site before a script is loaded; it’s a good idea to ensure your website still works without those resources.
Test your site with JavaScript disabled
Most modern internet browsers still provide an option to browse with JavaScript disabled—it’s rare, but some users do it. Furthermore, any third-party scripts you’re still loading have the potential to fail. Imagine what would happen if you relied on a CDN for your core JavaScript libraries, and the CDN went down: this is the same experience many ghost users will have the first time they visit. Checking your website with JavaScript disabled will give you firsthand experience with failure scenarios, so you’ll be able to implement backup solutions.
Display messages when scripts don’t load
Sometimes you can’t avoid using third-party resources, often in
mission-critical features like checkout. In these cases, showing
messages to your users when required scripts don’t load will ensure your
site never feels “broken”.
You can use noscript tags
to display messages to anyone with JavaScript completely disabled, but
that won’t help ghost users who are only blocking third-party requests,
or services experiencing downtime. I highly recommend adding code in
critical processes to verify that all required scripts have loaded and,
if they haven’t, display messages explaining what happened.
The Electronic Frontier Foundation’s donation page is a great example of this technique in action: when Stripe checkout fails, they show a helpful message explaining what to allow in order to fix it:
Use descriptive image alt text
When an image fails to load, most browsers display the content of the alt attribute in its place. Adding descriptive alt
text to all of your images will let ghost users immediately understand
your content, and as a bonus, improve accessibility for anyone using a
screen reader—the alt text will be read aloud in place of images.
When
it comes to descriptions of images, detail is critical. Consider the
difference between a caption that says “bowl of soup”, and this descriptive example from Vox Media:
If your site relies on ad revenue, host acceptable ads locally
Many users running blockers do so for personal security reasons; they’re uncomfortable with widespread data collection and the pervasiveness of malvertising, which is only able to exist because overreaching ad networks want to serve increasingly targeted ads.
If your site relies on ad revenue, strive to host text-based ads or static images on your first-party domain. These ads will avoid ending up on filter lists designed to block malicious actors, allowing you to reach more of your user base. Even better, the rest of your users who aren’t running blockers will enjoy a more secure and private experience on your site.
Help create the internet you want to use
Implementing these techniques will improve the resiliency of your
site across the board, and harden it against errors and unexpected
downtime. Mobile users in particular—said to make up the majority of all
internet traffic—will appreciate faster load times, less data usage,
and predictable content placement (without slow-loading ads appearing
suddenly). All of your users (including you!) will enjoy better
performance and privacy while using your site.
If we want a web that cares about privacy, it’s our responsibility as website creators to exemplify it.
Can you believe it’s been 30 years since the birth of the internet as
we know it? Considering we’re a web hosting company and our entire
business is reliant on the internet (aren’t all companies nearly reliant
on the internet these days?), we’re feeling a little nostalgic.
So let’s cheers to the internet as we know it and all the geniuses who make the world wide web spin! Here’s a look back at the pioneers.
Speaking of pioneers…
Wait. Who is Tim Berbers-Lee? Tim Berners-Lee
is the guy we owe “it all” to. He is the inventor of the World Wide Web
and is still the director of the World Wide Web Consortium, commonly
known as the W3C. The W3C is like the governing body of the internet,
and is responsible for setting the standards for the web such as coding
languages, best practices, operating guidelines, and helpful tools.
So of course, you’re going to see his name several times in our history of the internet below, starting with pre-Y2k.
So of course, you’re going to see his name several times in our history of the internet below, starting with pre-Y2k.
Imagine if the Y2K bug really did bring down the house…
Thankfully, the crisis was averted and we have 20 more years of internet awesomeness to talk about!
Thankfully, the crisis was averted and we have 20 more years of internet awesomeness to talk about!
What’s missing?
So, do you have a favorite “internet history” moment that is missing from the list?
Or, what new internet craze do you have up your sleeve for the next
20 years? You could be a pioneer just like Tim Berners-Lee. Just get
your ideas online and out for the wonderful world wide web to see!
If you’re testing form validation using Laravel Dusk, you’ve probably
hit a scenario where the form submission is blocked by Chrome before
it’s sent to the server because of HTML5 form validation.
HTML5 form validation blocks a submission when you add an attribute such as required to an input element, or you use type="email". In your Laravel Dusk tests, you’ll probably see this manifesting as a client-side popup dialog in your failing test screenshots.
This is a really tricky thing to test. Since it happens completely
client-side without modifying the DOM, it’s hard to assert that the
error appears. Even if you do work out a hacky way to do it, it’s not
actually testing that your web application’s form validation is working.
You’re essentially just testing that Chrome supports HTML5 form
validation, and I’m sure the Google/Chromium teams have their own tests
for that. 🙂
Your first thought may be to try to disable HTML5 form validation using ChromeOptions in DuskTestCase. Unfortunately there is no such option. That really only leaves one way: adding the novalidate
property to your HTML forms. This attribute, when applied to a HTML
form, disables the browser’s native form validation. But this has its
own drawback in that it disables a perfectly useful feature that
probably provides value to your users.
Thankfully, Dusk allows you to inject JavaScript onto the page at runtime! Using this feature, we can dynamically inject a small code snippet that iterates over the forms on the page and adds the novalidate attribute automatically, just for your tests. By adding this browser macro to DuskTestCase:
Thankfully, Dusk allows you to inject JavaScript onto the page at runtime! Using this feature, we can dynamically inject a small code snippet that iterates over the forms on the page and adds the novalidate attribute automatically, just for your tests. By adding this browser macro to DuskTestCase:
public static function prepare()
{
static::startChromeDriver();
Browser::macro('disableClientSideValidation', function () {
$this->script('for(var f=document.forms,i=f.length;i--;)f[i].setAttribute("novalidate",i)');
return $this;
});
}
you can then call it within your tests like so:
$this->browse(function (Browser $browser) {
$browser->visit('/register')
->disableClientSideValidation()
->type('email', 'notvalidemail')
->click('@submit')
->assertPathIs('/register')
->assertSee('The email must be a valid email address.');
});
And viola! The result is you’re actually testing your application’s form validation, and you don’t have to give up HTML5 form validation to do it.
The laravel-kustomizer package is a customizable feedback widget for your Laravel applications. It allows you to implement a customer feedback component on your website using Vue.js, but you can apply it in any frontend tool of your choice.
If you want to use the JavaScript and UI that ships with this package, include them in your layout:
<head>
<script src="{{ asset('vendor/kustomer/js/kustomer.js') }}" defer></script>
</head>
<body>
@include('kustomer::kustomer')
</body>
The #kustomer container element needs to live outside your app’s Vue.js container. You can also package the JS and CSS files to customize the widget heavily.
If you’re using Nova, you can use the nova-kustomer tool to implement Laravel Kustomizer into your dashboard:
You can learn more about this package, get full installation instructions, and view the source code on GitHub at mydnic/laravel-kustomer.
JavaScript is still the most popular language for the last six years, and it continues to develop according to Stack Overflow 2018 report. The evolution of its frameworks, libraries, and designs for the past years proved that it has lots to offer in the market. No wonder it’s developer’s top pick language for it provides a whole new experience of flexibility, challenge, and power.
In Coding Dojo bootcamp, we teach not only Javascript, but we offer five of the Most In-Demand Programming Languages of 2019 ranked in TIOBE Index. Our learning platform equips developers with the most sought-after tech skills and helps them stand out on the job market.