.NET Framework January 2022 Cumulative Update Preview

Today, we are releasing the January 2022 Cumulative Update Preview for .NET Framework.

Quality and Reliability

This release contains the following quality and reliability improvements.

CLR1

Addresses rare crashes and hangs that can appear in cases where a GC occurs while another thread is in the middle of certain special paths used to invoke shared-generic code from non-shared-generic contexts.

WPF2

Addresses a hang when scrolling a list control where both these conditions are

UseLayoutRounding is enabled, and
The item margin is not a multiple of the rounding quantum. (The quantum is a function of the DPI scaling in effect.)

Addresses an exception “Height must be non-negative” that can occur when adding items or groups to the collection displayed by an ItemsControl.
Addresses an issue where a shared ContextMenu stops displaying after it fails to display once because its owner was removed from the visual tree.

1 Common Language Runtime (CLR)
2 Windows Presentation Foundation (WPF)

Getting the Update

The Cumulative Update Preview is available via Windows Update, Windows Server Update Services, and Microsoft Update Catalog.

Microsoft Update Catalog

You can get the update via the Microsoft Update Catalog. For Windows 10, NET Framework 4.8 updates are available via Windows Update, Windows Server Update Services, Microsoft Update Catalog. Updates for other versions of .NET Framework are part of the Windows 10 Monthly Cumulative Update.

**Note**: Customers that rely on Windows Update and Windows Server Update Services will automatically receive the .NET Framework version-specific updates. Advanced system administrators can also take use of the below direct Microsoft Update Catalog download links to .NET Framework-specific updates. Before applying these updates, please ensure that you carefully review the .NET Framework version applicability, to ensure that you only install updates on systems where they apply.

The following table is for Windows 10 and Windows Server 2016+ versions.

Product Version
Cumulative Update

Windows 11

.NET Framework 3.5, 4.8
Catalog
5009469

Microsoft server operating systems version 21H2

.NET Framework 3.5, 4.8
Catalog
5009470

Windows 10, version 21H2

.NET Framework 3.5, 4.8
Catalog
5009467

Windows 10, version 21H1

.NET Framework 3.5, 4.8
Catalog
5009467

Windows 10, version 20H2 and Windows Server, version 20H2

.NET Framework 3.5, 4.8
Catalog
5009467

Windows 10 1809 (October 2018 Update) and Windows Server 2019

5009823

.NET Framework 3.5, 4.7.2
Catalog
5009472

.NET Framework 3.5, 4.8
Catalog
5009468

 

Previous Monthly Rollups

The last few .NET Framework Monthly updates are listed below for your convenience:

.NET Framework January 2021 Cumulative Update
.NET Framework November 2021 Cumulative Update
.NET Framework October 2021 Security and Quality Rollup

The post .NET Framework January 2022 Cumulative Update Preview appeared first on .NET Blog.

Bootstrap Table Guide and Best Bootstrap Table Examples

Tables and data visualization
Tables in modern Web Development
What is a bootstrap table? A basic example of Bootstrap table
Bootstrap Table Classes

Types of bootstrap tables
Striped rows and dark table
Bordered and borderless bootstrap table
Contextual bootstrap table classes
Table heads color
Hoverable rows
Small bootstrap table
Responsive bootstrap tables
Bootstrap table with images

Common questions about bootstrap tables
How to style a bootstrap table?
What is table responsive in bootstrap?
How do I add a border to a bootstrap table?
How do I center the text bootstrap table?
How do I make a scrollable table in bootstrap?

Best Bootstrap Table Examples
Conclusion

Tables and data visualization

Tables are so widespread and trivial it’s easy to take them for granted. Meanwhile, the value of a table or spreadsheet for big data is like that of an assembly line for heavy industry. Before we dive into our Bootstrap table examples, let’s take a moment to realize what an achievement we have at our disposal. When an aspiring business analyst or data scientist learns his or her craft, a good part of the learning process is dedicated to graphics. The demand for a mixture of hard data and fine art isn’t accidental. With technical progress, the data we work with gets more complex. As data gets more complex, understanding it becomes harder.

Ancient maps show the world known to mankind at the time and the importance of visualizing information

Data visualization is an ancient art. You may have heard of the term “Ptolemy’s Map”. That is the name commonly given to all geographical knowledge contained in the works of Claudius Ptolemy, not to be confused with Egyptian pharaohs. Claudius Ptolemy was a mathematician, an astronomer, a geographer, and a musical theorist (apparently, it was a thing back then). He lived in Alexandria in the second century A.D. and almost certainly never visited most places found in his maps. Still, his maps and descriptions give a fair representation of what lay beyond the horizon. Sure, the proportions were distorted and the distances inaccurate, but the man died almost 1,800 years before the launch of the first satellite. Let us give him some credit! Maps existed back then, and they were tools, not curiosities. Even when the world’s largest library contained less data than an average smartphone does today, it was obvious how helpful it is to represent information in a simplified visual way. Hence the modern popularity of infographics and diagrams.

Tables in modern Web Development

Tables are an important part of any web application’s life. Tables help both visualize and structure data. Instead of reading each entry’s full parameters, its location in the table gives us some insight. They help us absorb large amounts of data with relative ease. We can say that tables are the foundation of a modern web application. Therefore, it is very important to make them carefully and with love. After we’ve reviewed the best javascript table plugins, we decided to create a digest of the best tables out there, categorized by one technology. Here it is: today we will talk about Bootstrap tables.

Bootstrap table is good for creating date pickers, admin panels, calendars, and all other stuff to show complex data.

In this article, you will learn what a bootstrap table is, how to make basic bootstrap tables and how to make them beautiful. You will also learn how to customize bootstrap tables. After that, we will list the best examples of ready-made bootstrap tables.

What is a bootstrap table? A basic example of Bootstrap table

Bootstrap tables are well-organized components for displaying data. The data is presented in the form of columns and tables. Bootstrap tables are opt-in. To build it, you just need to add .table class to any <table> and then style it.

The code example of the basic Bootstrap table looks like this:

<table class=”table”>
<thead>
<tr>
<th scope=”col”>#</th>
<th scope=”col”>Name</th>
<th scope=”col”>Surname</th>
<th scope=”col”>Username</th>
</tr>
</thead>
<tbody>
<tr>
<th scope=”row”>1</th>
<td>Eugene</td>
<td>Stepnov</td>
<td>@e93</td>
</tr>
<tr>
<th scope=”row”>2</th>
<td>Mark</td>
<td>Dever</td>
<td>@md111</td>
</tr>
<tr>
<th scope=”row”>3</th>
<td>John</td>
<td>Piper</td>
<td>@piper</td>
</tr>
</tbody>
</table>

Bootstrap Table Classes

The basic principle when developing a bootstrap table is classes. You don’t need to write cumbersome CSS to style and customize your table. Just add classes to the <table> tag describing how the table will behave. For example, here are the most popular classes:

Border: Add a border with .table bordered;

Colors: Add color to different rows with .table striped;

Condense: Make your rows more compact with .table-condensed;

Hover: Highlight a table sortable line when you hover with .table-hover.

Next, we’ll look at how to put these classes into practice.

Types of bootstrap table

Now let’s take a look at different basic manipulations with Bootstrap table.

Striped rows and dark table

For creating a striped row table you just need to add .table-striped to any table row within the <tbody>. You can also add the table dark class to make the table dark and invert the colors.

<table class=”table table-dark table-striped”>
<thead>
<tr>
<th scope=”col”>#</th>
<th scope=”col”>Name</th>
<th scope=”col”>Surname</th>
<th scope=”col”>Username</th>
</tr>
</thead>
<tbody>
<tr>
<th scope=”row”>1</th>
<td>Eugene</td>
<td>Stepnov</td>
<td>@e93</td>
</tr>
<tr>
<th scope=”row”>2</th>
<td>Mark</td>
<td>Dever</td>
<td>@md111</td>
</tr>
<tr>
<th scope=”row”>3</th>
<td>John</td>
<td>Piper</td>
<td>@piper</td>
</tr>
</tbody>
</table>

Bordered and borderless bootstrap table

To add borders to a table, use the .table-bordered class. In this case, the table tag will look like this

<table class=”table table-bordered”>

</table>

For the borderless table, you should use:

<table class=”table table-borderless”>

</table>

Contextual bootstrap table classes

You can also use contextual classes to colorize individual lines or cells. It’s also worth mentioning that you can use several different classes at the same time to build a wide variety of tables.

To make a colorized table, you can apply the following classes to <tr> elements (rows) or <td> elements (individual cells):

.Table-primary
.Table-secondary
.Table-success
.Table-danger
.Table-warning
.Table-info
.Table-light
.Table-dark

In our example below, we have made a small table with a hover, using 3 context classes to colorize individual lines.

<table class=”table table-sm table-hover”>
<thead>
<tr>
<th scope=”col”>#</th>
<th scope=”col”>Name</th>
<th scope=”col”>Surname</th>
<th scope=”col”>Username</th>
</tr>
</thead>
<tbody>
<tr class=”table-danger”>
<th scope=”row”>1</th>
<td>Eugene</td>
<td>Stepnov</td>
<td>@e93</td>
</tr>
<tr class=”table-success”>
<th scope=”row”>2</th>
<td>Mark</td>
<td>Dever</td>
<td>@md111</td>
</tr>
<tr class=”table-warning”>
<th scope=”row”>3</th>
<td>John</td>
<td>Piper</td>
<td>@piper</td>
</tr>
</tbody>
</table>

Bootstrap table heads color

You can also specify different background colors for the table head using the modifier classes .thead-light or .thead-dark on the <thead> element.

The following example uses the class .thead-light to create a table with a light head.

<table class=”table table-dark table-striped”>
<thead class=”thread-light”>
<tr>

</tr>
</table>

Likewise, you can use the class .thead-dark to create a table with a dark head.

<table class=”table table-dark table-striped”>
<thead class=”thread-dark”>
<tr>

</tr>
</table>

Hoverable rows

Sometimes you need to highlight some rows of a table. Then we need to use :hover. In bootstrap, you don’t need to modify anything in the CSS file: just add the .table-hover class to the <table> tag

<table> tag

<table class=”table table-hover”>

</table>

Small bootstrap table

If you want to develop a small compact table, just add class .table-sm.

<table class=”table table-sm”>

<table/>

Responsive bootstrap table

One thing you simply need to know about is responsive bootstrap tables. To make any table responsive, wrap the <table> tag in a <div> with the class .table-responsive. Or you can specify the maximum breakpoint at which this table property will appear by adding the class .table-responsive {-sm | -md | -lg | -xl}. Look at an example below.

<div class=”table-responsive”>
<table class=”table”>

</table>
</div>

Bootstrap table with images

Adding images to a table, make sure you specify a max-width for the parent cell. You can use the sizing utilities or write your own CSS. By default, the content in a table cell is vertically aligned to the top.

<table class=”table table-image”>
<thead>
<tr>
<th scope=”col”>Number</th>
<th scope=”col”>Avatar</th>
<th scope=”col”>First Name</th>
<th scope=”col”>Last Name</th>
<th scope=”col”>Username</th>
<th scope=”col”>Social Link</th>
</tr>
</thead>
<tbody>
<tr>
<th scope=”row”>1</th>
<td class=”w-25″>
<img src=”https://s7d9.scene7.com/is/image/LifeWayChristianResources/piper_john_author?wid=300&hei=300&op_usm=2,.5,6,0″ alt=”John Piper”>
</td>
<td>John</td>
<td>Piper</td>
<td>@johnpiper</td>
<td>twitter</td>
</tr>
<tr>
<th scope=”row”>2</th>
<td class=”w-25″>
<img src=”https://www.capitolhillbaptist.org/monkimage.php?mediaDirectory=mediafiles&mediaId=3241749&fileName=mark-dever-2-300-300-0-0.jpg” class=”img-fluid img-thumbnail” alt=”Mark Dever”>
</td>
<td>Mark</td>
<td>Dever</td>
<td>@markdever</td>
<td>twitter</td>
</tr>
</tbody>
</table>

Common questions about bootstrap table

How to style a bootstrap table?

To style the bootstrap table, add various classes to the <table>, <th>, <tr> tags. For example, the .table-sm class will make your table compact. For more details refer to the official bootstrap documentation.

What is table responsive in bootstrap?

Table responsive allows any table to scroll horizontally. To make any table responsive just add .table-responsive class to <table> tag.

How do I add a border to a bootstrap table?

To add borders to the table, use the .table-bordered class on the <table> tag

How do I center the text bootstrap table?

The easiest way to center text in the bootstrap table is to add .text-center class in the <table> tag.

How do I make a scrollable table in bootstrap?

Use a responsive table to add scroll. Just add .table-responsive class to a <table> tag.

Best Bootstrap Table Examples

Bootstrap table

The bootstrap table is a plugin for integration with the most popular CSS frameworks. It is an extended version of the table that integrates with many CSS frameworks. It supports Material Design, Bootstrap, Bulma, Semantic UI, and Foundation. You can install it with npm or yarn by using the Bootstrap Table source JavaScript files and CSS.

One of the most important things about this plugin is that you make the table fully responsive in a very short time. The plugin is maintained by thousands of contributors and it has thousands of commits. The other good thing is that this library has great documentation with many live examples with source code on how to use this plugin. For instance, there are examples of a Modal table, different use of buttons, how to add search, merge or update cells, and other features that can extend your bootstrap table.

Notable features:

responsive web design;
scrollable table with fixed headers;
fully configurable via data attributes;
get data in JSON format using AJAX;
simple column sorting with a click;
powerful pagination and localization.

Bootstrap tables in Light Blue Bootstrap Admin Template

Light Blue HTML5 Admin Template is a product developed by Flatlogic, made in dark and transparent colors. The template is made on the basis of Bootstrap 4 and is fully responsive. In addition to tables, you will find many other components in this template such as buttons, icons, dashboards and others.

As for tables, in this template they are subdivided into Tables Basic and Tables Dynamic.

In Tables Basic you will find static bootstrap tables with the following features:

Tables with buttons;
Tables with images;
Striped and bordered tables;
Hover and overflow tables;
Tables with checkboxes.

In Tables Dynamic section you will find the following features:

Sortable tables;
Working search console;
Tables made on top of Backgrid.js;
Tables made on top of jQuery DataTables.

As a result, using this template, you get not only different types of well-designed bootstrap tables, but also a well-thought-out admin panel for a full-fledged web application with different components.

MDbootstrap bootstrap table generator

This tool allows you to quickly generate a bootstrap table to see how it will look, and copy the resulting code. The tool can create tables using the following combinations of bootstrap classes:

Striped
Hoverable
Bordered
Borderless
Small
Responsive
Captions

Also, in addition to this, you can choose the color of cells and borders. This tool will be very helpful if you want to test different table styles.

Fixed Column Bootstrap Table by Colorlib

The table is well suited for displaying huge data arrays since it’s not always possible to remember which cell corresponds to which one. This is why the first column is fixed while you scroll horizontally. It is fully customizable, allowing you to use any color you choose, or create a responsive table and add rows if necessary.

It uses Bootstrap and Fontawesome. The scroll is implemented with jQuery.

The product is completely free. To download and run it, you will need to leave your email on the site.

Bootstrap 4 static table with checkboxes and fixed header

Fixed header and checkboxes tables are featured in one of the largest bootstrap communities. The table has very accurate design and good user experience. The table uses Bootstrap 4 and Jquery. This snippet is free and open-source – you can use it in your project. The project has integration with FontAwesome and includes more than 1000+ images.

Creative Tim bootstrap table

This Bootstrap table is based on the bootstrap table plugin. The project is completely free and open-source, nevertheless it has wide functionality. You can set background color (5 colors), the background of the table can be created from scratch, or you can leave only the header. Also, the table can run either in full screen mode or compact. This table has all the functionality of bootstrap – table plugin.

Bootstrapious Pricing table

Fixed header bootstrap table template

Fixed Header Bootstrap Table Template has – guess what – a fixed header that gives you the ability to scroll vertically. The table has rounded corners, and it is also possible to change table color and use different color combinations. There is no column border in the variants, which allows you to add as much content as you like without getting cut off. The columns simply adjust themselves to keep the table looking impressive.

Sortable

This small bootstrap table has important functionality, namely the ability to sort the various columns of the table. This function is done with a little bit of jQuery code:

$(function(){
$(‘#keywords’).tablesorter();
});

Fade and Blur on Hover Data Table

This table has a strict corporate design that can be suitable for large, serious applications. Of course, you can change the color configuration settings and choose your theme from unlimited custom combinations that will deliver the right look for your table.

However, the main feature of this table is this: when you hover over a row, it will be highlighted by fading out the others. This will allow your users to focus better and clearly see what they are reading.

Fixed column datatable

In this template you will find 6 different example tables. This is a plugin written in Vue and Bootstrap. By using this template you get a data table with checkboxes, a data table with accordion, and data tables with different column alignment. The code script for all six designs is shared as a single code file. The template is fully customizable and responsive.

Bootstrap datagrid

Bootstrap datagrid is a jQuery datagrid plugin compatible with Bootstrap 2 and 3. It is completely free and open source, available under MIT license. The disadvantage of this tool is no Bootstrap 4 support. The plugin is completely responsive and fully configurable. The features of the plugin include sorting, filtering, change columns order, show or hide columns, single or multiple row selection, filters, localization, pagination, and more. As a bonus, Bootstrap datagrid has neat documentation.

React bootstrap table

A very useful tool indeed: react and bootstrap are the two most popular front end libraries. React bootstrap table allows you to create bootstrap style tables inside the React application. It works with Bootstrap 3 and 4. The installation, configuration and usage are very intuitive.

React bootstrap table supports following built-in features:

Striped, borderless, condensed table;
Column align, hidden, width, sort, title, styling, customization;
Table scrolling;
Cell format;
Pagination;
Row selection;
Table Search, Column filter;
Cell editor;
Insert & delete Row;
Export to CSV;
Rich function hooks;
Header column span;
Remote mode;
Row expand;
Keyboard navigation.

Footable

FooTable is a responsive plugin built for Bootstrap. The table is free to download and fully responsive. The features of this table include searching within the table, searching by category, pagination, sorting in individual columns and tag indicating the number of entries. The table displays 10 entries at a time, which can be changed according to your needs.

Js grid

jsGrid is a jQuery plugin you can add to your Bootstrap site. The plugin has a lot of basic features for tables such as sorting, searching, pagination, scrolling the entries, etc. Additional features of the table include data editing, validation, filtering, etc.

The plugin has very good documentation. Despite the fact it is written in jquery, there are still periodic updates.

Conclusion

In this article, we introduced you to the concept of Bootstrap table, as well as basic manipulations with it and various ready-made templates as a bonus.

When you create your table, we recommend you to think of what information will be the most important in it, and only then decide which features and elements to use. You can also choose bootstrap tables with more advanced options, including search, pagination, or sort features.

As for your ready-made examples of bootstrap tables, the best tables are the ones you customize yourself: because you know best what will suit your website and your vision.

If you want to somehow improve and comment on this article, we’ll be very happy to hear from you. You can also find many examples of bootstrap tables by looking at our bootstrap templates.

You might also like these articles

12+ React Boilerplates & Starter Kits for Developers in 2021

Top 24 Free Essential Plugins to Extend Bootstrap

6 Reasons to Use ReactJS for Web Development

The post Bootstrap Table Guide and Best Bootstrap Table Examples appeared first on Flatlogic Blog.

Functional Components vs. Class Components in React.js

The history of React.js components
Functional components in React
Class components in React.js
The difference between functional and class components
Bonus: Building an App with Flatlogic Platform

When you start to code with React you may get confused by some things in React, like JSX syntax or the difference between functional and class components. JSX is an interesting syntax extension to JavaScript that was developed to make the process of writing the UI elements more comfortable. The development with React doesn’t require using JSX, just like our article is not about it either. We are going to discuss Functional vs Class components. Let’s start.

The history of React.js components

We should jump into the history of React first to understand how React components evolved. React, created by Facebook software engineer Jordan Walke, is an open-source front-end JS library for building interactive user interfaces. The first release was in 2013, with 0.3.0 version. React has got further development and updated several times every year. The React team added more and more new features to the library to give developers more tools for coding. Among the most famous and loved features are the virtual DOM, one-way data-binding, JSX, reusable components, declarative programming, stable code, fast rendering of UI elements, great performance optimization opportunities. The current version at the time of writing this article is 17.0.1.

Along with all these benefits React offered it also gave developers two types of components they could use to create UI components. It can be supposed that both types of components provide the same opportunities for writing UI elements, and the choice depends only on the developer’s preferences. Well, it wasn’t true. The real situation was that class components were the only viable option to develop complex apps with React. The reason was that using class components you get a large number of capabilities, for example, state, while functional components didn’t provide such an option. However, the situation changed when React v.16.8 was released in 2019. A new version contained an update that was meant to take the development with functional components to the next level. React offered Hooks for functional components. The introduction of Hooks made it possible to write the entire complex application using only functions as React components. This is a deeply significant event that changed the way of React apps development. Keeping that in mind, we are going back to the present time and find out what is happening now and what functional and class components are.

Functional components in React

Functional components in React are just JavaScript functions like this:

function Foo(props) {
return <h1>Who is living young, wild, and free? – {props.name}</h1>;
}
const element = <Foo name=”Me!” />;
ReactDOM.render(element, document.getElementById(‘home’));

In our case, we render an element that represents the user-defined component called Foo. The element passes JSX attribute name=” Me” as a prop to our function component Foo, which returns a <h1>Who is living young, wild, and free? – Me!</h1> element as the result.

Props are inputs for both types of components. One of the main tasks of props is to pass information from component to component. It’s especially necessary if you want to build a dynamic user interface. However, there is one important rule that you shouldn’t forget: props are read-only. That means that all React components shouldn’t change their inputs and the same props must return the same result. Components that respect their props are called “pure”. That rule works both for class and function components. 

JSX is a special extension that allows us to place HTML elements right inside JavaScript code without using additional methods like createElement(). All your HTML tags will be converted into React elements after compilation. JSX may be convenient, however, it is an optional instrument for development. To see how the same blocks of code look like with/without using JSX try the online Babel compiler

Another way of writing function components is by using an arrow function.

An example of an arrow function:

const App = () => { //that is an arrow function
const greeting = ‘Hello Function Component!’;

return <Headline value={greeting} />;
};

const Headline = ({ value }) =>
<h1>{value}</h1>;

export default App;

Arrow functions have some benefits: 

The code written with arrow functions looks compact. Functions are easier to write and read. One of the reasons is an implicit return by simply omitting the curly braces (see video with an example).
Arrow syntax doesn’t contain its context and automatically bind this to the surrounding code’s context 

But since arrow functions give one more way to write code (along with standard functions and classes) you need to set rules when we use any of them. As an example you can stick to the following rules:

If you work with global scope and Object.prototype properties use function.
If you work with object constructors use class.
If you face any other situation use arrow function.

The examples above are called stateless function components because they just take props as an argument and return a react element. They don’t manage state and don’t have a lifecycle, while class components do. However, you can use Hooks with them that allow you to work with state and lifecycle and add even more features. We will speak about that in the comparison below.

Class components in React.js

Let’s start with an example:

class Foo extends React.Component {
render() {
return <h1>Who is living young, wild, and free? – {this.props.name}</h1>;
}
}

It is a regular ES6 class that extends the component class from the react library. To return HTML you have to use render() method in it. 

Class components work fine with props as well as functional components do. To pass the props to a component you can use a syntax similar to HTML attributes. In our sample case we need to replace props.name with this.props.name in the render() body to use props. 

Additional benefits class components offer by default are state and lifecycle. That is why class components are also known as “stateful” components. 

The state of a component is an observable object that holds some information and controls the behavior of the component. The difference between props and state is that props don’t change over time during the lifetime of a component. The state holds the data that can be changed over time and changes the component rendering as a result.

The state of a component is supposed to have the initial this.state that can be assigned with a class constructor. The class constructor is a special JavaScript method that allows to bind event handlers to the component or to initialize the local state of the component. 

If you don’t need to handle any of both cases above the implementation of a constructor is unnecessary. Example of a constructor:

constructor(props) {
super(props);
this.state = {};
}

Constructor() function inside a React component requires super(props) before any other statement. Super(props) is a reference to parents constructor() functionthat React.Component base class has. When we define a new constructor() inside a class component, we replace the base constructor() function. However, it has some code inside of it we still need. So to get access to that code we call super(props) – that is why we have to add super(props) every time we define a constructor() inside a class component. The constructor() is called before the React component is mounted. To use state in a class component we must define the initial state of it in the constructor. Instead of calling setState(), we need to assign the initial state with this.state command in the constructor. It’s the only case when we are allowed to change the state directly by assigning its value, otherwise use setState() instead. Constructor() has other rules you should be aware of, you can read about them on the link

Differentiating Functional vs Class components

1.State and lifecycle

Well, the standard answer to the question about the difference between functional and class components was that class components provide developers with such features as setState() and lifecycle methods componentDidMount(), componentWillUnmoun(), etc., while functional components don’t. That was true because functional components are plain JavaScript functions that accept props and return React elements, while class components are JavaScript classes that extend React.Component which has a render method. Both state and lifecycle methods come from React.Component, so they were available only for class components. The widespread advice was something like that: “Go with functional if your component doesn’t do much more than take in some props and render”. You had no options on how to build complex UI and class components dominated in React development for a while.

However, that has changed with the introduction of Hooks. To replace setState method to work with the state in class components React offers useState Hook.

To work with components lifecycle classes have such methods like componentDidMount, componentWillUnmount, componentWillUpdate, componentDidUpdate, shouldComponentUpdate. Functional components have got a tool to work with the same methods using only one Hook useEffect. You can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. 

Standard class methods work well but do look not very elegant. Functional components offer an elegant and simple decision: instead of using multiple lifecycle methods, we can replace them with one Hook useEffect. What React developers write about Hooks:

“Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate, getDerivedStateFromError and componentDidCatch lifecycles yet, but we plan to add them soon. It is an early time for Hooks, and some third-party libraries might not be compatible with Hooks at the moment.”

an official React documentation

So Hooks are more addition to functional components rather than a replacement of class components.

2. Syntax

The obvious difference is the syntax. Let’s examine several examples.

How we declare components.

Functional components are JavaScript functions:

function FunctionalComponent() {
return <h1>Hello, world</h1>;
}

Class components are classes that extend React.Component:

class ClassComponent extends React.Component {
render() {
return <h1>Hello, world</h1>;
}
}

To return our h1 we need the render() method inside a class component. 

The way we pass props.

Let’s say we have props with the name “First”.

<Component name = “First” />

Working with functional components, we pass the props as an argument of our function using the construction “props.name”. 

function FunctionalComponent(props) {
return <h1>Hello, {props.name}</h1>;
}

With class components, we need to add this. to refer to props.

class ClassComponent extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}

Handling state.

To handle state functional components in React offer useState()Hook. We assign the initial state of count equal to 0 and set the method setCount() that increases it by one every time we click a button. The component returns the number of times we clicked the button and the button itself. The initial state is used only during the first render. The type of argument can be a number, string, object, or null. To learn more about that useState() Hook see the official documentation.  

const FunctionalComponent = () => {
const [count, setCount] = React.useState(0);
return (
<div>
<p>count: {count}</p>
<button onClick={() => setCount(count + 1)}>Click</button>
</div>
);
};

Class components work a bit differently. They use setState() function, require a constructor, and this keyword. 

class ClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

render() {
return (
<div>
<p>count: {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click
</button>
</div>
);
}
}

The underlying logic is similar to the logic in functional components. In constructor() we declare a state object, state key “count” and the initial value equal to 0. In render() method we use setState() function to update the value of our count using this.state.count and the app renders the number of times the button was clicked and displays the button itself. The result is the same, but the same functionality requires more lines of code for class components. However, it doesn’t mean that the code written with class components will be more cumbersome than the code made with functional components, but the code definitely will be bigger.

Lifecycle methods.

With version 16.8 React allows working with lifecycle methods of components. That means that developers have better control over functional components and can manipulate their life phases (initialization or setting the initial state, mount, update, unmount). The initialization is explained in the paragraph above, let’s look at the next stage.

Mounting.

The useEffect Hook for functional components:

const FunctionalComponent = () => {
React.useEffect(() => {
console.log(“Hello”);
}, []);
return <h1>Hello, World</h1>;
};

The componentDidMount method for class components:

class ClassComponent extends React.Component {
componentDidMount() {
console.log(“Hello”);
}

render() {
return <h1>Hello, World</h1>;
}
}

The useEffect Hook possesses two parameters: the first is the “effect” itself that is going to be called once after every render of the component. The second parameter is an array of observable state or states (or so-called a dependency list). useEffect Hook only runs if one of these states changes. Leaving the second parameter empty useEffect Hooks runs once after render.

Updating.

The useEffect Hook for functional components:

function BooksList () {
const [books, updateBooks] = React.useState([]);
const [counter, updateCounter] = React.useState(0);

React.useEffect(function effectFunction() {
if (books) {
updateBooks([…books, { name: ‘A new Book’, id: ‘…’}]);
}
}, [counter]);

const incrementCounter = () => {
updateCounter(counter + 1);
}

}

The componentDidUpdate method for class components:

componentDidUpdate(prevProps) {
// Typical usage (don’t forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}

As we have mentioned the second parameter in the useEffect hook is an array of observable states, once a counter changes it triggers the effectFunction hook.

Unmounting.

The useEffect Hook for functional components (yes, again):

const FunctionalComponent = () => {
React.useEffect(() => {
return () => {
console.log(“Bye”);
};
}, []);
return <h1>Bye, World</h1>;
};

The componentDidUnmount method for class components:

class ClassComponent extends React.Component {
componentDidMount() {
console.log(“Hello”);
}

render() {
return <h1>Hello, World</h1>;
}
}

3. Hoisting works only for functional components

Hoisting is a concept that appeared in ECMAScript® 2015 Language Specification. According to that concept, JavaScript moves variable and function declarations to the top that allows you to access a variable or a function first and only then declare it. Actually, JS doesn’t move the code, it puts declarations in memory during the compile phase that allows calling a function before you declare it. That is not true to classes, trying to get access to a class before the declaration throws a ReferenceError exception. 

An example of the code where we call function before its declaration: 

catName(“Tiger”);
function catName(name) {
console.log(“My cat’s name is ” + name);
}
// The result of the code above is: “My cat’s name is Tiger”

Even though we call the function before we write it, the code works great. The following code with class declaration will throw an error: 

const p = new MyName(); // ReferenceError
class MyName {}

That is not all. JavaScript only hoists declarations, not initialization. If we declare a variable and call it before the initialization it returns undefined. See example: 

console.log(myName); // Returns undefined, as only declaration was hoisted
var myName; // Declaration
myName = “John”; // Initialization

Initializations with keywords let and const are also hoisted, but not initialized. That means that your app is aware of the variable existence. However, it can’t use it until variable initialization. The example below will throw a ReferenceError:

myName = “John”;
let myName;

That example will not run at all:

myName = “John”;
const myName;

Why does it matter? Let’s get back to React and create a simple React app in index.js file with one component in a separate file Component.js:

import React from ‘react’;
import {render} from ‘react-dom’;
import App from ‘.Component’;render(
<App/>,
document.getElementById(“root”)
);

And the component itself:

const Component = () => {
return (
<div>Hello, React</div>
);
}
export default Component;

The app renders a text: “Hello, React”. Since the component is small, there is a sense not to separate it and merge it into index.js file like this:

import React from ‘react’;
import {render} from ‘react-dom’;
render(
<Component/>,
document.getElementById(“root”)
);
const Component = () => {
return (
<div>Hello, React</div>
);
}

And we get an undefined error because we try to render a component that was declared with an arrow function before we initialize it.To repair the code just re-order the declaration and put it before calling render().

4. The way they capture values (props)

One interesting experiment (the original article with full analysis can be found here) that took place on the Internet is the following React app.

It’s a simple app that simulates a social network request to follow someone. The app displays a drop-down list with three profiles to follow, static greetings text, and two buttons that call the confirmation alert to start following a chosen person. The confirmation alert appears 3 seconds later after you clicked the button. The delay is set with setTimeout() method. 

The list of the experiment is the following: 

Choose a profile to follow 
Click a follow button with “function” text in brackets near it
Change a profile to follow in the drop-down list before the confirmation alert appears 
Check the name in the confirmation alert 
Repeat the same four steps above for the follow button with “class” text in brackets

In the first case with the functional button switching the name doesn’t affect the confirmation alert. With the class button switching the name changes the alert message, even though you clicked to follow Dan but switched to Sophie, the alert message will be “Followed Sophie”. The correct behavior is the first, of course. No one likes to follow a wrong profile on social media.  

The reason for such a behavior lies in the essence of functional and class components. Let’s examine these lines of code:

class ProfilePage extends React.Component {
showMessage = () => {
alert(‘Followed ‘ + this.props.user); };

And:
function ProfilePage(props) {
const showMessage = () => {
alert(‘Followed ‘ + props.user);
};

As we have said props are read-only, they are immutable. So once you pass the props to a functional component ProfilePage(props), the only remaining task for React is to render it after the time is up. 

On the other hand, this is mutable. And it’s okay because it allows us to use states and lifecycle methods correctly. So if we pass other props while the alert message doesn’t appear, this.props.name. changes and showMessage method displays the last version of props. Our showMessage method is not tied to any particular render and that may become a problem. 

There are several potential solutions that actually work. One of them is to catch props at the time of render like this:

class ProfilePage extends React.Component {
render() {
// Capture the props!
const props = this.props;
// Note: we are *inside render*.
// These aren’t class methods.
const showMessage = () => {
alert(‘Followed ‘ + props.user); };

const handleClick = () => {
setTimeout(showMessage, 3000);
};

return <button onClick={handleClick}>Follow</button>;
}
}

So we stuck our certain props to a particular render().

5. Running tests 

There are two most popular instruments for running tests: Enzyme and Jest. Enzyme is a JavaScript testing utility for React that allows testing React components’ display. Jest is a JavaScript testing framework for writing tests, in other words, for creating, running, and structuring tests. 

These two instruments do a great job on both types of components. There are some specificities in running tests for functional components, like the fact, that state hooks are internal to the component and can’t be tested by calling them. However, instruments and methods are similar. 

6. Performance difference 

There is an opinion that functional components show a greater performance compared to class components. The point is that the React functional element is a simple object with 2 properties: type(string) and props(object). To render such a component React needs to call the function and pass props – that is all. 

Class components are more complex: they are instances of React.Component with the constructor in it and complicated system of methods for manipulating state and lifecycle. 

Theoretically, calling a function should take less time than creating an instance of a class. Well, one developer held a test: he rendered 10000 elements of stateless components and class components. You can see the result here. As we see from the 3 experiments there is no difference in render time between rendering class and functional components.

To sum up everything above: 

Сlass components were the only option to add states to components and manipulate lifecycle. However, it has changed since the introduction of Hooks, which gave the same opportunities to functional components as classes had. 
The major difference is the syntax. It relates to the way we declare components, pass props, handling states, manage lifecycle. 

Function components capture the props and state by default. It is not a bug, but a feature of functional components.

Functional components require less code to write an equal component. However, that doesn’t mean that functional components more readable and convenient to use. If a developer is used to work with object-oriented programming, he finds using class components much more comfortable. Those who are used to functional programming like functional components more than class components. 
There are two most popular tools to test functional and class components: Enzyme and Jest. They work great for both types of components. 
There is no big difference in render time between class and functional components. 

Today you can build a whole app using only functional components. It was impossible till 2019. That became possible thanks to Hooks. Does Hooks replace class components in the coming years? We don’t think so, because there are still some features that functional components can’t reproduce. And there will always be developers, who are used to working with objects rather than with functions. However, we await the growth in functional component popularity and an increase in the number of features for Hooks. And it’s likely that the functionality Hooks will provide goes beyond class components possibilities. 

Bonus: Building an App with Flatlogic Platform

Understanding Functional and Class components is an important stepping stone in React development. Crafting Apps by hand requires a thorough understanding of all the intricacies of the library. However, there’s a quicker way for those who aren’t technically adept or lack time to write the whole thing from the ground up. Some people need a unique App with functions not seen elsewhere, but most apps are different combinations of the same parts and features. We used that insight when developing the Flatlogic Platform.

Flatlogic Platform is a constructor-style tool for combining pre-built parts into brand-new applications. It requires a few steps from you. Keep reading to know what those are!

#1: Name the Project

This step is what it sounds like. The only valuable advice we can think of is to pick a name that is easy enough to associate with the project.

#2: Choose stack

Next up, choose the technologies your App’s parts will run on. Those are underlying technologies for back-end, front-end, and database. In this example, we’re picking a combination of React, Node.js, and MySQL. But all other combinations are perfectly compatible, too.

#3: Choose Design

You’ll have several design schemes to choose from. Some are transparent and light, others with a heavier feel. Pick the one you like, this part is purely aesthetical.

#4: Create the schema

The schema is the structure of a database. Names of fields, types of data, the way the App processes said data… Every aspect that defines how the database works is a part of the schema. It might be tricky at first, but you’ll get the hang of it. A thorough review of what your App is supposed to do will be helpful. If you’re short on time or unsure, pick one of the pre-built schemas. One of them is bound to suit your needs.

#5: Review and generate

The heavy decision-making is over. It’s time to check if every choice you’ve made is the way you want it to be and (assuming everything’s fine) hit “Finish”.

The compilation takes a couple of minutes on most devices. Upon completion, the Platform will offer you your very own App. Hit “Deploy”, host it locally in one click or push it to GitHub for further use or adjustment.

Flatlogic Platform helps create simple yet functional and smooth Apps for commercial and administrative purposes, make sure you give it a try! Happy developing and see you in the next articles!

You might also like these articles:

React.js vs. React Native. What are the Key Differences and Advantages?

Top 12 Bug Tracking Tools

Angular vs. Bootstrap – 6+ Key Differences, Pros, and Cons

The post Functional Components vs. Class Components in React.js appeared first on Flatlogic Blog.

What is REST API

What is REST API
How REST API works
HTTP methods
Best REST clients and testing tools

What is the REST API?

REST, or Representational State Transfer, API  is a client-service architecture that is based on a request/response design. REST APIs are primarily used to access and work with data. 

How the REST API works?

The REST API works almost in the same way as any website. The call is made from the client to the server, and the data is received back via the HTTP protocol. You can also use them to provide means of accessing resources available on the server required for the client through the web browser by using request headers, request body, response body, status codes, etc.

HTTP Methods

HTTP methods or HTTP verbs form the main part of uniform interface constraint, followed by REST, which determines what actions have to be followed to get the requested resource. 

GET, POST, PUT and DELETE methods can be used to perform CRUD operations like Create, Read, Update, Delete.

One of the major advantages of RESTs is that they provide lots of flexibility, allowing you to do more with that particular API. REST APIs are useful for:

 Cloud apps

REST APIs are useful in cloud apps because their calls have no static data. If something fails, components without static data can seamlessly redeploy and scale according to load changes.

 Cloud services

The REST API is also used in cloud services because you need to control how the URL is decoded to bind to the service via the API. However, cloud services and microservices are bound to make RESTful APIs the rule of the future.

 Web use 

Since REST is not tied to client-side technology, you can access these APIs from a client-side web project, IoT device, or iOS App. You can build the infrastructure for your company without worrying about being tied to a specific client-side technology stack.

Best REST Clients and Testing Tools

Swagger

Swagger is an API testing tool that allows users to start their functional, security, and performance testing right from the Open API Specifications. Some pros:

Supports API documentation, development, design, and testing.
Swagger offers many open source features for the OpenAPI specification.

Postman REST Client

With Postman, you can monitor the API, create automated tests, perform debugging, and run requests. Some pros:

Smooth automated testing.
Co-working features for easy sharing and management.
Supports Swagger and RAML files.

Katalon Studio

Katalon Studio provides a common place to create and perform API/Web services, UI functional, and mobile testing. Some pros:

Has one of the most secure assertion libraries.
It’s a complete package and framework.
Supports a data-driven approach.

Karate DSL

Karate DSL is a framework for automating API, Performance, and Load testing that has its scripting language – Domain Specific Language (DSL).  This framework runs on Java and uses the Apache HTTP client to make HTTP connections. Some pros:

Built-in support for JavaScript and JSON objects 
Very powerful JSON schema assertion and validation.
Parallel execution.
Integration with Gatling for Performance testing.

The post What is REST API appeared first on Flatlogic Blog.

Exposing webhooks via mezzio-swoole

I was first introduced to the concept of webhooks via a 2009 blog post by John Herren, a former colleague at Zend.
At the time, they were in their infancy; today, they’re ubiquituous, as they provide a mechanism for a service to notify interested parties of events.
This saves traffic; instead of consumers polling an API for event changes, the service notifies them directly.
It also means that the consumer does not need to setup things like cronjobs; they instead setup a webhook endpoint, register it with the service provider, and their application takes care of the rest.

The thing is, handling a webhook can often lead to additional processing, and you are expected to send an immediate response to the provider indicating you received the event.

How can you achieve this?

Offloading processing

It’s likely no secret that I’m a fan of Mezzio and OpenSwoole1.
Running PHP in a persistent process forces me to think about state in my applications, which in turn generally forces me to be more careful and explicit in how I code things.
On top of that, I get the benefit of persistent caching, better performance, and more.

One feature I pushed into mezzio-swoole (the Swoole and OpenSwoole bindings for Mezzio) was functionality for working with swoole task workers.
There’s a variety of ways to use the functionality, but my favorite is by using a PSR-14 EventDispatcher to dispatch an event to which I attach deferable listeners.

What does that look like?

Let’s say I have a GitHubWebhookEvent, for which I have associated a GitHubWebhookListener2 in my event dispatcher.
I would dispatch this event as follows:

/** @var GitHubWebhookEvent $event */
$dispatcher->dispatch($event);

The nice part about this is that the code dispatching the event does not need to know how the event is processed, or even when.
It just dispatches the event and moves on.

To make the listener deferable, in Mezzio applications, I can associate a special delegator factory provided by the mezzio-swoole package with the listener.
This is done with standard Mezzio dependency configuration:

use MezzioSwooleTaskDeferredServiceListenerDelegator;

return [
‘dependencies’ => [
‘delegators’ => [
GitHubWebhookListener::class => [
DeferredServiceListenerDelegator::class,
],
],
],
];

This approach means that my listener can have any number of dependencies, and be wired into the container, but when I request it, I’ll be returned a MezzioSwooleTaskDeferredServiceListener instead.
This class will create a swoole task from the listener and event, which defers execution to the task workers, offloading it from the web workers.

Event state

Task workers receive a copy of the event, not the original instance.
Any state changes your listener makes in the event instance will not be reflected in the instance present in your web workers.
As such, you should only defer listeners that do not communicate state back to the dispatching code via the event.

Sharing an event dispatcher with the web server

mezzio-swoole defines a marker interface, MezzioSwooleEventEventDispatcherInterface.
This interface is used to define an event-dispatcher service consumed by MezzioSwooleSwooleRequestHandlerRunner for the purpose of dispatching swoole HTTP server events, getting around the “one event, one handler” rule swoole follows.
However, that can mean that you end up with two different dispatchers in your application: one used by the swoole web server, and one by the application, and that means you cannot delegate tasks.

To get around this, alias the MezzioSwooleEventEventDispatcherInterface service to the PsrEventDispatcherEventDispatcherInterface service:

use MezzioSwooleEventEventDispatcherInterface as SwooleEventDispatcher;
use PsrEventDispatcherEventDispatcherInterface as PsrEventDispatcher;

return [
‘dependencies’ => [
‘alias’ => [
SwooleEventDispatcher::class => PsrEventDispatcher::class,
],
],
];

Then make sure that any listener providers used with your event dispatcher include the following mappings (all classes are in the MezzioSwooleEvent namespace):

ServerStartEvent maps to ServerStartListener

WorkerStartEvent maps to WorkerStartListener

RequestEvent maps to StaticResourceRequestListener

RequestEvent maps to RequestHandlerRequestListener

ServerShutdownEvent maps to ServerShutdownListener

TaskEvent maps to TaskInvokerListener

As an example, using my phly/phly-event-dispatcher package:

/** @var PhlyEventDispatcherAttachableListenerProvider $provider */
$provider->listen(ServerStartEvent::class, $container->get(ServerStartListener::class));
$provider->listen(WorkerStartEvent::class, $container->get(WorkerStartListener::class));
$provider->listen(RequestEvent::class, $container->get(StaticResourceRequestListener::class));
$provider->listen(RequestEvent::class, $container->get(RequestHandlerRequestListener::class));
$provider->listen(ServerShutdownEvent::class, $container->get(ServerShutdownListener::class));
$provider->listen(TaskEvent::class, $container->get(TaskInvokerListener::class));

Offloading processing via webhooks

What this means is you can write a handler for a webhook that receives a payload, creates an event from that payload, dispatches the event, and immediately returns a response.

As a simple example, let’s say that the webhook event will take just the request content in its entierty:

declare(strict_types=1);

namespace App;

class WebhookEvent
{
public function __construct(
public readonly string $requestContent,
) {
}
}

Our webhook would then create an event with content from the request, dispatch it, and return a 204 (empty) response, indicating success:

declare(strict_types=1);

namespace App;

use PsrEventDispatcherEventDispatcherInterface;
use PsrHttpMessageResponseFactoryInterface;
use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
use PsrHttpServerRequestHandlerInterface;

class AtomHandler implements RequestHandlerInterface
{
public function __construct(
private ResponseFactoryInterface $responseFactory,
private EventDispatcherInterface $dispatcher,
) {
}

public function handle(ServerRequestInterface $request): ResponseInterface
{
$this->dispatcher->dispatch(new WebhookEvent((string) $request->getBody()));

return $this->responseFactory->createResponse(204);
}
}

GitHub gets an immediate 204 response back, indicating we’ve accepted the payload, and a task worker is delivered the payload to process when it gets a chance.

I like this approach, as it keeps the web logic minimal and simple, while giving me the power to process the webhook event with all the tools at my disposal.

Validation

You will want to make sure you validate your payload before doing any actual processing.
You can do that in the handler if desired, and return a 4xx error if needed.
My experience, however, is that most service providers that use webhooks don’t do anything with such errors, other than potentially stop sending payloads after a series of such responses.
As such, I usually put validation into my listeners, where I can log problems and then follow-up on them later.

Other considerations

Many services will use a shared secret when sending webhooks.
This might be used to generate a signature that is sent in the header, or even just a header value that indicates the payload came from them.
I put such validation into middleware, as it (a) becomes reusable in scenarios where the secret is the same, or where I might have multiple webhooks registered for different events from the same provider.
Mezzio makes it possible to add middleware when defining a route, ensuring that the middleware only gets triggered when it’s needed:

$app->post(‘/api/github/release’, [
GitHubWebhookValidationMiddleware::class, // validation middleware
GitHubReleaseWebhookHandler::class, // webhook handler
], ‘webhook.github.release’);

You’ll want to manage errors gracefully for your webhook endpoints.
Even though there’s not much code in the handler, another listener might raise an exception, or some of your middleware might (see above point).
I recommend putting the mezzio-problem-details middleware in your webhook handler’s pipeline:

$app->post(‘/api/github/release’, [
MezzioProblemDetailsProblemDetailsMiddleware::class,
GitHubWebhookValidationMiddleware::class, // validation middleware
GitHubReleaseWebhookHandler::class, // webhook handler
], ‘webhook.github.release’);

Similarly, your listener should let you know when there are errors.
The best way to do that is via logging, or via any monitoring APIs you may be using in your application.

Footnotes

1 I’ll refer to the two projects collectively as “swoole” throughout the document.

2 PSR-14 defines a ListenerProviderInterface from which event dispatchers can optionally retrieve listeners associated with the dispatched event.
Wiring these is up to the application developer; PSR-14 libraries generally provide these mechanisms.

Exposing webhooks via mezzio-swoole was originally
published 25 January 2022
on https://mwop.net by
Matthew Weier O’Phinney.

20+ Best Premium and Free Icon Packs for Web Developers and Designers

Pros of using icons
Best Icon Packs

Bonus!Creating Apps with Flatlogic

Final thoughts

Icons have a significant role in giving you the first impression of a site or application interface. But it takes a lot of time and money to develop them from scratch. Using icons on your site allows you to effectively communicate with your visitors: they increase readability, highlight important content, reinforce functionality or features, and enhance the design. Therefore, it is worth paying attention to ready-made best icon packs.

Also, when it comes to icon design, this is a great way to showcase designer qualifications. A sweet, nice icon pack is a perfect showcase of a designer’s work and a powerful instrument to build up your reputation online.

Additionally, icons are one of the most integral parts of a website or application. Icons are responsible for navigation and affect the overall experience of the application. Nowadays, if you are a small company there are many free and paid icon packs available. The process of choosing icons is very important, there are a bunch of icon resources, which also can be subdivided into material icons or social media icons. That is why we have compiled a selection of free and paid icon packs and resources for you.

Pros of using icons in your next UX design project

Icons help to increase the site or app readability;
Well made icons help reduce text volume. Using icons makes your message understandable without text;
Icons can add personalization to your product;
Icons can be a good starting point in getting to know the product;
Last, but not least: one of the most important functions of icons is to help users intuitively understand the application both at the first acquaintance and during subsequent use.

In this article, you will find a collection of some of the best premium and free icon packs you can use on your website or business, even if you’re not a creative artist. The icon sets presented in this article may be used not only on common websites and in basic cases, but also in more complex and specialized ones.

We split the icon packs into several categories for your ease. Before descriptions, you will see the category this product belongs to.

Free icons;

Marketplaces with icon sets. The marketplace contains icons from different authors. Here you can find both cheap and expensive, as well as good and low-quality products;

Material icon sets and Flat icon sets;

CSS icon sets. CSS icons are made using – guess what – CSS. To use them, just copy the code to your page;

Icons fonts. According to Pluralsight, icon fonts are actual fonts that contain symbols and glyphs instead of letters or numbers. They’re popular for web designers since you can style them with CSS the same way as regular text. Icon fonts are treated as text by browsers, so you’ll need to normalize them to avoid text anti-aliasing issues, and are supported in almost all browsers;

SVG icons. Scalable Vector Graphics (SVG) is an XML-based vector graphics format that can scale to any size without losing clarity. They can be displayed through using CSS, object tags, image tags, or inlined directly into your HTML;

Glyph and pictogram icon sets.

The List of Best Icon Packs

Flaticon

Web-site: https://www.flaticon.com/packs
Formats and Type: PNG, SVG, EPS, PSD, and BASE 64, Marketplace
Price and License: Limited free plan & premium plans from $7.50/month

Flaticon contains completely editable vectors and can be used for both personal and commercial projects. FlatIcon has more than 2.3 million vector icons grouped into 51202 packs.

The product has Adobe Extension which allows you to easily import icons inside Photoshop, Illustrator, and After Effects. If you’d like to use a web font instead of static files for your icons, FlatIcon will take care of the format conversion and generate a web font ready to use. You can also customize downloaded icons.

Key facts:

over 90,000 icons;
SVG, EPS, PSD, and PNG formats;
icon fonts;
Adobe Extension for CC suite;
Linkshare license with premium options; and
new icon packs are added every month.

A premium subscription with FlatIcon will provide you with full licensing rights, access to exclusive content, no ads, a MacOS app, and Adobe extensions, as well as the ability to create unlimited collections.

Jam Icons

Web-site: https://jam-icons.com/
Format and Type: SVG, CSS
Price and License: Free, MIT

Jam icons are a set of 896 handcrafted icons. This icon pack comes with both SVG and font versions. The icons can be used as SVG files in your web, print, or application development projects. The icons can also be used as a font with the given CSS stylesheets. There are 16px, 24px and 32px sizes. You can also choose to fill or stroke icons.

Fontisto Icon Pack

Web-site: https://fontisto.com/
Format and Type: CSS
Price and License: Free, MIT

Fontisto is a vector icons pack. Icons can be instantly customized: size, color, drop shadow, and anything that can be done with the power of CSS. The product doesn’t require Javascript. Fontisto icons are vectors, which means they will look good on high-resolution monitors.

On the website, you can find full documentation and various guides on how to start and customize the product. You can start using the product by simply pasting the link on your website. Additionally, you can use Fontisto with the package managers that are right for you: npm, yarn, bower, etc.

Iconscout

Web-site: https://iconscout.com/icons
Format and Type: SVG, PNG, ICO, ICNS, EPS, AI, PDF
License and Pricing: Free and Premium plans from $11.99

Iconscout is a resource of more than 2.9 million Vector Icons. Their range of icons category is incredible, no matter which kind of icons you search you’ll always get it on Iconscout. They come in a wide variety of styles of icons: outlined, solid, colored outlined, hand-drawn, and many more.
They also provide integrated tools, plugins, and editors. You can customize and convert your icons without leaving Iconscout.

Key Facts:

2.9M+ Icons, 30K+ Illustrations, 3K+ 3D Assets, 2.8k Lottie animations;
5000+ assets added every day;
Iconscout Application available to use right from your toolbar;
Integrated plugins and tools like Icon Editor and Icon Converter.

Iconmonstr

Web-site: https://iconmonstr.com/
Format and Type: SVG, EPS, PSD and PNG, Marketplace
Price and License: Free

Iconmonstr’s collection of icons has 4400+ icons. Every icon set offers both outlines and filled versions of the graphics to ensure that they can be used for a variety of design applications. Every icon on this site is available for free, and icon files come in such formats as SVG, AI, PSD, and PNG. The files can be used for free and commercial purposes.

Iconmonstr makes it simple to search for icons via its powerful search function. You can even save your favorite icons in a personal collection for future use.

Key features:

free use of all icons,
four format download options, and
downsized icons optimized for web use.

Pixsellz Material Icons Library

Web-site: https://icons.pixsellz.io/
Format: SVG, EPS, PSD, PNG, FIG, Material design
Price and License: Free, Apache License Version 2.0

A huge bundle of over 1000 icons divided into 16 different categories. The free icon pack is inspired by Material design and presented into three different visual styles – rounded, outline, and two-tone. The set is available in 6 different file formats, so you can use the icons in your preferred design software.

Key features:

3 styles,
Figma styles,
1000+ icons,
24×24 pixels,
Sketch styles and symbols,
16 categories, and
6 file formats.

Entypo

Web-site: http://www.entypo.com/
Format and Type: SVG
Price and License: Free, Creative Common License 4.0

Entypo is an SVG icon family pack, carefully crafted a few years ago by Daniel Bruce in Sweden. These icons are superb: when it comes to freebies, they’re top of the line. The product comes as SVG with 411 icons, free with a Creative Commons License.

The author says building a font takes a lot of time and it is better to spend time on developing new pictograms.

Evil Icons

Web-site: https://evil-icons.io/
Format and Type: SVG, Sketch
Price and License: Free, MIT

This pack is absolutely massive and it comes with everything – including SVGs and the original source files. That means you can download SVGs along with files for Illustrator and the .sketch files for Sketch.

Every icon follows the thin line style and they’re perfect for most websites. The fact you can edit the original source makes them even more valuable.

Streamline Icons

Web-site: https://streamlineicons.com/
Format and Type: ICONJAR, SKETCH, FIG, XD, SVG, AI, PDF, PNG
Price and License: Free to $411

Streamline Icons is another nice and adaptable free icon pack on the web market. The tool is organized in 53 categories with over 30000 vector icons.

This is one of the few icon packs optimized for Sketch, making it easy to manipulate stroke widths and colors. Built-in Sketch features such as symbols and shared styles make reusing elements, like icons, a quick and easy process.

The company has its own web app that helps to browse, search and download icons right from the browser.

Key features:

more than 30000 vector icons organized;
Smart Strokes to modify outline thickness;
Sketch, AI, EPS, PDF, PNG, SVG formats;
web app to search and edit icons;
each icon in Streamline 3.0 has three unique weights: light, regular and bold.

Smashicons

Web-site: https://smashicons.com/
Format and Type: JAR, SVG, AI, SKETCH, Marketplace
Price and License: Free to $149

Smashicons offers a comprehensive collection of icons with over 219000+ icons in their library. Smashicons works a bit differently than others: their pricing is based on a monthly plan of $5/month. This means that for $5 a month you get access to their entire collection of existing icons as well as any future icons they release.

Key features:

a very large collection of icons,
all icons are multi-platform compatible,
easy-to-use web app to search and find the icons you need,
subscription-based business model,
multiplatform support.

Icons8

Web-site: https://icons8.com/
Format and Type: SVG, PNG, PDF
License and Pricing: Good Boy License, Free to $24 per month

The icon set from Icons8 comes with more than 120000 icons that cover several categories; from business and office settings to people, food, and social media icons. The icons are designed to mimic the look of a specific operating system. You can download them in Windows, iOS, and Android versions.

The icons work with Sketch, Photoshop, and Xcode. You can use a web editor before downloading the icons to your system.

Key features:

SVG, PNG, and HTML formats;
icons available in different styles, such as line icon, filled icon, and full color;
all icons can be downloaded via .zip file;
edit before downloading;
both free and paid subscription options.

Icomoon

Web-site: https://icomoon.io/
Format and Type: SVG, PNG, PDF
License and Pricing: Free to $139 per month

Icomoon comes as a complete tool for iconography and icon management. The product has a high-quality solution for editing and managing icons. The Icomoon icons have been handcrafted on a 16X16 grid and are available in SVG, EPS, PSD, PDF, and AI formats. The icon set is also constantly updated by its creators.

Each icon pack features detailed licensing so that designers and developers know exactly how icons can be used. Users can also make their own custom icon fonts.

Key features:

comprehensive icon management tools,
free and paid download options,
a wide variety of download formats,
free and easy updates.

Glyphish Icon Pack

Web-site: http://www.glyphish.com/
Format and Type: SVG, PNG, PDF, PSD, Glyph, Icon font
License and Pricing: Creative Common Attribution, $99 lifetime

Glyphish offers a variety of different icon packs. Every pack comes in a variety of different formats, including PNG, SVG, PSD, and AI. The icon pack is available for $99. The free demo includes 50 icons. All icons can be easily edited by designers.

Key features:

icons for several platforms: iOS, Android, Web, Windows;
a set of 50 free icons;
easy drag-and-drop into Xcode;
icons specially sized for Apple Retina displays.

Ionicons

Web-site: https://ionicons.com/
Format and Type: SVG and Webfont, Icon font
License: MIT

The Ionic team decided to release their icons as a webfont called Ionicons. Naturally, they’re totally free and available on GitHub. You can even add these icons directly to your site using the CDN version of the stylesheet. It fully supports SVG and web fonts.

Key features:

completely free,
easy setup by copying and pasting link,
comes as a webfont,
customized sizes,
over 1100 items.

Angular Material Icons

Web-site: https://material.io/resources/icons/?style=baseline
Format and Type: SVG, Webfont, Material design
License and Pricing: Free, Apache License 2.0

Material Icon is a free icon pack from Google. To ensure readability and clarity, these icons have been optimized to look great on all platforms and displays. These material icons are totally free and accessible on GitHub. This icon pack is absolutely massive with over 1,000 icons covering a wide array of interface features.

All of the symbols are available in five themes. You will get a range of downloadable sizes and densities. The best format for web projects is an easy-to-use icon web font.

Linearicons

Web-site: https://linearicons.com/
Format and Type: SVG, Webfont, Icon font
License and Pricing: Free to $59, Common Creative License

Linear Icon pack is one of the most popular and best icon packs for personal or commercial purposes. Linear icon pack comes in both free and premium versions. The free version of this amazing icon pack comes under Creative Common license. There are also different packages you can choose for your needs, such as the Desktop Package.

Key features:

CloudFront CDN;
free version available;
comes with different formats: SVG, PDF, Webfont.

Feathericons

Web-site: https://feathericons.com/
Format and Type: SVG, Webfont, Iconfont
License and Pricing: Free, MIT License

Feather is one of the most popular open-source icon sets. These are open-source icons that have been designed on a 24X24 grid. The icons are available in SVG format. It’s under the MIT license, and there are about 250+ icons in open source.

The icons are easy to edit, clean and crisp – regardless of size. They were designed as an icon font first, so it’s meant to be embedded as a web font.

Iconfinder

Web-site: https://www.iconfinder.com/
Format: SVG, PNG, ICO, Marketplace
License and Pricing: From $9 to $49 per month

Iconfinder is one of the most popular icon resources on the net. It offers over 4 million icons, providing users with a variety of search options including icon format, price, size, background, etc. There are several monthly payment plans – from $9 to $49. You can also choose the “pay as you go” system.

Icon files are available in SVG, PNG, ICO, ICNS, and Adobe Illustrator formats, and dimensions range between 16×16 to 512×512. You can also work with some of the site’s best designers if you can’t find something you like or simply want custom icons designed especially for you and your brand.

Key features:

both free and paid use options,
flexible search features,
icons available in a variety of formats,
a lot of categories and styles,
icon editor.

The Noun Project

Web-site: https://thenounproject.com/
Format and Type: SVG, PNG, Marketplace
License and Pricing: Creative Commons License, From $39.99

The Noun Project offers one of the largest icon libraries available on the web. Most of this site’s icons are available in SVG and PNG formats, as well as in black and white styles.

The site’s library is made up of icon files designed by a variety of independent designers. It’s a place where creators and creative professionals can collaborate to sell their designs and find a seemingly endless library of premium icons.

Searching this huge and comprehensive icon library is very easy. Additional key features of this icon library include both free and premium download options, many large sets of icons, an application for Mac, and more. This icon library is regularly updated, and new icons and sets are being posted every day.

Key features:

over 150,000 icons;
SVG, PNG formats;
search and discovery tools;
Creative Common License with premium options;
free and paid download options;
new icons uploaded on a near-daily basis.

Fontawesome Icons

Web-site: https://fontawesome.com/icons
Format and Type: SVG, PNG, Icon font, Marketplace
License and Pricing: SIL OFL 1.1

Font Awesome is the most used and the most popular icon font set around. It is also the default icon set for the team at bootstrap. It is also available as SVG icons among other formats.The license is open and free for anything, commercial or personal.

Every icon is fully scalable and maintainable directly in CSS. You can change colors, shadows, background gradients, and pretty much anything else using pure CSS3. Another reason to use this library is that it’s fully optimized and has no compatibility issues because it doesn’t require JavaScript at all.

Key features:

Vector Font,
every icon comes with a CSS Class & Unicode,
free,
built with accessibility in mind,
features easy upgrading across websites,
offers a desktop cheat sheet for the entire icon library.

Lineicons

Web-site: https://lineicons.com/
Format and Type: SVG, Web font, Icon font
License and Pricing: Free

LineIcons also provide free CDN with clear documentation which makes it easy to get started. 

This icon pack is completely free and comes with 450+ line icons. It covers every single essential icon you need for the project from different categories. LineIcons also provides free CDN and clear documentation to get started easily. It comes with 2 different scalable packages – WebFonts and SVG files you can use depending on your project needs.

Key features:

450+ Free Icons,
SVG Files,
Web Font Ready,
free CDN.

Bonus!

A little less than a year has gone by since we released the article. We kept checking the market for new icons and ion packs and we’re happy to report the rating still stands. Still, the market is vibrant and ever-changing, so there had to be some shifts and updates. The packs on our list aren’t sorted in any specific order so there’s no need to realign them. However, we found a few new entries for the list, and we believe at least one of them deserves an honorable spot.

Linea Icons

Website: https://linea.io/

Formats: SVG, PNG

Linea is a vast icon hub. They have numerous categories like Free Basic Icons, Line Icons, Free e-Commerce Icons, and so on. Theirs is one of the richest free icon collections out there. If we had to pick the main minus of Linea’s collection, we’d say it’s the lack of diversity. All icons here are similarly styled which can be an issue if you plan to launch a second product with a distinctly different style. However, with the icons available in .png and other formats supporting transparent backgrounds, their look changes greatly with a background. We loved Linea icons’ distinctive hand-drawn style. And considering that most of their packages are free, you should definitely give Linea a try.

Features:

Free access
Cozy hand-drawn-like look
A variety of collections like eCommerce, arrows, music, etc.

Building an App with Flatlogic

We’ve covered a lot about web icons and using them in web development. If that’s all you needed out of the article, skip to the conclusion. If you’re interested in creating applications on your own without special training and with minimal investment of your time, keep reading!

Most applications can be replicated by using different combinations of the same parts. That’s what we did with Flatlogic Platform. We stripped App development down to just a few choices. Next up, we’ll see what they are.

#1: Pick a Name

This part is self-explanatory

#2: Pick a Stack

Choose underlying technologies for the front-end, the back-end, and the database. Minimal research of each option should suffice.

#3: Pick the Design

You’ll see several design options. Pick the one that you’re the most comfortable with. You’ll probably spend a lot of time looking at it.

#4: Pick the Database Schema

Define the fields, data types, parameters, and the relationships between all of them. The schema is how your database works. It’s what kind of data it receives and how it processes that data. Our Schema Editor is easy to use. Or you could use one of the ready schemas you’ll be offered.

#5: Review and Generate

At this stage, you’ll do exactly that: review if all options are right and generate the App. Once the App is ready, you can push it to GitHub or host it in one click.

Final Thoughts about Icon Packs

Choosing the right icon pack for your project should not be based on what is considered most popular but rather what best suits the needs of your project. When choosing an icon set, pay attention to how easy it is to start a project, which formats are present in the library, and the price.

Also, an important factor when choosing an icon pack will be matching the style of your application or site.

We hope this article will help you choose the most suitable premium or free icon pack for your needs.

You might also like these articles:

jQuery vs JavaScript. Why we Removed jQuery From our Templates?
Top JavaScript Maps API and Libraries
20+ React Developer Tools to Increase Your Programming Productivity

The post 20+ Best Premium and Free Icon Packs for Web Developers and Designers appeared first on Flatlogic Blog.

Azure Functions consumption plan naming

This post is about how to follow naming conventions for Azure Function consumption plans. Unlike Azure App Services, when we create Azure Functions with consumption plan Azure will create a plan name which you can’t modify. If you’re following certain naming conventions it will be different from what you’re following. Here is an example.

If you choose App Service Plan or Premium Plan there is an option to create new plan with the name.

I was following the naming convention from Microsoft Docs. You can find more details here and here.

There is no direct way to solve this problem. But we can do something like – create an ARM template and deploy it instead of creating it directly. So in the Review + Create screen, click on the Download a template for automation link. We will get a screen like this.

In this screen choose the Deploy option. It will redirect to Custom Deployment screen – in this screen you will get an option to create / modify the Hosting Plan Name. And which will help you to configure your Function App consumption plan name.

This way you can create Azure Function consumption plans with our desired name.

Here are some resources which will help you to learn more about Azure Resource naming.

Develop your naming and tagging strategy for Azure resources
Define your naming convention

Happy Programming 🙂

Asimov, programming and the meta ladder

One of my favorite stories by Isaac Asimov is Profession. The following is a
spoiler, so please read the story before proceeding if you don’t like spoilers.

In the futuristic society of year 6000-something, people no longer need to learn
their profession from books, lectures or hands-on experience. Each person has
their brain analyzed at a certain age and then the know-how for the occupation
that’s best suited for them is simply uploaded into the brain using special
cassettes (hey, this story is 60 years old) and electrodes. The folks who end up
the best at their craft (determined via competitions) end up with high-demand
assignments on “Class A” outer worlds.

The protagonist, George Platen, has a dream of getting “educated” in a certain
profession and reaching a desirable assignment. But he runs into trouble when
his brain assessment determines that no profession is a good fit for him, and
he’s placed in a special “house for the feeble-minded” to spend his time however
he wants, even reading books.

Long story short, after some adventures George discovers the truth on his own;
someone has to create these training cassettes, advance human technology and
update training materials to account for these advances. There’s a
“meta-profession”, something akin to scientist, and George was selected for this
meta-profession.

I always loved this story for the meta aspect; many occupations are prone to
automation, and this has become much more true since Asimov first put the plot
to paper. But some human professions are necessarily “meta”; you can automate
them, but this just generates new professions that have to develop said
automation. Ad infinitum, or at least until Singularity.

In the course of my career, I’ve heard the promises of “no code” programming
many times. These tools didn’t cause the demand for programmers to plummet, but
to simply shift in other directions. More recently, I treat the hype about AI
coding assistants like GitHub Copilot with similar calm. These are
great tools that are going to make some programmers’ lives easier, but replace
programmers? Nope; only move programmers another notch up the meta ladder.

By the way, do you know what profession George Platen was aiming at before he
knew the truth? Computer programmer. That’s a pretty far-sighted move by Asimov,
given that the story was written in 1957!

Client Side PDF Generation In Angular With jsPDF.

Client Side PDF Generation In Angular With jsPDF.

In this Angular PDF tutorial, i’m getting to share with you ways to export PDF come in Angular application  exploitation the jsPDF package. we are able to generate PDF for numerous documents like invoices, reports, forms etc. in an exceedingly net application, we are able to produce pdf exploitation Browser print strategies, third party tool, and that we may transfer the PDF on the client-side.

There are few other PDF packages available such as:

jsPDF
PDFMake
ng2-pdf-viewer

However, during this post, we tend to area unit about to focus solely on jsPDF generator plugin to export the PDF in Angular twelve.

The jsPDF may be a JavaScript-based module, it’s accustomed generate PDFs on the client-side, and it offers the big range of strategies that enables you to customise the PDF read simply.

You can check out the official documentation here.

What is a PDF File?

Adobe developed PDF at around Nineteen Nineties. it’s two primary goals. The primary goal was that users ought to be ready to open the documents on any hardware or software. The second goal was that whenever a user opens a PDF document that has got to look a similar.

PDFs embrace text, images, embedded fonts, hyperlinks, video, interactive buttons, forms, and more.

Setup Angular Project

Use command via Angular CLI to create a brand new Angular project.

ng new angular-jspdf

Install jsPDF Package

npm install jspdf

Usage

import { jsPDF } from “jspdf”;

// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();

doc.text(“Hello world!”, 10, 10);
doc.save(“a4.pdf”);

If you want to change the paper size, orientation, or units, you can do.

// Landscape export, 2×4 inches
const doc = new jsPDF({
orientation: “landscape”,
unit: “in”,
format: [4, 2]
});

doc.text(“Hello world!”, 1, 1);
doc.save(“two-by-four.pdf”);

 

The post Client Side PDF Generation In Angular With jsPDF. appeared first on PHPFOREVER.

Running cronjobs via an Openswoole timer

Sites I build often utilize cronjobs to periodically pull in data from other sources.
For example, I might want to poll an API once a day, or scrape content from another website once a month.
Cronjobs are a perfect fit for this.

However, cron has a few problems:

If the job is writing information into the file tree of your web application, you need to ensure permissions are correct, both at the filesystem level, and when writing the cronjob (e.g., running it as the same user, or changing permissions on completion).
If you are running console tooling associated with your PHP application, you may need to worry about whether or not particular environment variables are in scope when you run the job.
In containerized environments, usage of cron is strongly discouraged, as it means running another daemon.
You can get around this with tools such as the s6-overlay, but it’s another vector for issues.

Since most sites I build anymore use mezzio-swoole, I started wondering if I might be able to handle these jobs another way.

Task workers

We introduced integration with Swoole’s task workers in version 2 of mezzio-swoole.
Task workers run as a separate pool from web workers, and allow web workers to offload heavy processing when the results are not needed for the current request.
They act as a form of per-server message queue, and are great for doing things such as sending emails, processing webhook payloads, and more.

The integration in mezzio-swoole allows you to decorate PSR-14 EventDispatcher listeners in mezzio-swoole MezzioSwooleTaskDeferredListener or DeferredServiceListener instances; when that happens, the decorator creates a task with the Swoole server, giving it the actual listener and the event.
When the schedule process the task, it then calls the listener with the event.

The upshot is that to create a task, you just dispatch an event from your code.
Your code is thus agnostic about the fact that it’s being handled asynchronously.

However, because tasks work in a separate pool, this means that the event instances they receive are technically copies and not references; as such, your application code cannot expect the listener to communicate event state back to you.
If you choose to use this feature, only use it for fire-and-forget events.

I bring all this up now because I’m going to circle back to it in a bit.

Scheduling jobs

Swoole’s answer to scheduling jobs is its timer.
With a timer, you can tick: invoke functionality each time a period has elapsed.
Timers operate within event loops, which means every server type that Swoole exposes has a tick() method, including the HTTP server.

The obvious answer, then, is to register a tick:

// Intervals are measured in milliseconds.
// The following means “every 3 hours”.
$server->tick(1000 * 60 * 60 * 3, $callback);

Now I hit the problems:

How do I get access to the server instance?
What can I specify as a callback, and how do I get it?

With mezzio-swoole, the time to register this is when the HTTP server starts.
Since Swoole only allows one listener per event, mezzio-swoole composes a PSR-14 event dispatcher, and registers with each Swoole HTTP server event.
The listeners then trigger events via the PSR-14 event dispatcher, using custom event types internally that provide access to the data originally passed to the Swoole server events.
This approach allows the application developer to attach listeners to events and modify how the application works.

To allow these “workflow” events to be separate from the application if desired, we register a MezzioSwooleEventEventDispatcherInterface service that returns a discrete PSR-14 event dispatcher implementation.
I generally alias this to the PSR-14 interface, so I can use the same instance for application events.

I use my own phly/phly-event-dispatcher implementation, which provides a number of different listener providers.
The easiest one is PhlyEventDispatcherAttachableListenerProvider, which defines a single listen() method for attaching a listener to a given event class.

On top of that, Mezzio and Laminas have a concept of delegator factories.
These allow you to “decorate” the creation of a service.
One use case is to decorate the AttachableListenerProvider service, and call its listen() method to attach listeners.

This is the long-winded explanation for what comes next: a delegator factory on AttachableListenerProvider that registers a listener on MezzioSwooleEventServerStartEvent that in turn registers a tick to run a job pulled from the container:

namespace Mwop;

use MezzioSwooleEventServerStartEvent;
use PhlyEventDispatcherAttachableListenerProvider;
use PsrContainerContainerInterface;

class RunPeriodicJobDelegatorFactory
{
public function __invoke(
ContainerInterface $container,
string $serviceName,
callable $factory,
): AttachableListenerProvider {
/** @var AttachableListenerProvider $provider */
$provider = $factory();

$provider->listen(
ServerStartEvent::class,
function (ServerStartEvent $e) use ($container): void {
$e->getServer()->tick(
1000 * 60 * 60 * 3,
$container->get(SomeJobRunner::class),
);
},
);

return $provider;
}
}

I then would attach this to the AttachableListenerProvider via configuration:

use MwopRunPeriodicJobDelegatorFactory;
use PhlyEventDispatcherAttachableListenerProvider;

return [
‘dependencies’ => [
‘delegators’ => [
AttachableListenerProvider::class => [
RunPeriodicJobDelegatorFactory::class,
],
],
],
];

This is… fine.
However, I ran into a scenarios almost immediately where this approach caused a segfault in the application, bringing down the server.

And that’s where the tasks come back into play.

I modified the above example to now dispatch an event instead.

namespace Mwop;

use MezzioSwooleEventServerStartEvent;
use PhlyEventDispatcherAttachableListenerProvider;
use PsrContainerContainerInterface;
use PsrEventDispatcherEventDispatcherInterface;

class RunPeriodicJobDelegatorFactory
{
public function __invoke(
ContainerInterface $container,
string $serviceName,
callable $factory,
): AttachableListenerProvider {
/** @var AttachableListenerProvider $provider */
$provider = $factory();

$provider->listen(
ServerStartEvent::class,
function (ServerStartEvent $e) use ($container): void {
// This is done in the listener to prevent a race condition!
$dispatcher = $container->get(EventDispatcherInterface::class),

$e->getServer()->tick(
1000 * 60 * 60 * 3,
function () use ($dispatcher): void {
$dispatcher->dispatch(new SomeJob());
}
);
},
);

return $provider;
}
}

This approach requires a bit more work.
I need to now also register a listener for the SomeJob event, and I need to configure the listener to be deferable.

First, let’s create a delegator to attach that listener; it will look a lot like the previous examples:

namespace Mwop;

use PhlyEventDispatcherAttachableListenerProvider;
use PsrContainerContainerInterface;

class SomeJobRunnerDelegatorFactory
{
public function __invoke(
ContainerInterface $container,
string $serviceName,
callable $factory,
): AttachableListenerProvider {
/** @var AttachableListenerProvider $provider */
$provider = $factory();

$provider->listen(
SomeJob::class,
// Since listeners are invokables, we can likely use the same class as previously
$container->get(SomeJobRunner::class)
);

return $provider;
}
}

Now for the wiring.
We’ll register both delegator factories with the AttachableListenerProvider, but we will also register a delegator factory for our SomeJobRunner class:

return [
use MezzioSwooleTaskDeferredServiceListenerDelegator;
use MwopRunPeriodicJobDelegatorFactory;
use PhlyEventDispatcherAttachableListenerProvider;

return [
‘dependencies’ => [
‘delegators’ => [
AttachableListenerProvider::class => [
RunPeriodicJobDelegatorFactory::class,
SomeJobRunnerDelegatorFactory::class,
],
SomeJobRunner::class => [
DeferredServiceListenerDelegator::class,
],
],
],
];

This outlines why delegator factory configuration maps to arrays instead of class names: so you can run more than one per service.
When we request our AttachableListenerProvider service, its factory will be passed to the first delegator, and the return value of that delegator passed to the next, and so on.
The result here is that we end up registering both of our listeners with it.

The second registration is a fun one.
The DeferredServiceListenerDelegator registers a MezzioSwooleTaskServiceBasedTask that incorporates the service name and the container.
When invoked, it passes the event instance provided to it to the task instance.
When the task is invoked, it pulls the listener from the container, and then calls it with the event.

The end result is that by dispatching an event in our tick handler, we effectively push execution into our task workers, ensuring we don’t waste precious web workers on handling the periodic event.

Scheduling jobs

The problem I saw with this approach is that it required adding a tick every time I want to create a new periodic job.
On top of that, I have no control over when it would execute, only how frequently.
Say what you want about cron, but it does understand how to schedule for specific times.

So, I grabbed Chris Tankersley’s cron-expression package.
This excellent package allows you to pass a cron schedule string to it, and it will then let you know:

If it is a valid schedule.
If it’s due to run at the given time (defaulting to “now”).

With this in hand, I could create a generalized tick.

I decided that my configuration would be in the following format:

[
‘jobs’ => [
‘job name’ => [
‘schedule’ => ‘crontab expression’,
‘event’ => ‘event class name’,
],
],
]

From there, I created a Cronjob class that had properties for the schedule and event class:

namespace Mwop;

class Cronjob
{
public function __construct(
public readonly string $schedule,
public readonly string $eventClass,
) {
}
}

and one representing the entire crontab:

namespace Mwop;

use ArrayIterator;
use Countable;
use IteratorAggregate;
use Traversable;

use function count;

class Crontab implements Countable, IteratorAggregate
{
/** @var Cronjob[] */
private array $jobs = [];

public function count(): int
{
return count($this->jobs);
}

public function getIterator(): Traversable
{
return new ArrayIterator($this->jobs);
}

public function append(Cronjob $job): void
{
$this->jobs[] = $job;
}
}

A cron event interface would allow me to instantiate events to listen to, and give me access to the timestamp if needed:

namespace Mwop;

use DateTimeInterface;

interface CronEventInterface
{
public static function forTimestamp(DateTimeInterface $timestamp): self;

public function timestamp(): DateTimeInterface;
}

A config parser will validate the various entries, logging and omitting any that are invalid.
I’m not showing that code, as it’s fairly verbose, and easy to create on your own.

With those changes, I could now update my delegator to be more general:

namespace Mwop;

use CronCronExpression;
use DateTimeImmutable;
use MezzioSwooleEventServerStartEvent;
use PhlyEventDispatcherAttachableListenerProvider;
use PsrContainerContainerInterface;
use PsrEventDispatcherEventDispatcherInterface;
use PsrLogLoggerInterface;

class RunPeriodicJobDelegatorFactory
{
public function __invoke(
ContainerInterface $container,
string $serviceName,
callable $factory,
): AttachableListenerProvider {
/** @var AttachableListenerProvider $provider */
$provider = $factory();

$config = $container->get(‘config’)[‘cron’][‘jobs’] ?? [];

/** @var Crontab $crontab */
$crontab = (new ConfigParser())($config, $container->get(LoggerInterface::class));

// Do not register if there are no jobs!
if (0 === $crontab->count()) {
return $provider;
}

$provider->listen(
ServerStartEvent::class,
function (ServerStartEvent $e) use ($container, $crontab): void {
// This is done in the listener to prevent a race condition!
$dispatcher = $container->get(EventDispatcherInterface::class),

$e->getServer()->tick(
1000 * 60, // every minute
function () use ($dispatcher, $crontab): void {
$now = new DateTimeImmutable(‘now’)
foreach ($crontab as $job) {
$cron = new CronExpression($job->schedule);
if (! $cron->isDue($now)) {
continue;
}
$dispatcher->dispatch(($job->eventClass)::forTimestamp($now));
}
}
);
},
);

return $provider;
}
}

From there, I could configure jobs:

namespace Mwop;

return [
‘cron’ => [
‘jobs’ => [
‘some-job’ => [
‘schedule’ => ‘*/15 * * * *’,
‘event’ => SomeJob::class,
],
],
],
];

In the final version I extracted a callable class to register with the tick, but still pull that service from the container only within the anonymous function serving as the ServerStartEvent listener, in order to prevent a race condition from trying to pull the event dispatcher service, which then requires the listener providers… which in turn require the dispatcher.
You can see where that’s going.

This approach works brilliantly!

By running the tick every minute, I can evaluate if there are any cronjobs that should run, and, if so, dispatch them.
Since I configure the listeners to run as tasks, they are offloaded into the task worker queue, so that my web workers to not block on them.
Because this is running in the same process group, I don’t have to worry about permissions, and the environment is exactly the same as the web workers.
In many ways, it ends up being a more robust solution than using cron.

Takeaways

Over the years, I’ve seen a number of solutions to running cronjobs from PHP applications.
It’s not uncommon for frameworks and PHP applications to include functionality to periodically run cronjobs after flushing buffers to the webserver.
The key benefits they have is that they share the same environment and permissions as the web server — which is typically useful for application-related jobs — and they don’t require a separate daemon be present on the webserver.
However, I’ve tended to steer away from these, as they rely on the idea that your website is getting regular traffic, and they tie up web worker processes (whether those are mod_php or php-fpm).

Having the ability to offload these to a separate worker pool entirely erases that objection for me.
If all task workers are busy, the task will be processed once they work through the queue.
And no incoming requests will be blocked by this queue or the cronjob itself once it processes.

There is added complexity to the application.
However, by abstracting the cron runner, adding new cronjobs becomes:

Creating a custom event type.
Creating a listener for that event that does the work.
Registering the listener with a listener provider.
Configuring the listener such that it will be deferred.
Adding configuration detailing the schedule and the event.

I don’t have to worry about whether or not I’m running the job as the correct user, whether or not the user has a login shell (web worker users often do not, which adds complexity to setting up your cronjob), whether or not the cronjob operates with the same environment as the application, and so on.
And those last three items are trivial dependency and configuration wiring, so long as they’re documented.

I’m still testing the functionality, but plan to either propose it to mezzio-swoole, or create a package for it.
Since mezzio-swoole is an ideal target for containerized applications, having this functionality will be a nice feature for those who want to provide scheduled jobs with their applications.

Running cronjobs via an Openswoole timer was originally
published 21 January 2022
on https://mwop.net by
Matthew Weier O’Phinney.