Re-Introducing PHPUnit – Getting Started with TDD in PHP

There are a lot of PHPUnit posts on our site already (just check the tag), but it’s been a while since we’ve actually introduced people to it, and the tool has evolved significantly since then.

This article aims to re-introduce the tool in a modern way, to a modern audience, in a modern PHP environment – if you’re unfamiliar with PHPUnit or testing, this post is for you.

Illustration of crash test dummy in front of monitor with graphs

Here we assume you’re familiar with object oriented PHP and are using PHP version 7 and above. To get an environment up and running which has PHP 7 pre-installed, and to be able to follow instructions in this post to the letter without getting tripped up, we suggest you use Homestead Improved. Note also that some command line usage will be expected, but you will be guided through it all. Don’t be afraid of it – it’s a tool more powerful than you can imagine.

If you’re wondering why we’re recommending everyone use a Vagrant box, I go in depth about this in Jump Start PHP Environment, but this introduction of Vagrant will explain things adequately as well.

What exactly is Test Driven Development?

Test Driven Development is the idea that you write code in such a way that you first write another bit of code the sole purpose of which is making sure that the originally intended code works, even if it’s not written yet.

Checking if something is indeed what we expect it to be is called asserting in TDD-land. Remember this term.

For example, an assertion that 2+2=4 is correct. But if we assert that 2+3=4, the testing framework (like PHPUnit) will mark this assertion as false. This is called a “failed test”. We tested is 2+3 is 4, and failed. Obviously, in your application you won’t be testing for sums of scalar values – instead, there’ll be variables which the language will replace with real values at run-time and assert that, but you get the idea.

What is PHPUnit?

PHPUnit is a collection of utilities (PHP classes and executable files) which makes not only writing tests easy (writing tests often entails writing more code than the application actually has – but it’s worth it), but also allows you to see the output of the testing process in a nice graph which lets you know about code quality (e.g. maybe there’s too many IFs in a class – that’s marked as bad quality because changing one condition often requires rewriting as many tests as there are IFs), code coverage (how much of a given class or function has been covered by tests, and how much remains untested), and more.

In order not to bore you with too much text (too late?), let’s actually put it to use and learn from examples.

The code we end up with at the end of this tutorial can be downloaded from Github.

Bootstrapping an Example Application

To drive the examples home, we’ll build a simple command line package which lets users turn a JSON file into a PHP file. That PHP file will contain the JSON data as an associative PHP array. This is just a personal use case of mine – I use Diffbot a lot and the output there can be enormous – too large to manually inspect, so easier processing with PHP can come in very handy.

Henceforth, it is assumed that you are running a fully PHP 7 capable environment with Composer installed, and can follow along. If you’ve booted up Homestead Improved, please SSH into it now with vagrant ssh, and let’s begin.

First, we’ll go into the folder where our projects live. In the case of Homestead Improved, that’s Code.

cd Code

Then, we’ll create a new project based on PDS-Skeleton and install PHPUnit inside it with Composer.

git clone converter
cd converter
composer require phpunit/phpunit --dev

Notice that we used the --dev flag to only install PHPUnit as a dev dependency – meaning it’s not needed in production, keeping our deployed project lightweight. Notice also that the fact that we started with PDS-Skeleton means our tests folder is already created for us, with two demo files which we’ll be deleting.

Next, we need a front controller for our app – the file all requests are routed through. In converter/public, create index.php with the following contents:

echo "Hello world";

You should be familiar with all the above contents. With our “Hello World” contents in place, let’s make sure we can access this from the browser.

If you’re using Homestead Improved, I hope you followed instructions and set up a virtual host or are accessing the app via the virtual machine’s IP.

The project's Hello World screen

Let’s delete the extra files now. Either do it manually, or run the following:

rm bin/* src/* docs/* tests/*

You may be wondering why we need the front controller with Hello World. We won’t be using it in this tutorial, but later on as we test our app as humans, it’ll come in handy. Regardless, it won’t be part of the final package we deploy.

Suites and Configurations

We need a PHPUnit configuration file which tells PHPUnit where to find the tests, which preparation steps to take before testing, and how to test. In the root of the project, create the file phpunit.xml with the following content:

<phpunit bootstrap="tests/autoload.php">
    <testsuite name="converter">
      <directory suffix="Test.php">tests</directory>


A project can have several test suites, depending on context. For example, everything user-account-related could be grouped into a suite called “users”, and this could have its own rules or a different folder for testing that functionality. In our case, the project is very small so a single suite is more than enough, targeting the tests directory. We defined the suffix argument – this means PHPUnit will only run those files that end with Test.php. Useful when we want some other files among tests as well, but don’t want them to be run except when we call them from within actual Test files.

You can read about other such arguments here.

The bootstrap value tells PHPUnit which PHP file to load before testing. This is useful when configuring autoloading or project-wide testing variables, even a testing database, etc – all things that you don’t want or need when in production mode. Let’s create tests/autoload.php:


require_once __DIR__.'/../vendor/autoload.php';


In this case, we’re just loading Composer’s default autoloader because PDS-Skeleton already has the Tests namespace configured for us in composer.json. If we replace template values in that file with our own, we end up with a composer.json that looks like this:

    "name": "sitepoint/jsonconverter",
    "type": "standard",
    "description": "A converter from JSON files to PHP array files.",
    "homepage": "",
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "SitePoint": "src/SitePoint"
    "autoload-dev": {
        "psr-4": {
            "SitePoint": "tests/SitePoint"
    "bin": ["bin/converter"],
    "require-dev": {
        "phpunit/phpunit": "^6.2"

After this, we run composer du (short for dump-autoload) to refresh the autoloading scripts.

composer du

The First Test

Remember, TDD is the art of making errors first, and then making changes to the code that gets them to stop being errors, not the other way around. With that in mind, let’s create our first test.


namespace SitePointConverter;

use PHPUnitFrameworkTestCase;

class ConverterTest extends TestCase {

    public function testHello() {
        $this->assertEquals('Hello', 'Hell' . 'o');



It’s best if the tests follow the same structure we expect our project to have. With that in mind, we give them the same namespaces and same directory tree layouts. Thus, our ConverterTest.php file is in tests, subfolder SitePoint, subfolder Converter.

The file we’re extending is the most basic version of the Test class that PHPUnit offers. In most cases, it’ll be enough. When not, it’s perfectly fine to extend it further and then build on that. Remember – tests don’t have to follow the rules of good software design, so deep inheritance and code repetition are fine – as long as they test what needs to be tested!

This example “test case” asserts that the string Hello is equal to the concatenation of Hell and o. If we run this suite with php vendor/bin/phpunit now, we’ll get a positive result.

PHPUnit sample test positive

PHPUnit runs every method starting with test in a Test file unless told otherwise. This is why we didn’t have to be explicit when running the test suite – it’s all automatic.

Our current test is neither useful nor realistic, though. We used it merely to check if our setup works. Let’s write a proper one now. Rewrite the ConverterTest.php file like so:

Continue reading %Re-Introducing PHPUnit – Getting Started with TDD in PHP%

Source: Sitepoint

Using Polymer in WordPress: Build a Custom Google Maps Component

Web components are a set of standards for creating custom, reusable HTML elements. Polymer is an open-source JavaScript library for building web applications using web components. Created by those clever folks at Google, it provides a number of additional features over vanilla web components and when used with a polyfill, supports the latest version of all major browsers.

In this tutorial I’m going to show you how easy it is to make use of web components and Polymer in WordPress. I’m going to start by showing you how to integrate Polymer into your WordPress install, then I’m going to demonstrate how to add a working Google Maps component to your site’s side bar. This might be useful for any site (e.g. that of a restaurant) which needs to provide visitors with directions to their premises.

After reading, you’ll be able to employ this technique on a site of your own. And you’ll not be limited to a Google Map widget, you’ll be able to choose from the wide range of pre-made components, or even write your own.

As ever, all of the code for this tutorial is available in a GitHub repository.

Why Polymer?

As native support for web components is growing ever better, you might be forgiven for asking if Polymer is still relevant. The short answer to that question is Yes!

Polymer does make use of a variety of web component polyfills—which will hopefully one day full by the wayside—but it is a lot more than that. Polymer is a wrapper around the web components API that allows us to develop and implement new components at a much greater speed than we would otherwise be able. It offers various additional features over vanilla web components, such as one-way and two-way data binding, computed properties and gesture events. It comes with a very polished CLI which can be used for such tasks as scaffolding out a project, running tests, or running a local server, and it can make use of a wide range of pre-built elements, such as the much loved material design elements library.

In short, Polymer is still very relevant. It is a powerful framework, which is used in production by large companies such as USA Today, Coca Cola and Electronic Arts.

Setting Up WordPress

Before we start, we need to setup our environment that is going to be running WordPress. For this tutorial, I’ll be using the ScotchBox Vagrant VM, equipped with some pre-installed tools to kickstart your WordPress installation.

If you have WordPress installed already, or would prefer to use a different method, you can skip this bit. If you need a bit of help with the setup, but don’t want to go the vagrant route described below, try Googling “install WordPress locally” and looking for an up-to-date tutorial.

We start of by making sure that Git, Vagrant and Virtual Box are installed on our system. We can then clone the GitHub repo with ScotchBox’s pre-populated Vagrantfile.

git clone sitepoint-wp-polymer

Now we are ready to run vagrant up. After our machine has booted, we have to remove the default /public/index.php static file and install WordPress.

cd sitepoint-wp-polymer/public
rm index.php
git clone .

Now we have to make a duplicate of the wp-config-sample.php file. Name it wp-config.php.

cp wp-config-sample.php wp-config.php

and edit the following values:

// wp-config.php

// ...

define('DB_NAME', 'scotchbox');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');

// ...

Now you are ready to fire up your browser and visit You will be prompted to enter the admin account credentials and site title. Feel free to fill these out as you see fit.

Using Polymer in WordPress: WordPress installation

Adding the SitePoint Base Theme

So we’ve got WordPress set up, now we need a theme. Out of the box, this will be the Twenty Seventeen theme, but this is pretty generic and includes much more than you normally need. A good alternative here, is to use the SitePoint WordPress base theme.

This theme was created in response to the question “What would the perfect WordPress base theme look like?”. Its features include:

  • No fat. No cruft. Speedy.
  • Minimal design. It’s your job to make it pretty.
  • No ‘cute’ features you never actually use.
  • SEO friendly to its core.
  • Super Mobile-friendly.
  • 100% Open Source and free to use.

The SitePoint WordPress base theme is a great starting point for new projects. It’s mobile friendly, easy to use and 100% free. To follow along with the rest of tis tutorial, head over to the theme’s homepage and download it now.

And while you’re there, you might like to check out the suite of paid themes SitePoint offers, too. These are all built on top of the base theme and include an ecommerce theme, restaurant theme, portfolio theme, business theme and construction theme.

After downloading SitePoint WordPress base theme, unzip it and copy/paste to thewp-content/themes folder. Then create a new folder called sitepoint-base-child, in wp-content/themes. In that directory create a style.css file and a functions.php file.

cd wp-content/themes/
mkdir sitepoint-base-child
cd sitepoint-base-child
touch functions.php style.css

Open up style.css and copy this into it:

 Theme Name:   SitePoint Base Child
 Author:       Almir B.
 Author URI:
 Template:     sitepoint-base
 Version:      1.0.0
 Text Domain:  ab-sitepoint-base

And into functions.php:


add_action( 'wp_enqueue_scripts', 'sp_theme_enqueue_styles' );
function sp_theme_enqueue_styles() {
  wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );

This will enqueue the base CSS from the parent theme.

We just created a child theme, whose role is to implement functionalities on top of the base theme without having to modify the base files. All of the customisations go into this child theme.

One last step is to go to the admin dashboard, then to Appearance > Themes from the main side menu, and click Activate under, Sitepoint Base Child theme.

Using Polymer in WordPress: Activate Sitepoint Base Child Theme

Including Polymer in WordPress

Now that’s done, we have to install Polymer with bower. Make sure you are in the public/wp-content/themes/sitepoint-base-child folder, and then run:

bower init

You can answer with default answer to every question. Next we need to install the dependencies:

bower install --save Polymer/polymer#^2.0.0 PolymerElements/paper-input#2.0-preview

This will install Polymer and the paper-input component, so that we can have a fancy material designed input component out of the box. It is important to use the #2.0-preview tag for the paper input and also for the Google Map element later, as it will not work with the latest version of Polymer (version 2.0) otherwise.

In order to user Polymer, we have to include it using an HTML import, and we will also include the polyfill for web components, so as to support older browsers.

Head to the functions.php file in the child theme, and add an enqueue to the existing enqueue function.


add_action( 'wp_enqueue_scripts', 'sp_theme_enqueue_styles' );
function sp_theme_enqueue_styles() {
  wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
  wp_enqueue_script( 'polymer', get_stylesheet_directory_uri() . '/bower_components/webcomponentsjs/webcomponents-lite.js' );

WordPress does not have an enqueue function for enqueueing HTML imports, but we can hook into the wp_head hook which outputs into the <head> element of the page.


add_action( 'wp_enqueue_scripts', 'sp_theme_enqueue_styles' );
function sp_theme_enqueue_styles() {
  wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
  wp_enqueue_style( 'polymer', get_stylesheet_directory_uri() . '/bower_components/webcomponentsjs/webcomponents-lite.min.js' );

add_action( 'wp_head', 'include_polymer_elements' );
function include_polymer_elements() {

  <link rel="import"
        href="<?php echo get_stylesheet_directory_uri() ?>/bower_components/polymer/polymer.html">
  <link rel="import"
        href="<?php echo get_stylesheet_directory_uri() ?>/bower_components/paper-input/paper-input.html">

That’s all we needed to start using Polymer elements in WordPress. Now let’s create a WordPress widget so we can take this out for a test ride.

Registering a Widget

In order to create a new widget, we will create a new child class from the WP_Widget class and then register it with the widgets_init hook.

Create a new folder in your child theme, name it lib, and add it a file named sitepoint-map-widget.php.

mkdir lib
cd lib
touch sitepoint-map-widget.php

Copy the following into that file:

// lib/sitepoint-map-widget.php

class SitepointMapWidget extends WP_Widget {

  function __construct() {
    // Instantiate the parent object
    parent::__construct( false, 'Google Paper Input' );

  function widget( $args, $instance ) {
    echo '<paper-input raised always-float-label label="Floating label"></paper-input>';

All we did here is create a new child class of WP_Widet and called the parent constructor in order to give the widget a custom name. Additionally, the widget function is the one that does the actual output. For now, we will simply output a <paper-input> element, which is an element from the paper-input-elements collection.

Last but not least, we need to include this new PHP file at the top of our functions.php file:

// functions.php
require_once( 'lib/sitepoint-map-widget.php' );

// ...

and then register a widget at the end of the file:

// functions.php

// ...

add_action( 'widgets_init', 'sp_register_widgets' );
function sp_register_widgets() {
  register_widget( 'SitepointMapWidget' );

Now we can go into the admin dashboard of WordPress. From the main menu, go into Appearance > Widgets, and there you should see a widget named Google Paper Input on the left.

Drag and drop it into the Main Sidebar section to the right, above the rest of the default widgets from the SitePoint Base theme.

Using Polymer in WordPress: Widget to sidebar

Now you can visit the homepage, and on the right side right above the search box, you will see a material design input with a label.

Using Polymer in WordPress: Paper Input

And thus we have concluded Polymer’s Hello, World! example. We’ve covered a lot of ground already—installing Polymer, integrating it with WordPress and including a sample widget, all in just a few lines of code—but in the next section we will take this further and implement our Google Map component.

Continue reading %Using Polymer in WordPress: Build a Custom Google Maps Component%

Source: Sitepoint

10 Elegant CSS Pricing Tables for Your Latest Web Project

Pricing tables are an important tool for businesses promoting and selling their products or services on their website. As such they need to be simple
and attractive in design, to highlight the most important information
about each product or service and to clearly differentiate between available
features, options and costs so that potential customers find it easy and
intuitive to choose the most
appropriate plan for their needs.

Here we’ve compiled a list of the 10 most tastefully
designed CSS pricing tables to be found at CodeCanyon. Some are quite minimalist in
their design, others provide a dizzying range of options, and others still take
a somewhat more creative approach to design and function. No matter what you’re
looking for, you’re bound to find a pricing table here that will suit your

1. Comparative
Responsive Pricing Tables

Comparative Responsive Pricing Tables offers a wide array of
options for designing your pricing tables. Users can select any of 13 unique
designs which they can then customise in variety of ways with a selection of
hover animations, colour schemes, tooltips, etc. These tables, which are fully
responsive, use Font Awesome icons and are also cross-browser compatible.

Customers reviewing this product have described it as a “very
good product that comes with premium service.”

Comparative Responsive Pricing Tables

Best features:

  • 13 unique designs
  • tooltips with text and lists
  • multiple colour themes for each design
  • three types of hover animation
  • and much more

Responsive Pricing Tables
is exactly what you need if you’re looking for feature-rich
design options for creating your pricing tables.

2. CSS3
Responsive WordPress Compare Pricing Tables

CSS3 Responsive WordPress Compare Pricing Tables is a
CodeCanyon bestseller and for good reason. Like Comparative Responsive Pricing
Tables above, it offers a wide range of highly customisable design options from
simple static tables to tables with sliding columns, crossfade animation
columns, various hover features and tables with images. It also offers browsers
support for the six most popular browsers on the market.

Customers like these pricing tables because they say they’re
very flexible and “well designed for any kind of comparison with multiple
adjustment options.”

CSS3 Responsive WordPress Compare Pricing Tables

Best features:

  • admin panel with live configuration
  • 20 predefined colour versions
  • unlimited number of columns and rows
  • ability to set different width values and font sizes for each
  • and much more

A solid performer CSS3
Responsive WordPress Compare Pricing Tables
will hold its place in the
pricing tables market for years to come.

3. Responsive
Multi Style Bootstrap Pricing Tables

Responsive Multi Style Bootstrap Pricing Tables is another
good choice for users looking for pricing tables that offer a wide range of
design possibilities.

Responsive Multi Style Bootstrap Pricing Tables comes with three different attractive designs, and each design can be configured in several different ways
using 20 different colour schemes. Users can decide whether they want to use
the pricing tables with or without Bootstrap.

Responsive Multi Style Bootstrap Pricing Tables

Best features:

  • three different designs
  • 20 colour themes for each design
  • hover effects
  • tooltips
  • Font Awesome icons
  • and much more

Multi Style Bootstrap Pricing Tables
is not a WordPress plugin; however, WordPress
users can purchase a WordPress version.

4. Pure
CSS Responsive Pricing Tables for WordPress

Pure CSS Responsive Pricing Table for WordPress is a
Bootstrap integrated plugin for WordPress that provides users with 15
predefined themes which are easy to use, highly customisable, and provide unlimited
colours and styles to fit into your existing WordPress theme.

Support for the plugin is provided via email and includes answering
technical questions about the item’s features and assistance with reported bugs
and issues.

The Pure CSS Responsive Pricing Table for WordPress

Best features:

  • create unlimited tables
  • drag and drop column and row sorting
  • PayPal integrated
  • Google Fonts supported
  • and much more

Around since 2015, Pure
CSS Responsive Pricing Tables for WordPress
been consistently updated to keep it a crowd favourite.

5. Pricing—Responsive
CSS3 Pricing Table

Pricing—Responsive CSS3 Pricing Table is the latest pricing
table plugin to arrive on CodeCanyon. It’s fully responsive, build on the
Bootstrap framework and compatible with Firefox, Safari, Opera, Chrome, Edge, and
IE10 and IE11 browsers.

These pricing tables are fully customisable but do not offer
a wide variety of styling choices, so will appeal to users looking to create
tables with simple and clean, yet attractive design.

Responsive CSS3 Pricing Table

Best features:

  • responsive and mobile-friendly layout
  • month/year pricing toggle included
  • button CSS3 effect, hover CSS3 effect
  • and much more

With its stripped-back design, Pricing—Responsive
CSS3 Pricing Table
is definitely the newcomer to watch.

6. Great
Pricing Tables Framework

Another newcomer to CodeCanyon, Great Pricing Tables
Framework’s strength is its simplicity and ease of use.

The plug features a responsive design and three style variations.
Like the other plugins featured here, it uses standard HTML5 and CSS3
technology and has wide cross-browser compatibility.

Great Pricing Tables Framework

Best features:

  • easy
    to use
  • responsive design
  • Font Awesome included
  • Bootstrap supported
  • and much more

Pricing Tables Framework
may not offer a
lot of features, but its very clean and simple approach to pricing table design
is definitely its strength.

7. 7
Responsive Flat Bootstrap Pricing Tables

7 Responsive Flat Bootstrap Pricing Tables provides users
with seven distinctly different pricing tables in a minimalist style.

These tables support Bootstrap, with a promised Bootstrap 4
update coming later this year as well as free CSS and jQuery updates in the
future. Customers praise the pricing table’s  “sleek and modern design” that you “can copy and paste
straight onto my site”.

7 Responsive Flat Bootstrap Pricing Tables

Best features:

  • minimalist
  • responsive
  • horizontal
    and well as vertical tables
  • and
    much more

If clean and classic is what you’re looking for, then 7
Responsive Flat Bootstrap Pricing Tables
is the right choice for you.

8. Round
Pricing Tables

Pricing Tables is quite a unique offering among this list of pricing
tables as it offers round pricing tables instead of rectangular ones.

prices are displayed in each circle and when visitors move their mouse over each
circle, the list of features offered is displayed. Customers who’ve bought this pricing table
found that it is an excellent product with “good code” that “doesn’t conflict with
others, and is easy to edit.”

Round Pricing Table

Best features:

  • creative design
  • CSS3 animations
  • Google and Font Awesome supported
  • cross browser support
  • and much more

Pricing Tables
won’t appeal to every user, but for those users with less information to display
and who are looking for a more creative approach to pricing tables, this
pricing table is ideal.

9. Hexagon CSS Pricing Table

The Hexagon CSS
Pricing Table is another pricing table that uses a cool and clever design to bring
a bit of pizazz to your site.

Like Round
Pricing Tables, this pricing table challenges the
tradition pricing tables model, in this case by using hexagons instead of rectangles. Comparative prices are displayed in each hexagon, and when visitors hover over each hexagon, details of each pricing plan
are revealed through any number of different animation effects.

 Hexagon CSS Pricing Table

Best features 

  • 16 different hover styles
  • 12 different colour schemes
  • cool animation effects
  • Google Font and Font Awesome supported 
  • and much more

As is the case with the Round Pricing Table Features, Hexagon
CSS Pricing Table
 will appeal to users who are open to a more creative approach to pricing tables.

10. CSS Pricing Tables

CSS Pricing Tables has been trending recently on
CodeCanyon, probably because users are drawn to its uncomplicated
design. The plugin uses one design but allows users to customise the colours schemes used to create the right look for their site.

CSS Pricing Tables

Best features:

  • responsive design
  • hover effect
  • 361 icons included
  • easy to use
  • and much more

CSS Pricing Tables may not offer enough styling options for many users, but for those looking to get pricing tables up and ready to go in the shortest possible time, these tables are a great choice. 


These 10 elegant CSS pricing tables for your latest web project are by no means the only ones available at Envato
. So if you haven’t found anything here that meets your needs,
we have plenty of other great options on offer.

And if you want to improve your CSS skills, check out our
ever so useful free CSS

Source: Nettuts Web Development

Getting Started With the Flux Architecture in React

Final product image
What You’ll Be Creating

In this tutorial, you will learn about Facebook’s Flux architecture and how it’s used to handle the data flow in React-based applications. We’ll begin by covering the basics of Flux and understanding the motivation behind its development, and then we’ll practice what we’ve learned by building a simple virtual wallet application.

Throughout the tutorial, I will assume you’ve used React before, but have no experience with Flux. You might get something out of it if you already know the basics of Flux and are looking to gain a deeper understanding.

If you are completely new to the React scene, I recommend going through the Getting Started With React course by David East, here on Envato Tuts+. It’s a fantastic course that will get you up to speed in no time.

What Is Flux?

Flux is mainly an application architecture concept developed by Facebook, but the same term also refers to a library that represents the official implementation.

Facebook came out with Flux as an attempt to solve the problems caused by the MVC pattern in their massive codebase. They struggled with issues where actions triggered cascading updates that led to unpredictable results and code that was hard to debug. This may sound familiar if you’ve used MVC frameworks before, as in most of them everything tends to be tightly coupled. Add watchers and two-way data binding to the mix, and you’ve got yourself a proper headache.

My advice is to avoid any attempt at finding common ground between Flux and MVC. It won’t help much, other than amping up your confusion. Flux attempts to solve things differently, and trying to compare it with other patterns won’t help.

Project Setup

If you’d like to follow along with the tutorial, first make sure you have the required software installed. When you have finished, clone the boilerplate branch from the GitHub repository I prepared to accompany this article.

Here are the software requirements and the versions I had installed at the time of writing this article:

  • Git: 2.11
  • Node.js: 6.9
  • NPM: 3.10
  • Yarn: 0.22
  • Your editor of choice

The boilerplate serves as a starting point for the upcoming small project that we will be building, a small virtual wallet app. It contains the Webpack configuration for transpiling the ES6 syntax to plain JavaScript and WDS for serving the files. It also has some CSS component styles so you can jump right into coding.

In order to install all the required dependencies, cd into the project directory and run yarn.

In the next section, you will be setting up the application’s core components before integrating Flux. I haven’t included them in the boilerplate as I believe it would create more confusion. If you’re not interested in building the app, you can skip these steps and jump to the next section.

Components Setup

Start by including the following code inside js/index.js, which serves as the application’s entry point:

For the main <App /> component, create a new file inside js/components called App.js and add the following code:

The <App /> component wraps two other components, one for the form responsible for adding new items and another one for the list of items. To create the <AddNewItem /> component, create a new file AddNewItem.js inside js/components and add this code:

The component bundles some logic for updating the state when the form fields update and also some basic validation. Let’s finish off the components setup by creating the last one inside js/components/ItemsList.js for the items list, using this code:

That’s it! You’re done setting up the project’s components. The great part is that they also come with free styling.

Run yarn start and wait for the bundle to build. If you point your browser to localhost:8080, you should see the app without any functionality.

Next, we’ll cover what Flux is and how you can use it to add functionality to the virtual wallet application.

The Flux Building Blocks

At a high level, Flux breaks down into four major parts: actions, the dispatcher, stores, and views:

  • Actions describe an action that took place in the application.
  • The dispatcher is a singleton registry of callbacks. It acts as a middleman by passing the actions to all the stores that subscribed to it.
  • Stores manage the state and logic needed to update it for specific parts of the application.
  • Views are plain old React components.

In Flux, all data flows in a single direction:

  • Actions are passed to the dispatcher using convenience classes called action creators.
  • The dispatcher sends (is dispatching) the actions to all the stores that subscribed to it.
  • Finally, if the stores care about a particular action that was received (or more), they update their state and signal the views so they can re-render.

Below is a visual representation of this process.

Representation of how data flows in a Flux application


Data is sent “through the wire” in a single direction using plain JavaScript objects called actions. Their job is to describe an event that took place in the application and to transport the new data to the stores. Each action must have a type and an optional payload key that contains the data. An action looks similar to the one below:

The action’s type must be represented by a descriptive and consistent uppercase string—similar to the common convention of defining constants. They serve as unique IDs that stores will use to identify the action and respond accordingly.

A common practice is to define all action types in a constants object and reference that object instead across the application to maintain consistency. Our virtual wallet will support a single action, which adds items to the list—both expenses and financial gains will be treated as a single item—so our constants file will be very slim.

Create an index.js file in the js/constants folder and use the following code to create your first action type:

Actions are passed to the dispatcher using convenience class helpers called action creators that handle the simple task of creating and sending the action to the dispatcher. Before creating our action creator, let’s see what the dispatcher does first and understand its role in Flux.

The Dispatcher

The dispatcher is used to coordinate the communication between action creators and stores. You can use it to register a store’s actions handler callback and also to dispatch actions to the stores that subscribed.

The dispatcher’s API is simple, and it has only five methods available:

  • register(): Registers a store’s action handler callback.
  • unregister() : Unregisters a store’s callback.
  • waitFor(): Waits for the specified callback(s) to run first.
  • dispatch(): Dispatches an action.
  • isDispatching(): Checks if the dispatcher is currently dispatching an action.

The most important are register() and dispatch() as they’re used to handle most of the core functionality. Let’s see how they look and work behind the scenes.

This is, of course, the basic gist. The register() method stores all callbacks in a private _callbacks array and dispatch() iterates and calls each callback stored using the received action.

For simplicity, we won’t write our own dispatcher. Instead, we’ll use the one provided in Facebook’s library. I encourage you to check out Facebook’s GitHub repo and see how it’s implemented.

Inside the js/dispatcher folder, create a new file index.js and add this code snippet:

It imports the dispatcher from the flux library—which was installed using yarn earlier—and then exports a new instance of it.

Having the dispatcher ready now, we can get back to actions and set up our app’s action creator. Inside the js/actions folder, create a new file called walletActions.js and add the following code:

The WalletActions class is exposing an addNewItem() method that handles three basic tasks:

  • It receives an item as an argument.
  • It uses the dispatcher to dispatch an action with the ADD_NEW_ITEM action type we created earlier.
  • It then sends the received item as payload along with the action type.

Before putting this action creator to use, let’s see what stores are and how they fit in our Flux-powered application.


I know, I said you shouldn’t compare Flux with other patterns, but Flux stores are in a way similar to models in MVC. Their role is to handle the logic and store the state for a particular top-level component in your application.

All Flux stores must define an action handler method that will then be registered with the dispatcher. This callback function mainly consists of a switch statement on the received action type. If a specific action type is met, it acts accordingly and updates the local state. Finally, the store broadcasts an event to signal the views about the updated state so they can update accordingly.

In order to broadcast events, stores need to extend an event emitter’s logic. There are various event emitter libraries available, but the most common solution is to use Node’s event emitter. For a simple app like a virtual wallet, there’s no need for more than one store.

Inside the js/stores folder, create a new file called walletStore.js and add the following code for our app’s store:

We start by importing the required dependencies needed for the store, beginning with Node’s event emitter, the dispatcher followed by the ActionTypes. You will notice that below it, there is a constant CHANGE, similar to the action types you learned about earlier. 

It’s actually not one, and it shouldn’t be confused. It’s a constant used for the event trigger when the store’s data change. We will keep it in this file as it isn’t a value used in other parts of the application.

When initialized, the WalletStore class starts by registering the _registerToAction() callback with the dispatcher. Behind the scenes, this callback will be added to the dispatcher’s _callbacks array. 

The method has a single switch statement over the action’s type received from the dispatcher when an action is dispatched. If it meets the ADD_NEW_ITEM action type, it then runs the _addNewItem() method and passes along the payload it received.

The _addNewItem() function sets an id for the item, pushes it to the list of existing items, and then emits a CHANGE event. Next, the getAllItems() and getTotalBudget() methods are basic getters, which we’ll use to retrieve the current store’s state and the total budget.

The final two methods, addChangeListener() and removeChangeListener(), will be used to link the React components to the WalletStore so they get notified when the store’s data change.

Controller Views

Using React allows us to break down parts of the application into various components. We can nest them and build interesting hierarchies that form working elements in our page.

In Flux, components located at the top of the chain tend to store most of the logic needed to generate actions and receive new data; therefore, they are called controller views. These views are directly hooked into stores and are listening for the change events triggered when the stores are updated.

When this happens, controller views call the setState method, which triggers the render() method to run and update the view and send data to child components through props. From there, React and the Virtual DOM do their magic and update the DOM as efficiently as possible.

Our app is simple enough and does not respect this rule by the book. However, depending on complexity, larger apps can sometimes require multiple controller views with nested sub-components for the major parts of the application.

Fitting It Together

We’ve finished covering the major parts of Flux, but the virtual wallet app is not yet completed. In this last section, we’ll review the entire flow from actions to views and fill in the missing code needed to complete Flux’s unidirectional data flow.

Dispatching an Action

Getting back to the <AddNewItem /> component, you can now include the WalletActions module and use it to generate a new action in the _addNewItem() method.

Now, when the form is submitted, an action is dispatched and all stores—one in our case—are notified about the new data.

Listening for Store Changes

In your WalletStore, currently when an item is added to the list its state changes and the CHANGE event is triggered, yet no one is listening. Let’s close the loop by adding a change listener inside the <ItemsList /> component.

The updated component closes Flux’s unidirectional data flow. Note that I skipped including the entire render() method to save some space. Let’s go step by step through what’s new:

  • The WalletStore module is included at the top.
  • The initial state is updated to use the store’s state instead.
  • A new _onChange() method is used to update the state with the new data from the store.
  • Using React’s lifecycle hooks, the _onChange() callback is added and removed as the store’s change listener callback.


Congrats! You’ve finished building a working virtual wallet app powered by Flux. You’ve learned how all the Flux components interact with each other and how you can add structure to React apps using it.

When you’re feeling confident in your Flux skills, make sure you also check out other Flux implementations like Alt, Delorean, Flummox or Fluxxor and see which one feels right for you.

Let me know your thoughts in the comments below, I’d love to know what you think about Flux or assist if you’re having difficulties following the tutorial. If you’d like, you can also reach me on Twitter @hiskio.

Source: Nettuts Web Development

Summer Bliss And August Adventures: Wallpapers To Kick-Start The New Month (August 2017 Edition)



Could there be a better way to welcome the new month as with a tidy desktop and a fresh wallpaper? Well, we’ve got you covered. To help you start into August freshly inspired, artists and designers from across the globe once again challenged their artistic skills to create unique desktop wallpapers for you to indulge in — wallpapers that are a bit more distinctive as the usual crowd.

Desktop Wallpaper Calendars August 2017

All wallpapers in this collection can be downloaded for free and come in versions with and without a calendar — to keep your deadlines always in sight or to stick to your favorite wallpaper even after the month has ended. A big thank-you to everyone who shared their artworks with us! Now it’s up to you to decide which one will become your August companion.

The post Summer Bliss And August Adventures: Wallpapers To Kick-Start The New Month (August 2017 Edition) appeared first on Smashing Magazine.

Source: Smashing Magazine

Twig – the Most Popular Stand-Alone PHP Template Engine

Twig is a template engine for PHP. But isn’t PHP itself a template engine?

Yes and no!

Even though PHP started as a template engine, it didn’t evolve like one, and while we can still use it as one please tell me which version of “Hello world” you prefer:

<?php echo "<p> Hello " . $name . "</p>"; ?>


<p> Hello {{ name }} </p>

PHP is a verbose language, and that verbosity is amplified when trying to output HTML content.

Modern template systems will take away some of that verbosity and still add a fair share of functionality on top. Things like security and debug features are mainstays in modern template engines.

Today, we’re focusing on Twig.

Twig logo

Twig is a template engine created by Sensio labs, the company behind Blackfire and Symfony. Let’s take a look at its main strengths and how can we use it in our projects.


There are two ways of installing Twig. We can use the tar ball available on their website, or we can use Composer, just like we always do and recommend.

composer require twig/twig

We’re assuming you’re running an environment with PHP set up and Composer globally installed. Your best bet is using Homestead Improved – it’ll let you get started in 5 minutes on the exact same machine we’re using, so we’re all on the same page. If you’d like to learn more about PHP Environments, we have an excellent premium book about that available for purchase here.

Before we go any further, there’s something we need to clarify first.

As a template engine, Twig operates both on the front and on the back end of a project. Because of that, we can look at Twig in two different ways: Twig for template designers and Twig for developers.

On one side, we prepare all data we need. On the other side, we render all that data.

Basic Usage

To exemplify the basic usage of Twig, let’s create a simple project. First of all, we need to bootstrap Twig. Let’s create a bootstrap.php file with the following content:


// Load our autoloader
require_once __DIR__.'/vendor/autoload.php';

// Specify our Twig templates location
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');

 // Instantiate our Twig
$twig = new Twig_Environment($loader);

Twig uses a central object called Environment. Instances of this class are used to store the configuration, extensions, and to load templates from the file system or other locations.

With our Twig instance bootstrapped, we can go on and create an index.php file where we will load some data and pass it to a Twig template.


require_once __DIR__.'/bootstrap.php';

// Create a product list
$products = [
        'name'          => 'Notebook',
        'description'   => 'Core i7',
        'value'         =>  800.00,
        'date_register' => '2017-06-22',
        'name'          => 'Mouse',
        'description'   => 'Razer',
        'value'         =>  125.00,
        'date_register' => '2017-10-25',
        'name'          => 'Keyboard',
        'description'   => 'Mechanical Keyboard',
        'value'         =>  250.00,
        'date_register' => '2017-06-23',

// Render our view
echo $twig->render('index.html', ['products' => $products] );

This is a simple example; we are creating an array of products that we can use in our template. Then, we use the render() method which accepts a template name (this is a file inside the template folder that we defined earlier) and the data that we want to pass to the template.

To complete our example, let’s go inside our /templates folder and create an index.html file. First, let’s take a look at the template itself.

<!DOCTYPE html>
<html lang="pt-BR">
        <meta charset="UTF-8">
        <title>Twig Example</title>
    <table border="1" style="width: 80%;">
            {% for product in products %}
                    <td>{{ }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.value }}</td>
                    <td>{{ product.date_register|date("m/d/Y") }}</td>
            {% endfor %}

Opening index.php in the browser (by visiting localhost or, depending on how you’ve set up your hosts and server) should produce the following screen now:

Rendered table

But let’s go back and take a closer look at our template code.

Continue reading %Twig – the Most Popular Stand-Alone PHP Template Engine%

Source: Sitepoint

Grab Our Free Printable Mailchimp Cheat Sheet

Grab Our Free Printable Mailchimp Cheat Sheet

Almost every entrepreneur needs to engage in email marketing at some point. Mailchimp is one of the most popular email marketing tools out there today, and you may find yourself logging in to create campaigns or view data multiple times per week (or day!).

If you need a handy reference for common Mailchimp tasks, SitePoint’s Jacob McMillen has you covered. This one-page cheat sheet provides no-fluff steps for:

  • Setting up an email campaign
  • Creating a sign-up form
  • Creating a mailing list
  • Viewing email performance data
  • Creating an API key

Grab it now!

Continue reading %Grab Our Free Printable Mailchimp Cheat Sheet%

Source: Sitepoint

Building a Better Web with Automated Testing on Real Devices

Automated Testing on Real Devices

This article was originally published on Medium.

My work is entirely dedicated to that of helping people build better, faster and more accessible apps and websites. Running Calibre has given me a lot of insight to the challenges that teams face while building and maintaining their little slices of the web.

Something that has really struck me this past year is how little we as a web industry know about the ways in which people (yep, real people, not other web developers) access the Internet, and tangentially, how antiquated our methods of delivering content to users really are.

Sure, we’ve had some major advances in the last couple of years that are dramatically improving how quickly we can push content down to devices, but ultimately as an industry not much has changed from the core premise of “load the HTML, find the other resources, then load them too.”

Dinosaurs fighting: "Eat Your Vegetablesssss!"

Left: Web developers, Right: Internet users.

Today, global Internet access is somewhere around 46.1%. That is, only half of the population on this beautiful blue marble that we call home will have a rough idea of what ‘pull to refresh’ means. The rest? Well, they’re not connected, so they probably don’t.

If you investigate the growth of the web over the last three years, it won’t take very long to find that Internet access in India has been growing at a rate of which we’ve never seen before.

In 2016 alone, India introduced 106 million people to the Internet, for the first time. To add some perspective, that’s around 290,000 people every day.

That’s growth of about 30% from 2015, and if those numbers are matched again in 2017 (this is highly likely), that’s another 140 million people.

Indeed, only 35% of Indians are online today, and the population is 1.2 billion.

We’re set for tremendous, unprecedented growth for the next few years.


Mobile usage surpassed desktop usage some time during 2014 — 51.3% of devices with an Internet connection, are hand-held. Being that hand-held devices are generally far cheaper (and often just as capable for everyday tasks as their more expensive and less portable counterparts, desktop computers) this does not come as a great surprise.

Looking for more on Jenkins and continuous integration? Check out these great links:

Check out SitePoint Premium for more books, courses and free screencasts.

Data and Connectivity

Last year I did some research to calculate how much mobile data cost in a number of locations around the globe. Taking the local minimum wage, finding the carrier with the largest market share, and finding the best value for money prepaid plan that had at least 500mb of data.

Number of hours worked for 500mb of data: India 17 hours; Brazil 13 hours; Indonesia 6 hours; Germany 1 hour

India topped out the leaderboard. More than 2 days of full time work to get a data plan that we in the western world would consider “maybe ok for your parents”.

It goes a bit further than that too, because even if you can afford to have a device, with a decent monthly data allowance, do not for one second assume that it will be fast.

Average LTE speed: Germany 20.3 Mbps; Brazil 19.68 Mbps; Indonesia 8.79 Mbps; India 6.39 Mbps

Regardless of the average LTE speed, I have more, perhaps shocking news: 60% of the worlds average mobile connections, are 2G.

That isn’t just “2G speeds”, that’s a 2G connection. On your iPhone, you might’ve seen the network advertised as ‘Edge’, and everything … well, it stopped working, right?

You may be thinking, “Well, almost everyone I know has at least a DSL connection … that should be better than the speeds I’m reading here”, and unfortunately, that isn’t quite the case.

The global average Internet connection speed? 7 Mbps. 🤕

Continue reading %Building a Better Web with Automated Testing on Real Devices%

Source: Sitepoint

The Best Markdown Editor for Windows

A box for a typesetter's letters

This popular article was updated in 2017, covering the newest Markdown editors for Windows and reviewing how some older ones have fared over time.

Markdown has become the standard text markup language on the web. It is commonly used in modern CMSs, forums, and authoring tools. It’s cross-platform, easy to understand, and easy to collaborate on.

There are many “flavors” (variations or extensions) of Markdown, with varying names, due to the creators not wanting anybody to use the “Markdown” name for their projects. Forks include PHP-Markdown, PageDown, Parsedown, and Pandoc, to name a few.

Large websites tend to tweak it with additional customizations, and so you’ll also hear names like “Vim-Flavored-Markdown” and “GitHub-Flavored Markdown”. The Stack Exchange network uses Markdown known as Pagedown, and MarkdownSharp on the server side, with bits of PHP-Markdown thrown in.

In this article, I’ll use “Markdown” or “vanilla Markdown” to refer to the original Markdown spec, and I’ll refer to the names of specific flavors when describing extended features.

Looking for more on Markdown? Check out these great links:

Check out SitePoint Premium for more books, courses and free screencasts.

Syntax Flavors

No single program covers every style and syntax of Markdown, but you’ll always get the basic Markdown syntax as a starting point. SitePoint itself asks authors to use classic Markdown for article submissions and links to the main project’s website here for learning it.

An initiative to make an official specification comes from CommonMark. A couple of the editors below support it, and I have hopes we’ll get a common universal standard some day to avoid having so many flavors.

The point is, make sure the editor you choose supports the specific syntax you want to work with most!

Multiple Editing Styles

These apps are quite different from each other in how they look and feel. During my testing of these seven tools, it became clear that no two did things the same way, leaving me with little more than general opinion on which I like best.

In this article, I won’t be reviewing online editors such as Dillinger, Markable or StackEdit. My focus here is just on apps you can run on your Windows machine.

I found these to be the primary feature differences in the editors:

  • supported syntax and extensions
  • syntax highlighting and/or WYSIWYG features
  • live preview window (split screen)
  • export options
  • syntax helpers, toolbars, shortcut keys, etc.
  • free and/or paid options

In no particular order, here are my opinions after using each editor for some time.


Texts is a Windows and Mac editor that looks a bit like the Windows editor Notepad. It has a clean, single-pane interface with no live preview. There is one simple toolbar that can be toggled on or off.

You don’t see raw code in Texts, as it formats the code in traditional WYSIWYG style. This is the only editor in this lineup that hides the syntax code from you.

Texts isn’t free. It starts with a trial and then costs $19 for each user in a team or as a single license. This is down from $30 in my previous review.

Texts uses Pandoc, which means Pandoc must be installed for certain features to work.

Texts caters more to WYSIWYG users who want to export their documents into PDF, Word, HTML5, ePUB, etc. It includes Tex for math formulas, and some special handling of ad-hoc hyperlinks, footnotes, and tables. Other advanced features are support for Unicode, OpenType fonts, and presentation mode.

Exporting to PDF also requires an install of XeLaTeX.

Personally, Texts did not fit my preferred writing style and was quirky to me in how it processes styles and hides the raw markup as I type it.

A screenshot of the Texts editor

If you want a vanilla Windows or Mac app, a WYSIWYG writing style, and good exporting options, Texts could be just the ticket. It also has some interesting features like shifting paragraphs, “paste-as” options, and an “insert bibliography” feature.


WriteMonkey focuses on the “clean” and distraction-free UI. The interface has almost nothing on it, and it’s designed to be used full-screen. A right-click will pull up all the program’s extensive options, including file and folder view, table of contents, bookmarks, and so much more. It’s a single-pane editor that doesn’t hide the Markdown source. Minimal syntax highlighting can be enabled if desired; otherwise you see plain text.

Supported syntax includes Markdown Extra, Textile, and WikiCreole.

This editor is best for Markdown experts who don’t want or need WYSIWYG styles to get work done, but who also like to tinker for the perfect editing experience. Anything from precise margins and zoom to typewriter sounds and scrolling effects can be changed. It counts just about everything in the document, even your top used words.

You can set timers for how long you want to edit, or character or word limits so you don’t write too much!

Other cool features include text replacements, auto-backups, and word lookups.

WriteMonkey is a free, Windows-only, standalone application that requires Microsoft .NET 4.0. You can, of course, run it from a USB drive, and this is the only editor in the lineup which is standalone.

It supports extensions as well as language packs for many different translations. Extensions are only for people who donate to the project and include things like a thesaurus and Pomodoro timer.

WriteMonkey is a tinkerer’s editor. The plugin engine is JavaScript, and you can even customize the UI itself for theming and placing what you like on the info bar.

The left/right margins can be adjusted within the window. As shown in the image below, I shifted the writing area to the left:

The writing area in WriteMonkey

Below are pictured some of the available features in the main right-click menu:

WriteMonkey options

Even looking at my progress, there are many options to play with:

And more WriteMonkey options

WriteMonkey might have been my top editor, if not for the fact that I enjoy having a bit more in the visual styling of the Markdown itself, and I’m not as big into the endless tinkering and advanced features. If you’re on Windows and want a standalone app that’s free, this is for you.

Continue reading %The Best Markdown Editor for Windows%

Source: Sitepoint

10 Things You May Not Know WooCommerce Can Do

Just like WordPress itself is capable of transforming into many forms, so is WooCommerce.

WooCommerce is a great plugin for running a web store on WordPress, however, it is not just a web store, it is quite a versatile plugin that can be used for a variety of other purposes.

The reason WooCommerce can do so many things is that it has an excellent built-in payment engine, which other plugins can tap into. So even if you’re not actually selling products, you can still use this engine and its many different payment methods.

Transforming your WooCommerce website into something different is done by using additional plugins or extensions as they are often called.

In this article, I’ll cover 10 different WooCommerce extensions to give you some ideas of what you can do with WooCommerce, with one recommended plugin for each purpose. Feel free to Google around and see if there’s an alternative plugin that may better suit your specific needs.



Demo: The WC Resort & Spa
Plugin: WooCommerce Bookings

Whether you are selling hotel rooms like in the demo, or tickets to your very own stand-up comedy show, using a bookings plugin takes care of it. It uses a date and time calendar to allow visitors to select the time they want to place a booking.

The plugin is quite ingenious by giving you enough ways to control your calendar, preventing over bookings or no shows. You can even have a customer check availability with you first. The plugin also takes care of the invoicing, using the WooCommerce payment option.



Demo: Sellxed WooCommerce Subscription Demo
Plugin: WooCommerce Subscriptions

Subscriptions are used for allowing recurring payments. This plugin is simple yet powerful to sell subscriptions for newspapers, online access, products etc. It even synchronizes with many popular payments gateways. So when a customer cancels his subscription with the provider itself, the subscription gets cancelled in your store as well.

It doesn’t matter if you are selling physical or online products with monthly or yearly subscriptions. As long as it is recurring, this plugin will fit the bill.



Demo: –
Plugin: Groups for WooCommerce

WordPress already has an excellent Groups plugin which can be used to define membership levels. Combine that with the Groups for WooCommerce plugin and you can begin selling paid memberships. Add the aforementioned Subscriptions plugin and you can even sell recurring memberships.

Paid memberships are very popular with mastermind or study groups. This way a new member needs to pay for a membership, after which they get access to the premium content the author is providing. Coupled with subscriptions, the author is assured of a recurring income from their group.

Continue reading %10 Things You May Not Know WooCommerce Can Do%

Source: Sitepoint