Thursday, July 20, 2017

How to Write JavaScript-Style Test Watchers in PHP

I didn't start out writing tests for my code. Like many before and since, my "testing" was to write code and refresh the page. "Does it look right?", I'd ask myself. If I thought so, I'd move on.

In fact, most of the jobs I've had have been with companies who don't much care for other forms of testing. It's taken many years, and wise words from people like Chris Hartjes, for me to see the value in testing. And I'm still learning what good tests look like.

Vector icon with eye

I recently started working on a few JavaScript projects which had bundled test watchers.

Here's a great premium video tutorial about test driven NodeJS development!

In the land of JavaScript, it's not uncommon to preprocess source code. In the land of JavaScript, developers write in syntax not widely supported, and the code is transformed into syntax that is widely supported, usually using a tool called Babel.

In order to reduce the burden of invoking the transformation scripts, boilerplate projects have started to include scripts to automatically watch for file changes; and thereafter invoke these scripts.

These projects I've worked on have used a similar approach to re-run unit tests. When I change the JavaScript files, these files are transformed and the unit tests are re-run. This way, I can immediately see if I've broken anything.

The code for this tutorial can be found on Github. I've tested it with PHP 7.1.

Setting Up The Project

Since starting to work on these projects, I've started to set a similar thing up for PHPUnit. In fact, the first project I set up the PHPUnit watcher script on was a PHP project that also preprocesses files.

It all started after I added preprocessing scripts to my project:

composer require pre/short-closures

These particular preprocessing scripts allow me to rename PSR-4 autoloaded classes (from path/to/file.phppath/to/file.pre), to opt-in to the functionality they provide. So I added the following to my composer.json file:

"autoload": {
    "psr-4": {
        "App\\": "src"
    }
},
"autoload-dev": {
    "psr-4": {
        "App\\Tests\\": "tests"
    }
}

This is from composer.json

I then added a class to generate functions with the details of the current user session:

namespace App;

use Closure;

class Session
{
    private $user;

    public function __construct(array $user)
    {
        $this->user = $user;
    }

    public function closureWithUser(Closure $closure)
    {
        return () => {
            $closure($this->user);
        };
    }
}

This is from src/Session.pre

To check if this works, I've set up a small example script:

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

$session = new App\Session(["id" => 1]);

$closure = ($user) => {
    print "user: " . $user["id"] . PHP_EOL;
};

$closureWithUser = $session->closureWithUser($closure);
$closureWithUser();

This is from example.pre

...And because I want to use the short closures in a non-PSR-4 class, I also need to set up a loader:

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

Pre\Plugin\process(__DIR__ . "/example.pre");

This is from loader.php

This is a lot of code to illustrate a small point. The Session class has a closureWithUser method, which accepts a closure and returns another. When called, this new closure will call the original closure, providing the user session array as an argument.

To run all of this, type into terminal:

php loader.php

As a side-note, the valid PHP syntax that these preprocessors generated is lovely. It looks like this:

$closure = function ($user) {
   print "user: " . $user["id"] . PHP_EOL;
};

...and

public function closureWithUser(Closure $closure)
{
   return [$closure = $closure ?? null, "fn" => function () use (&$closure) {
       $closure($this->user);
   }]["fn"];
}

You probably don't want to commit both php and pre files to the repo. I've added app/**/*.php and examples.php to .gitignore for that reason.

Setting Up The Tests

So how do we test this? Let's start by installing PHPUnit:

composer require --dev phpunit/phpunit

Then, we should create a config file:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit
    backupGlobals="false"
    backupStaticAttributes="false"
    bootstrap="vendor/autoload.php"
    colors="true"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="false"
    processIsolation="false"
    stopOnFailure="false"
    syntaxCheck="false"
>
    <testsuites>
        <testsuite>
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>

This is from phpunit.xml

Were we to run vendor/bin/phpunit, it would work. But we don't have any tests yet. Let's make one:

namespace App\Tests;

use App\Session;
use PHPUnit\Framework\TestCase;

class SessionTest extends TestCase
{
    public function testClosureIsDecorated()
    {
        $user = ["id" => 1];
        $session = new Session($user);

        $expected = null;

        $closure = function($user) use (&$expected) {
            $expected = "user: " . $user["id"];
        };

        $closureWithUser = $session
            ->closureWithUser($closure);

        $closureWithUser();

        $this->assertEquals("user: 1", $expected);
    }
}

This is from tests/SessionTest.php

When we run vendor/bin/phpunit, the single test passes. Yay!

What Are We Missing?

So far, so good. We've written a tiny bit of code, and a test for that code. We don't even need to worry about how the preprocessing works (a step up from JavaScript projects).

The troubles begin when we try to check code coverage:

vendor/bin/phpunit --coverage-html coverage

Since we have a test for Session, the coverage will be reported. It's a simple class, so we already have 100% coverage for it. But if we add another class:

namespace App;

class BlackBox
{
    public function get($key)
    {
        return $GLOBALS[$key];
    }
}

This is from src/BlackBox.pre

What happens when we check the coverage? Still 100%.

This happens because we don't have any tests which load BlackBox.pre, which means it is never compiled. So, when PHPUnit looks for covered PHP files, it doesn't see this preprocess-able file.

Continue reading %How to Write JavaScript-Style Test Watchers in PHP%


by Christopher Pitt via SitePoint

Form

Form

Minimal One Pager for designer, Dan Flynn. Nice little touch with the inverted color scheme when you access the off-canvas content area.

by Rob Hope via One Page Love

6 of the Best Free Contact Form Plugins for WordPress

Web forms are essential for common data collection tasks, such as collecting email addresses, visitor information, feedback, surveys and member registrations. Even the humble contact form is usually found on most websites.

At the time of writing, searching for "contact form" on the WordPress Plugin Directory yields 1,533 results! To help navigate the volume of options and cut through the noise, I'll cover some of the most popular, regularly updated and free WordPress contact form plugins available.

Jetpack's Contact Form Module

Jetpack Contact Form

Jetpack is a popular and feature rich WordPress plugin with more than 30 modules. With these modules, you can add different features to your WordPress website depending on your needs.

One of Jetpack’s most commonly used modules is the Contact Form module, which provides a simple and elegant form creator. Jetpack will send an email notification for each contact form response and you can customize the email address to which the notifications will be sent. If you're using the Akismet plugin, every form submission will be checked for spam as well.

If you want to find out more about Jetpack or install it on your site, visit the Jetpack page on the WordPress.org repository.

Continue reading %6 of the Best Free Contact Form Plugins for WordPress%


by Tahir Taous via SitePoint

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

How to Define and Implement a Go Interface

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

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

What Is a Go Interface?

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

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

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

Go Interfaces Best Practices

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

Clear Intentions

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

Dependency Injection

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

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

Factories

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

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

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

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

Testability

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

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

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

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

Using a Go Interface

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

Implementing a Go Interface

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

Here are two concrete implementations of the Shape interface:

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

Base Implementation

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

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

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

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

Here is the output:

Interface vs. Contract

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

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

Conclusion

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


by Gigi Sayfan via Envato Tuts+ Code

Resto

Resto

'Resto' is a free One Page HTML template crafted for a café, restaurant and other culinary needs. Features include sticky header navigation that smooth scrolls to sections, parallax scrolling backgrounds, big image intro slideshow, specials menu, food menu, reservation form, blog/event feed and ends with a contact form with opening times. Really like how they combined fonts Pinyon Script with Open Sans to create stylish section title typography. Cheers ProBootstrap for this generous freebie!

by Rob Hope via One Page Love

How to Create a Facebook Live Show

Want to broadcast a regular live show on Facebook with a co-host? Wondering how to plan all of the logistics for your show? In this article, you’ll discover how to launch a successful Facebook Live show, with or without a co-host. #1: Define the Key Objective, Measurement Tactics, and Success Benchmarks Before you get swept [...]

This post How to Create a Facebook Live Show first appeared on .
- Your Guide to the Social Media Jungle


by Julia Bramble via