JavaScript Design Patterns: The Singleton

Among languages used in widespread production, JavaScript is by far the most quickly evolving, looking less like its earliest iterations and more like Python with every new spec put forth by ECMA International. While the changes have their fair share of detractors, the new JavaScript does succeed in making code easier to read and reason about, easier to write in a way that adheres to software engineering best practices (particularly the concepts of modularity and SOLID principles), and easier to assemble into canonical software design patterns. Let’s dig into that last point by examining how the best way to implement a singleton in JavaScript has evolved with the rise of ES6.

What Is ES6

ES6 (aka ES2015) is the latest specification of the JavaScript language, and the first major update to the language since ES5 was standardized in 2009. Browser support for ES6 is still incomplete, however, ES6 code can easily be transpiled into ES5 code using a tool such as Babel. ES6 gives JavaScript a ton of new features, including a superior syntax for classes, and new keywords for variable declarations. You can learn more about it by perusing Sitepoint articles on the subject.

What Is a Singleton

alt text

In case you’re unfamiliar with the singleton pattern, it is, at its core, a design pattern that restricts the instantiation of a class to one object. Usually, the goal is to manage global application state. Some examples I have seen or written myself in real software development life include using a singleton as the source of config settings for a web app, on the client-side for anything initiated with an API key (you usually don’t want to risk sending multiple analytics tracking calls, for example), and to store data in memory in a client-side web application (e.g. stores in Flux).

A singleton should be immutable by consuming code, and there should be no danger of instantiating more than one of them.

Note: there are scenarios when singletons might be bad, and arguments that they are, in fact, always bad. For that discussion, you can check out this helpful article on the subject.

The Old Way of Creating a Singleton in JavaScript

The old way of writing a singleton in JavaScript involves leveraging closures and immediately-invoked function expressions . Here is how we might write a (very simple) store for a hypothetical Flux implementation the old way:

Continue reading %JavaScript Design Patterns: The Singleton%


Source: Sitepoint

7 Workflows Entrepreneurs Should Automate with Zapier

Zapier integrations

Zapier helps you to build bridges between your favorite apps and services, allowing teams and individuals to automate more of their workflows. Every one-to-one connection made between two apps is called a “Zap” and they’re designed to make you work smarter, not harder. With over 500 apps to choose from, it’s almost impossible to choose only a handful of Zaps.

Let’s take a look at seven Zaps that can make your life easier.

1. Create Mailchimp Subscribers from Typeform or PayPal

PayPal to Mailchimp workflow

Mailchimp is an email marketing service that lets you design emails, maintain a list of subscribers, email those subscribers, and then monitor the results of that campaign. But what happens when a customer isn’t a subscriber?

With this PayPal → Mailchimp workflow, Zapier monitors all sales made via PayPal and enters the customer’s email address into your email campaign in Mailchimp, effectively helping you to retain each new customer.

Typeform to Mailchimp workflow

You can do the same thing with Typeform. Let’s say that you’re using Typeform to survey your website’s visitors about the user experience that they received. The Typeform → Mailchimp Zap will retain the user’s email address in Mailchimp so you can tell that user about the new version of your website, derived from the feedback that they originally offered.

2. Create Trello Cards from Gmail Emails and Update in Slack

Gmail to Trello workflow

With the influx of morning emails it can be near-impossible to convert each one into an actionable task in a sensible amount of time. The Gmail → Trello Zap can fix that, helping you to reach “inbox zero” much faster. In short, Zapier scans your Gmail for emails with a certain label and creates a formatted Trello card from them.

Trello to Slack workflow

You can take this workflow a step further by automatically updating teammates about this new Trello card in Slack, so that the team can be notified about the task and complete it. All that from a simple label!

3. Get Notified of New Dropbox Files in Slack

Dropbox to Slack workflow

I can think of a number of reasons why this Dropbox → Slack setup is epic. Firstly, Dropbox really drains your battery because it constantly checks for file updates, so having notifications in Slack can quite literally save you hours of battery life. But don’t worry, not only can you be notified in Slack of new Dropbox files, but Slack can import the file, making it searchable and downloadable from within Slack. Dropbox doesn’t even need to be switched on!

Continue reading %7 Workflows Entrepreneurs Should Automate with Zapier%


Source: Sitepoint

Review: Is the New and Improved Google Fonts Better?

It’s been six years since Google first unveiled one of the world’s largest, free web font services. Their easy-to-use interface was instrumental in bringing what was often considered a brittle technology to the masses. Since 2010 the service has steadily grown in both library diversity and scale.

Recently the service received a full make-over, bringing a more streamlined way for you to preview fonts and get up and running in no time.

But is it actually better? Let’s take a look.

 <em>Latest website on the left with the legacy site on the right</em>

Latest website on the left with the legacy site on the right

A Polished and Updated Look

I certainly believe that the overall look and feel of Google Fonts has improved. One of the first big things you will notice will be that the whole site uses Material Design. Gone are the thick borders, low-resolution graphics, and bright blue buttons. These are replaced by subtle animations and interactions helping you to focus on narrowing down your fonts.

Google fonts applying Material design

The updates to the visuals are pretty impressive, but what’s also good is that the site is now fully mobile responsive. The previous version of the site didn’t handle smaller resolutions or resizing gracefully, leading to lots of random UI bugs that made the site look weird / remove functionality.

Better Responsiveness

On the right, as the screen gets smaller you can see we lose the ‘Preview Text’ input field making it impossible to get a live preview of our text. Also, as the screen gets narrower the action buttons start to cover up both the font name and the author, eventually vanishing entirely.

The legacy site has been around for a long time and provided a heap of functionality so we can generally cut them some slack. It’s refreshing to see that the new site looks great and works across all device types.

Dynamic Theme Chooser

One area of concern for designers was choosing a font which works well across different foreground / background colors. Sometimes a font might look great when it’s black on a white but then could be next to impossible to read when a bright color is used.

Google added a custom color chooser right at the top of the site. When clicked it provides a quick swatch of colors to let you preview how your fonts will look. You can use this to see how your fonts will pair up when used on dark / light backgrounds with dark / light text.

Dynamic Theme Chooser

Even though you can’t precisely specify the colors you want, this is a nifty tool that everyone should use when picking out their fonts.

Featured Fonts are a brand new introduction to the updated Google Fonts website. Accessible right from the top menu, these featured fonts are collections of fonts that Google wants to highlight. These collections are created by either Google themselves or by outside agencies to showcase a particular design style or philosophy.

Showcasing Featured Fonts

Currently, there are only a few sets of featured fonts, however, it would make sense if this range will increase in time as more fonts are added and the previous Google Fonts website is discontinued.

A Supercharged Inline Font Selector

The main experience with Google Fonts is how to preview and select your fonts, some would argue this is the most important part of the website.

Previously, when viewing your fonts you would see something similar to the diagram below – a simple preview of text with a series of action buttons. Your view might look different depending on how you’ve filtered your search but generally, it’s a simple square box with a series of actions a big blue add button.

Continue reading %Review: Is the New and Improved Google Fonts Better?%


Source: Sitepoint

WordPress Theme Automation With Gulp

As website code becomes more complicated and repetitive steps that just beg for optimization become ever more commonplace, there should be a better and more efficient development process out there.

In this tutorial, I’ll introduce Gulp, and how to integrate it with WordPress theming to automate and enhance the theme development process by putting together an automated workflow.

Why You Need to Automate Your Development Workflow

Workflow optimization can be incredibly beneficial and rewarding for your development process. Here are some of the reasons to give it a go:

  • It removes all those repetitive and boring tasks, replacing them with custom tools.
  • It saves a lot of time for doing other important core development work.
  • It helps optimizes your website for performance by minifying and optimizing all assets.

What You’ll Need

  • WordPress installed on your development machine.
  • Node.js and npm installed.
  • Command line basic knowledge.

Introduction to Gulp

Gulp is a JavaScript task runner that will help automate time-consuming tasks like CSS compressing, Sass compiling, image optimization and browser reloading.

Gulp gives you the tools to do various actions automatically after certain trigger events. For example, consider the following scenarios:

  • Every time you save a Sass file, Gulp will compile Sass and output a minified CSS file.
  • When you add a new image to a folder, Gulp will optimize this image and move it to a new dedicated folder.
  • When you save a PHP or a Sass file, Gulp will automatically reload the browser.

Gulp Setup

First, you need to install Gulp globally in your system. Later, I will show you how to install it as a package inside your theme.

Assuming Node.js is installed, open the command line tool, then install Gulp using npm via:

[code language=”bash”]
npm install gulp -g
[/code]

Now, run gulp -v (Gulp’s version command) to test that Gulp is installed correctly. You should get output similar to:

[code language=”bash”]
➜ ~ gulp -v
[09:33:59] CLI version 3.9.1
[/code]

Theme Setup

In this tutorial, I will use Underscores as the base theme. To download it, navigate to underscores.me, generate a new theme and give it a name like “gulp-wordpress”, download it to the WordPress themes directory, then activate it from the dashboard.

From the command line, navigate to the gulp-wordpress directory where you have added the theme, for example in my case:

[code language=”bash”]
cd ~/www/wordpress/wp-content/themes/gulp-wordpress
[/code]

Next, run the npm init command and follow a few simple steps to create a package.json file which will include some information about the theme and the packages that will be installed later.

After finishing up the steps, you will have a starting file that looks similar to this:

{
  "name": "gulp-wordpress",
  "version": "1.0.0",
  "description": "WordPress Theme Development Automation with Gulp",
  "author": "Name"
}

Next, install Gulp as a development dependency:

[code language=”bash”]
npm install gulp –save-dev
[/code]

A node_modules directory is now created containing Gulp package source files, and your package.json file has been updated to include Gulp as a development dependency.

{
  "name": "gulp-wordpress",
  "version": "1.0.0",
  "description": "WordPress Theme Development Automation with Gulp",
  "author": "Author Name",
  "devDependencies": {
    "gulp": "^3.9.1"
  }
}

Some Gulp tasks like gulp-autoprefixer require ES6-style Promises support so that you can install the es6-promise polyfill, and then require it at the top of the gulpfile.js as we will do next.

[code language=”bash”]
npm install es6-promise –save-dev
[/code]

The last step to configure Gulp is to create an empty gulpfile.js configuration file, which will be used to define Gulp tasks such as JavaScript and Sass.

The gulpfile.js starter file will look like this:

require('es6-promise').polyfill();

var gulp = require('gulp');

// default task
gulp.task('default');

What we have done above is:

  • Required the es6-promise polyfill on top of the file, then we have imported in gulp.
  • Created a default task.

To make sure that Gulp is running and everything is done perfectly, run gulp in the command line to execute the default task created in the gulpfile.js file. The output should be similar to:

[code language=”bash”]
[09:48:23] Using gulpfile ~/www/wordpress/wp-content/themes/gulp-wordpress/gulpfile.js
[16:33:13] Starting ‘default’…
[16:33:13] Finished ‘default’ after 58 μs
[/code]

Speeding up Development with Gulp Tasks

At this point, the theme is ready for new tasks, and it’s time to go through some common tasks that you can use to speed up your theme development.

Working with CSS (Sass)

If you are using Sass to write CSS, two main things needed to be automated, the first one is to compile Sass to CSS, the second is to use autoprefixer to add vendor prefixes to your CSS. Also note that I’m using Sass as an example, if you prefer another option like Less for example, you can find a Gulp plugin for it too.

First, install gulp-sass and gulp-autoprefixer.

[code language=”bash”]
npm install gulp-sass gulp-autoprefixer –save-dev
[/code]

The next step is to create a Sass directory with a basic structure.

├── sass
│   └── style.scss

The style.scss file is the main starting point, you are free to create your Sass architecture and import other components, modules, functions inside it based on your preference.

Continue reading %WordPress Theme Automation With Gulp%


Source: Sitepoint

Desktop Wallpaper Calendars: July 2016


  

To help you start into July freshly inspired, artists and designers from across the globe challenged their artistic abilities and created desktop wallpapers for you to indulge in. This monthly creativity mission has been going on for eight years now, and each month the enthusiastic work of the community brings forth interesting, beautiful, and unique results. Wallpapers that are a little more distinctive than the usual crowd.

Desktop Wallpaper Calendars: July 2016

This post features their designs for July 2016. All wallpapers come in versions with and without a calendar and can be downloaded for free. A big thank-you to everyone who contributed their ideas! Now could there be a better occasion to freshen up your desktop?

The post Desktop Wallpaper Calendars: July 2016 appeared first on Smashing Magazine.


Source: Smashing Magazine

Lessons Learned From Plugin Support


  

A year and a half ago I released my first premium WordPress plugin, Advanced Ads. It’s true that once the plugin was out, my most important task was support. Support is a crucial element that determines not only the success of the project, but also how happy everyone will be, me included.

Lessons Learned From Plugin Support

With this in mind, I constantly optimized my approach to providing support. Let me share with you what I learned. Read on to find out what I learned about support, the four sides that will help you understand each request, which fears of mine proved to be unfounded, what an efficient support system looks like and, last but not least, how to optimize support.

The post Lessons Learned From Plugin Support appeared first on Smashing Magazine.


Source: Smashing Magazine

Elixir’s Ecto Querying DSL: Beyond the Basics

This article builds on the fundamentals of Ecto that I covered in Understanding Elixir’s Ecto Querying DSL: The Basics. I’ll now explore Ecto’s more advanced features, including query composition, joins and associations, SQL fragment injection, explicit casting, and dynamic field access.

Once again, a basic knowledge of Elixir is assumed, as well as the basics of Ecto, which I covered in An Introduction to Elixir’s Ecto Library.

Query Composition

Separate queries in Ecto can be combined together, allowing for reusable queries to be created.

For example, let’s see how we can create three separate queries and combine them together to achieve DRYer and more reusable code:

SELECT id, username FROM users;
SELECT id, username FROM users WHERE username LIKE "%tp%";
SELECT id, username FROM users WHERE username LIKE "%tp%" LIMIT 10, 0;
offset = 0
username = "%tp%"

# Keywords query syntax
get_users_overview = from u in Ectoing.User,
  select: [u.id, u.username]

search_by_username = from u in get_users_overview,
  where: like(u.username, ^username)

paginate_query = from search_by_username,
  limit: 10,
  offset: ^offset

# Macro syntax
get_users_overview = (Ectoing.User
|> select([u], [u.id, u.username]))

search_by_username = (get_users_overview
|> where([u], like(u.username, ^username)))

paginate_query = (search_by_username
|> limit(10)
|> offset(^offset))

Ectoing.Repo.all paginate_query

The SQL version is quite repetitive, but the Ecto version on the other hand is quite DRY. The first query (get_users_overview) is just a generic query to retrieve basic user information. The second query (search_by_username) builds off the first by filtering usernames according to some username we are searching for. The third query (paginate_query) builds off of the second, where it limits the results and fetches them from a particular offset (to provide the basis for pagination).

It’s not hard to imagine that all of the above three queries could be used together to provide search results for when a particular user is searched for. Each may also be used in conjunction with other queries to perform other application needs too, all without unnecessarily repeating parts of the query throughout the codebase.

Continue reading %Elixir’s Ecto Querying DSL: Beyond the Basics%


Source: Sitepoint

Introduction to Developing jQuery Plugins

You’ve probably worked on interactive components before, like sliders, galleries or interactive forms. While you might be creating these on a site-by-site basis, one great time saver is to build your functionality as a jQuery plugin to speed up your development.

jQuery plugins let you define your functionality once and then drop it into your projects as needed, getting you up and running faster.

We’re going to look at how to build your own jQuery plugin. We’ll look at all the areas you need to know to get you up and running building plugins in no time.

We’ll be using a plugin I’ve created called fancytoggle to showcase the different parts of a plugin. It’s a simple plugin for toggling the visibility of nested elements, such as list items, to create accordion-style widgets for things like FAQs. The overall idea is about the concepts of plugins, but this example should help you see how it all works in practice.

See the Pen FancyToggle by SitePoint (@SitePoint) on CodePen.

A Plugin Approach: The Advantages

The core concept here is to create something extensible that you can add to your projects to give you quick functionality. jQuery’s plugin functionality simplifies the process of building reusable code.

One of the strengths of these plugins is that they let the developer define several options that can be used to customize the functionality. You might create several options that change the way your plugin operates entirely, or you might just define a few to give the user a bit more control for styling or layout. With plugins, this choice will be up to you.

Developing jQuery Plugins

Let’s run through the steps needed to register a new jQuery plugin. We’ll use our example plugin, fancyToggle, so you can see how it’s all put together.

Creating our function with $.fn

jQuery plugins work by registering a function with the name you want to call to trigger your plugin (for example, you call jQuery’s inbuilt .width() or .height() functions when you want the width / height returned)

We attach our function to jQuery’s $.fn object to make it available to the global $ object. This registers our function and lets it be called on objects or selections.

//registering our function
$.fn.fancytoggle = function(){
  // ...
};

That’s all there is to it! You now have a new method you can call from jQuery’s $ object. Right now, it won’t do anything, but you can call this method wherever you like, for example on a selector:

//Call fancytoggle on this element
$('.my-element').fancytoggle(); 

You can register as many functions as you want with $.fn, however its good practice to avoid registering more than one function unless the plugin does distinctly different tasks.

Multiple collections and looping

An important thing to understand is that when your plugin is called it might be applying itself to either a single element or to several. For example with our plugin, if we are applying fancytoggle() to several different items we will have a collection to process within our function.

To process each element we just need to loop through the collection using jQuery’s $.each function:

Continue reading %Introduction to Developing jQuery Plugins%


Source: Sitepoint

Introducing the CSS text-align-last Property

Sometimes tiny details that mostly go unnoticed can make or break the user experience. This can include subtle text shadows applied to a headline or proper spacing between different elements on a web page.

The text-align-last property is useful in this respect. It specifies how either the last line of a block or the line right before a forced line break will be aligned. This is important because the last line in a paragraph generally doesn’t have enough text to fill up the entire space. You may or may not notice the changes but it will improve the overall look of your website.

This tutorial will cover all the aspects of the text-align-last property including acceptable values, support and browser specific behavior.

Usage and Possible Values

It is pretty simple to use text-align-last in your projects. Here is a basic snippet to align the last line of text to the right:

.intro-graph {
  text-align: justify; // Required for IE and Edge 
  text-align-last: right;
}

This property has seven possible values. You are probably familiar with the usual left, right and center values. They align the text in the last line to the left, right and center of the container.
The following demo shows the differences between these three values:

See the Pen text-align-last — Example 1 by SitePoint (@SitePoint) on CodePen.

The fourth value, justify, aligns the last line in such a way that the text aligns its left and right edges to the left and right edges of the container. This is achieved by inserting an appropriate amount of space between words when necessary. Depending on the amount of text, you can use this property to completely fill the space on the last line without too much gap between words. The text in the second paragraph is also justified but since the last line only contains one word it is aligned to the left.

See the Pen text-align-last — Example 2 by SitePoint (@SitePoint) on CodePen.

While left aligning the last line of text works for languages that are read from Left to Right (LTR), it will be wrong to do so with RTL languages. In such cases, assigning the values left or right can cause issues when you don’t know the language to be used beforehand.

Fortunately, you can use the keyword start to align the text to the starting position of a line based on the direction of text. This implies that setting text-align-last to start will left align the text of LTR languages and right align the text of RTL languages. Similarly, you can use the value end to align the text to the ending position of a line based on the direction of text. This will right align the text of LTR languages and left align the text of RTL languages.

See the Pen text-align-last — Example 3 by SitePoint (@SitePoint) on CodePen.

The default value for this property is auto. In this case, the text inside the last line is aligned using the value of the text-align property unless text-align is set to justify. When set to justified, the text is justified only if the value of the text-justify property is set to distribute. Otherwise, the text is start aligned.

Continue reading %Introducing the CSS text-align-last Property%


Source: Sitepoint

Disco with Design Patterns: A Fresh Look at Dependency Injection

Dependency Injection is all about code reusability. It’s a design pattern aiming to make high-level code reusable, by separating the object creation / configuration from usage.

Illustration of people's outlines dancing in a disco

Consider the following code:

<?php

class Test {

    protected $dbh;

    public function __construct(PDO $dbh)
    {
        $this->dbh = $dbh;
    }

}

$dbh  = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$test = new Test($dbh) 

As you can see, instead of creating the PDO object inside the class, we create it outside of the class and pass it in as a dependency – via the constructor method. This way, we can use the driver of our choice, instead of having to to use the driver defined inside the class.

Our very own Alejandro Gervasio has explained the DI concept fantastically, and Fabien Potencier also covered it in a series.

There’s one drawback to this pattern, though: when the number of dependencies grows, many objects need to be created/configured before being passed into the dependent objects. We can end up with a pile of boilerplate code, and a long queue of parameters in our constructor methods. Enter Dependency Injection containers!

A Dependency Injection container – or simply a DI container – is an object which knows exactly how to create a service and handle its dependencies.

In this article, we’ll demonstrate the concept further with a newcomer in this field: Disco.

For more information on dependency injection containers, see our other posts on the topic here.

As frameworks are great examples of deploying DI containers, we will finish the article by creating a basic HTTP-based framework with the help of Disco and some Symfony Components.

Installation

To install Disco, we use Composer as usual:

composer require bitexpert/disco

To test the code, we’ll use PHP’s built-in web server:

php -S localhost:8000 -t web

As a result, the application will be accessible under http://localhost:8000 from the browser. The last parameter -t option defines the document root – where the index.php file resides.

Getting Started

Disco is a container_interop compatible DI container. Somewhat controversially, Disco is an annotation-based DI container.

Note that the package container_interop consists of a set of interfaces to standardize features of container objects. To learn more about how that works, see the tutorial in which we build our own, SitePoint Dependency Injection Container, also based on container-interop.

To add services to the container, we need to create a configuration class. This class should be marked with the @Configuration annotation:

<?php
/**
 * @Configuration
 */
 class Services {
    // ...
 }

Each container service should be defined as a public or protected method inside the configuration class. Disco calls each service a Bean, which originates from the Java culture.

Continue reading %Disco with Design Patterns: A Fresh Look at Dependency Injection%


Source: Sitepoint