Electron and Angular2: simple App example

In our first post about Electron, we were covering the main topics about what is and how it works. This time we will cover how to create a dummy application using Electron and Angular2 as a front-end framework.

The application tree should be something like this picture:

tree

we can observe:

  • gulpfile and package.json: we will talk later about this 2 files, by now we can just say that are needed to build the application.
  • assets: The package.json is a file useful to give directives to Electron, with this method we can order show/hide the window borders, icon, maximized/minimized, etc.
  • frontend: here we got the content relative to the front end, more especifically all the Angular2 stuffs.
  • main: contains the index.js referenced by assets/package.json and is the start point of our electron application.
  • Tsconfig and typescript files are needed to transcode the typeScript code into javascript.

The main gulp tasks needed to build and “deploy” the application sources:

gulp_file_main_tasks

from this file, the most important tasks are frontend and electron. The first one copy all the content from the source path.

The principal Electron tasks to run the application:

main_electron_gulp_tasks

 

The  second task begins the transcoding and building of the application.

   The electron package.js, it is useful to pass directives at start time, the format of  is exactly the same as that of Node’s modules, and the script specified by the main field is the startup script of your app, which will run the main process. An example of your package.json might look like this:

package_electron

   We need to remember, if the main field is not present in, Electron will attempt to load an “index.js”.

The main index file loaded by electron at first time looks like a common js file:

main_electron

Then, the final product, the application up and running:

app_running

    we realize that is a common web application, the tick here is to work in the look & feel to “hide” that common details (relative to the chromium browser) and make an effort in order to show the appplication like a elaborated desktop app. It is possible to change icon, task bar, menus, system buttons etc. Even if you don’t like the squared and classical window you can hide the background and create a “floating” app with alpha and the shape you want.

   In the sample app we’ve created a minimal environment with an image background and a button in the middle. If you press the button, you will get as result a notification at the notification area, that position will be according to the SO where the app is running, in my case Im running ElementaryOs so the notification area is in the upper-right conner:

notification_electron

The cool part here is, that notification is executing in real native code. The Electron API does the hard work to communicate to the SO what we are trying to do, in our case, show a notification with a text and image.

That’s all for this second part of Electron, you can download the code from here thanks for reading!

 

Unit testing your Javascipt with Jasmine, KarmaJS & Travis CI

Unit testing is an important part of any software project but until recently it was difficult to test your front-end javascript and oft neglected by developers. Using Jasmine, Karma and TravisCI we will show you how to painlessly automate your JS testing.

Javascript is used on over 93% of websites today and used to do all sorts of front end magic. Most likely, your interactions with the web are provided via Javascript.

With any luck you have moved beyond the anti-patterns of yore and you have abstracted your JS functionality into some coherent objects to maintain your sanity. Now it’s time to start testing these pieces of code.

Testing Tools

I explored javascript unit testing using three tools: Jasmine, Karma and TravisCI. Using all three in conjunction seems to get the best results for a larger team.

Jasmine

Jasmine is a very popular javascript unit testing framework, very similar to many other xUnit testing frameworks like phpUnit and jUnit. Many other testing tools like actually use the same syntax (if not use Jasmine outright) so this is a pretty good thing to learn about.

I should note, unlike many other xUnit frameworks, Jasmine is BDD or a Behavior Driven Development framework. This is a fancy way of saying you structure your test suites in a way where you test ‘behavior’ scenarios rather than simple methods and functions.

KarmaJS

Karma is a test runner that executes your unit tests in a ‘real browser’. In short, it runs your Jasmine tests in a real browser via websockets.

This means you can test using a headless browser like PhantomJS or a real browser like Chrome. This really becomes useful when you need to test in multiple browsers, but especially useful when you need to run your tests locally (via Chrome) or remotely on a CI (in our examples below we run the unit tests using Chromium. More on that later).

There’s a little setup involved with Karma, but not too much. Honestly, it took less time to get my Karma config created than it did to write my example unit tests.

Travis CI

Travis CI is a hosted continuous integration tool that will watch your repo and execute your tests on certain conditions like a push or a pull request. It is also is free for your open source, or at least your public, Git Hub repos. Best of all, you can also show a super cool ‘build status’ badges in your github readme page.

Travis CI: Using Chromium

Please note that if you run your KarmaJS tests locally using Chrome, you will need to make sure Travis CI knows to use the open source equivalent Chromium as it fit’s into its ‘free tier’ licensing scheme.

Below are the key things you need to set this up, all of this code can be found in our examples below:

.travis.yml config

We need to tell Travis to install the Chromium browser package when it creates the container. Add the noted entry (‘export CHROME_BIN=chromium-browser’) into the “before_install” section of your travis config.

...
before_install:
 - export CHROME_BIN=chromium-browser
...
karma.conf.js

Next we need to determine if our tests are executed by Travis, and if so, tell Travis to use Chromium (which is aliased to CHROME_BIN from our config above) when exec’ing our tests:

// Config values to allow TravisCI to run chrome in it's container
browsers: ['Chrome', 'ChromeCanary'],
   customLaunchers: {
   // tell TravisCI to use chromium when testing
   Chrome_travis_ci: {
      base: 'Chrome',
      flags: ['--no-sandbox']
   }
},

...

// Detect if this is TravisCI running the tests and tell it to use chromium
if(process.env.TRAVIS){
   config.browsers = ['Chrome_travis_ci'];
}

I think its easiest to look at config from our example code to see exactly where this is placed in your config: https://github.com/arroyolabs-blog/movie-vote/blob/master/karma.conf.js

Example Project: Movie Vote

I created a very basic ‘web app’ (this is a stretch) to learn more about using Jasmine/Karma/CI with javascript.

It’s a simple JS class where a user can up or downvote a movie. While it includes a very basic html page you can run in your browser to see the class in action, the real magic is in the testing.

Here is a link to the Travis CI page showing our passing tests: https://travis-ci.org/arroyolabs-blog/movie-vote

Example Project 2: ng2 3 page SPA

If you are using ng-cli, karma is already configured for you. Running it is super easy and the hardest part is finding a CI solution that works for you.

Check out our super simple example and review the Travis Config to see this in action: https://travis-ci.org/arroyolabs-blog/effective-funicular

Conclusion

Testing is a very important part of software development and can be fun and easy once you get things set up to run automatically. Hopefully after reading this post you will have a good idea of how to integrate unit testing into your JS projects.

Go basics – Control Structures

Hello readers, in this episode we’re going to talk about languages structures, as a preface to future post where I will show you all this stuff in action, with OOP and concurrency examples and reviewing some toolkits and frameworks.

Of course, this is not an exception, on each topic of this post I will show you an example of how it can be used and a comparison with languages to make it easy to understand for those whom come from PHP, C, Java, etc.

Loops and Bifurcations 

For

Go has only one looping construct, the for loop.
The basic for loop has three components separated by semicolons:

– the init statement: executed before the first iteration
– the condition expression: evaluated before every iteration
– the post statement: executed at the end of every iteration

The init statement will often be a short variable declaration, and the variables declared there are visible only in the scope of the for statement.

The loop will stop iterating once the boolean condition evaluates to false.

Note: Unlike other languages like C, Java, or Javascript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.

Following there’s some examples that shows each variation with its equivalent in PHP:

While loop in GO
var counter int = 0

for counter < 100 {

    counter += 1

}
PHP Version
<?php 
while($counter < 100){ 
     $counter++; 
}
 Foreach in Go
import "fmt"

for key, value := range list {
    fmt.Printf("%d => %s\n",key, value)
}
PHP Version
<?php 
foreach($list as $key=>$value){     
    echo "{$key} => {$value}\n"; 
}
Common For loop in Go looks like C
for i := 0; i < 10; i++ {
	fmt.Println("The value of i : ", i)
}

If-else

The if statement in Go, like For statement, does not need to be surrounded by  ( ), but the braces { } are required.

Like for, the if statement can start with a short statement to execute before the condition.

Variables declared by the statement are only in scope until the end of the if.

As many other languages, it support the else statement.

 Chained if statement in GO
if value, ok := m[key]; ok {
    fmt.Println("value is:", value)
}
PHP Version
if( isset($_POST['id'])) {
    $id = $_POST['id'];
}
If-else in Go
if _string == "my example" { 
    fmt.Println("this is ",$string) 
} else {
    fmt.Println("this is no my string") 
}
If-else in PHP
<?php
if($_string == "my example"){
   echo "this is ".$string;
} else {
   echo "this is no my string";
}

switch

This is a multiple choice statement that allows us to select between more than two options, and most of the time faster than if-else.

The differences against other languages is that each case body breaks automatically, unless it ends with a fallthrough statement,

and Switch without a condition is the same as switch true.

This construct can be a clean way to write long if-then-else chains.

Switch in Go
switch i {
	case 0 : fmt.Println("Zero")
	case 1 : fmt.Println("One")
	case 2 : fmt.Println("Two")
	case 3 : fmt.Println("Three")
	case 4 : fmt.Println("Four")
	case 5 : fmt.Println("Five")
	case 6 : fmt.Println("Six")
	case 7 : fmt.Println("Seven")
	case 8 : fmt.Println("Eight")
	case 9 : fmt.Println("Nine")
	default : fmt.Println("Unknown Number")
}
Switch in PHP
<?php

switch $i {
	case 0 : 
               echo "Zero";
               break;
	case 1 : 
               echo "One";
               break;
	case 2 :
               echo "Two";
               break;
	case 3 : 
               echo "Three";
               break;
	case 4 : 
               echo "Four";
               break;
	case 5 :
               echo "Five";
               break;
	case 6 :
               echo "Six";
               break;
	case 7 : 
               echo "Seven";
               break;
	case 8 : 
               echo "Eight";
               break;
	case 9 : 
               echo "Nine";
               break;
	default : 
               echo "Unknown Number";
}

Functions

Functions are defined using the keyword func followed by the function name, arguments and the return values.

func say_hello() {
    fmt.Println("Hello From the function")
}

Parameter

Functions may have a return value. This value can also be named.

Simple function in Go
func Add(first, second int) (result int){ 
    return first + second 
}
Same example in PHP
<?php
function add($first, $second) {
   return ($first + $second);
}

Multi-types result

This is one of Go goodies that does not has equivalence in other common languages like PHP or C. In Go we can return multiple values of different types, also naming each returned parameter. Let me show an example:

func divide(n,d int) (result float, err error) {
    if d == 0 {
        err = errors.New("")
    } else {
        result = n / d
    }
    return result, err
}

Variadic

Functions can take 0 to undefined variables of a particular data type.

func sum(args ...int) (total int) {
	total := 0
	for _, i := range args {
		total = total + i
	}
	return total
}

Closure

Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

func Sequence() func() int {
    i := 0
    return func() int {
        i += 1
        return i
    }
}

nextValue := Sequence()

fmt.Println(nextValue()) // 1
fmt.Println(nextValue()) // 2
fmt.Println(nextValue()) // 3
fmt.Println(nextValue()) // 4

Do not miss the second part of this post where we will use this concepts while discuss OOP and concurrency.

Moving to Slim PHP

After developing Erdiko for over 4 years we are making some big changes for the next major release. We are modifying the framework to support Slim. Erdiko will soon be built on top of the great features of the Slim PHP micro framework.

We have been developing our open source micro framework for 4 years now.  We haven’t publicized it much but we’ve poured hundreds of hours into it and use it considerably on client projects. The framework and many of its modules are used and liked in the PHP community.

We are ready to take Erdiko to the next level and in the process of architecting a new Erdiko framework.  The next version will be more modular, better tested and, most importantly, built on top of an existing micro framework.

When we started Erdiko the other micro frameworks weren’t there yet, thats part of the reason we start Erdiko.  Silex and slim were in infancy, lumen didn’t exist (and Laravel was just starting to get more notice), and heck composer was less than a year old and wasn’t on many people radar yet.  Fast forward a few years and we now find a very different landscape for PHP and JavaScript development.

Speaking of this landscape, the fact that we can and do move much of the app to the front-end with powerful JavaScript frameworks means the duty of the back end has changed.  You no longer need to add ridiculous layers of front-end logic in your PHP classes and templates.  This shift alone means you need to rethink what you need from a php framework.

Thats where micro frameworks soar…places where you need a fast backend and leveraging a smarter front-end (e.g. SPA with JavaScript).  Add the great SaaS tools at your disposal as well and you have all the ingredients to make performant websites that you can grow your business with.  You don’t need a big bloated full stack in most cases.  If you do, often the built in feature X just won’t cut it and you end up integrating a 3rd party package or writing that component yourself anyways.

Now back to the topic at hand, what’s the deal with SlimPHP?  After reviewing numerous frameworks it became apparent that SlimPHP was the best of bunch for the kind of code we like, community we like and of course the kind of features and performance we like.  It’s router, http objects and flexibility has Erdiko beat.  We also looked at and experimented with Silex, lumen and some others before making the decision.

Erdiko adds the MVC and theming support to a typical micro framework.  We’ve developed some useful components and feel that adding these on top of an existing framework will make development even more efficient and flexible.

Erdiko has some special features that will aim to make development more enjoyable and lead to better applications.  We have been distilling pieces of Erdiko that will be moved and improved to work with Slim.  Right now we feel the configuration, theme engine and controller support will make the cut.  Actually quite a bit of erdiko will exist in the new framework, but we will strive to leverage slimphp and the slim paradigm whenever possible.  On the model side we have included wrappers for powerful ORMs so that developers can pick the best one for the job and install with one command.

Electron and cross-platform applications

These days with the latest new technologies applied to apps we want everything faster, accessible and lightweight. To accomplish these goals, companies find that the developers do their job with tools that  require  low effort and can be used in many places.

Then, developers went to work and improve a kind of automatic programming with open source. For this reason, developers at Github started to work on developing something quick and comfortable without the need to learn another programing language. They wanted a framework to get a piece of product without reworking the same application on multiple platforms.

Chromium and the open source

Cheng Zhao, Electron’s director, realized the advantages of Google Chromium and their open source, at the beginning developed by Google Inc. to the community of developers who needed their own browser, without realizing about the potential which was delivering to Github’s developers. Later on, they started working on that for long weeks to get the Chromium core.

Finally, with the job done and successfully tested, it was launched in April of 2015. A few months later, Microsoft launched Windows10 with the possibility of installing applications from the Windows store (web based) then. For that reason, they believed in the great potential of this project.

But, what is Electron?

Electron is an open source project (GNU) written by  Cheng Zhao, an engineer working at GitHub  in Beijing  for the Atom text editor team. Its combines Google Chromium and NodeJS´s features in one codebase. Because of that, Electron updates with their releases. Under the hood, together they share the same Javascript engine V8, and it means that we, as developers, could use both context at the same time (something that, with a regular web app would be impossible)

NodeJS has supported Mac, Windows and Linux equally from the version 0.6 and Google Chromium is also cross-platform. The Electron’s API philosophy is that it only adds features supported by all platforms.  For example, on Windows, applications can put shortcuts in the JumpList of task bar, and on Mac, applications can put a custom menu in the dock menu. Electron conveniently allows developers to send notifications with the HTML5 Notification API, using the currently running operating system’s native notification APIs to display it.

Forget to develop one web application written in asp.NET and another one in C# for desktop, now with Electron you can develop only one NodeJS application and rebuild for desktop platform. Besides, it is an open source and you can improve some aspects such as performance or your custom features.

The project at present.

The team released Electron when they launched Atom two years ago, known as Atom Shell, the framework they’d built Atom on top of. In those days was the ‘driving force’ behind the features and functionalities that Electron provided as they pushed to get the initial Atom release out.

Today as a dedicate project, Electron is a growing community of developers and companies building a lot of apps (just in the past year it has been downloaded over 1.2 million times) and releasing the mature 1.0 version.

electron-downloads

In the last times Electron has since been used to create applications by companies as Microsoft, Slack, Docker etc. we can inspect a few of them here.

Angular2 and the future of HTML5 on desktop

  • The main process  provides platform specific API’s and taking care about the application lifecycle
  • Meanwhile the render process  provides functionality for the user interface, in this case Chromium with all it’s advantages such as Chrome Developer Tools available right inside of your desktop app.
  • Angular2 currently has become one the most popular open source javascript frameworks in the world:
    – Its modular so we can choice what part of Angular use
    – its modern, is targeted on ES6 and “evergreen” modern browsers, no hacks or workarounds are needed, allowing developers to focus on the code related to their business domain.
    – its focused on mobile devices which means that we can port a current mobile applications to desktop just wrapping up in Electron.

Looks like Electron + Angular2 is a pretty good combination.

In the next post about Electron we will make a real code basic application to demonstrate the use of this nice stack.

My two cents

There are a lot of good features but here are some collected pros and cons:

Pros:

  • No cross-browser compatibility issues
  • No loading of remote assets (then no latency)
  • Reuse of npm modules, out of the box
  • hardware access
  • Native-ish features (system dialogs, file selection dialogs, notifications, printer, etc)

Cons:

  • The size, the Electron API Demos for linux compress takes 41MB (it could be worst, giving account that is a complete and customizable browser).

Shadow DOM

The Shadow DOM is a way to create elements that are not affected by the same attributes and properties as those in the Light DOM. The Shadow DOM provides true scope encapsulation; your element’s CSS and JS are scoped to it alone! Think of the Shadow DOM as a lightweight version of an iframe.

The DOM is what most people are talking about when they are talking about a web page’s elements rendered in your browser. The DOM, or the Document Object Model, is the API that allows a web browser to interact with and render the HTML, CSS and Javascript to create a webpage.

When you think about creating a web page, we typically think about the HTML elements we structure and style and interactive with using CSS and JS. For the sake of simplicity, we will call the elements you see rendered as the Light DOM.

The Shadow DOM by contrast is a way to create elements that are not affected by the same attributes and properties as those in the Light DOM. The Shadow DOM provides true scope encapsulation; your element’s CSS and JS are scoped to it alone! Think of the Shadow DOM as a lightweight version of an iframe.

To render elements created via the Shadow DOM, you must ‘inject’ them into the Light DOM. We’ll cover some examples of this later in the post.

You have already seen the Shadow DOM

You might not even be aware, but you have already seen the Shadow DOM in action already. A lot of complex input elements rendered in the browser are actually created via the Shadow DOM due to the encapsulated styling and javascript scope.

The most common example is the Video Tag. Take this simple example tag:

<video src="Clipped_Red_Lexus.mov" controls></video>

This simple tag results in the following rendered HTML in your browser:

video_tag_example

Notice how much “extra” HTML is rendered under the “#shadow-root”. This code is generated by your browser automatically to give you these complex UI elements like the Play Button and the Volume Slider.

These elements have their own styling and event listeners that are not affected by the host DOM.

Why should we care about the Shadow DOM?

Using the Shadow DOM you can create truly re-usable pieces of code you know will act reliably no matter where you place them. Create one widget, and use it in any of your code, and stop worry about CSS and JS collisions!

Also, most importantly, the Shadow DOM is the base from which the modern web is being built upon.

When we talk about web components, we are talking about the implementation of the Shadow DOM. When you see those fancy ‘live’ updating forms in Angular2, again, Shadow DOM.

Clearly, understanding this is quite important to understanding these new web frameworks.

Example 1: Inserting Elements into a Host Root

Here is a very basic example illustrating using the Shadow DOM to inject elements into a host root.

Example 2: Isolated styles in a Shadow DOM Element

Here is a very basic example showing the isolated CSS styling when using the Shadow DOM.

Please note the injected element’s CSS does not affect the CSS in the host element. Only the injected elements are red.

Example 3: Insertion Points with “content” tags

Here is an example showing insertion points and querying using the content tag. (Please note, that in Shadow DOM v1, the content tag will be replaced by the slot selector, read more about this below in “Whats Next”)

This simple example shows how one can select some content from the host element, inject it into the Shadow DOM template, which in turn get injected into the host DOM.

Whats next?

We reviewed some concepts about the Shadow DOM laid out in what is commonly referred to as “Shadow DOM v0”. This is to say we are working with the very first iteration of the implementation.

The new spec for v1 has, for the most part, been agreed upon and the major browser publishers are working on implementing the new features.

Hayato Ito at Google has a great list explaining some of the changes we can expect along with simple examples showing these new features.

Conclusion

While I provided only simple examples of the Shadow DOM, I hope this inspires you to explore more yourself. Thanks for reading!

Go basics – Data Types

Today we are going to walk thru basics of Go language. Starting with a list of supported data types and defining custom types.

I’ll try to show you some examples of how to deal with basic Go stuff and compare with PHP as a reference.

Data types

Integer

Integers are numbers without a decimal component. Go lang support four types for integer based on the amount of bits can address, and three  extra types based on machine architecture.

Since computers use a base-2 for representation, 8, 16, 32 and 64 tell us how many bits each of the types use. Then for the first sub set of integers Go also split them on signed and unsigned.

Signed Integers: int8, int16, int32, int64.

Unsigned Integers: uint8, uint16, uint32, uint64.

Also, a byte is an alias for uint8 and a rune for int32.

For the second sub set, the machine dependent integers we have: uint, int and uintptr.

Floating Point Numbers

Generally known as Real Numbers, represents those numbers with decimal component.

Go has two floating point types : float32 and float64.

It also has two complex number types : complex64 and complex128.

String

This data type is represented by a sequence of characters with a definite length.

Literals in Go can be created in 2 ways, with double quotes, that allows the use of special characters like \n and \t, but cannot contain new lines, or with backticks quotes, that permits the use of new lines.

You can concatenate two or more strings, like lots of languages except PHP that use a dot (.), with plus sign (+), and each individual character can be obtained using indexes.

var example string = "weird\t string\n sample!”

otherway := `weird

sample!`

In comparison with PHP, here are a couple of examples of string operations:

 PHP
$part_1 = "weird"; 
$part_2 = "string"; 
$part_3 = "sample!";
Length in PHP
$stringLength = strlen($part_1); // 5
Length in Go!
var string_length int = len(example) 
Concatenations in PHP
$full_str = "{$part_1} {$part_2}";
$full_str .= $part_3
Concatenations in Go!
var full_str string
full_str = part_1 + " " + part_2

Boolean

Booleans are a special 1 bit integer type used to indicate True or False.

The logical operators which can be used on booleans are:

and &&

or ||

not !

Arrays, Slices, Maps

Array is a set of elements of an specific type. [n]T is an array of n elements of type T, where n is the length of the set and T represents the type, i.e. to create an array of ten element length of string, it should looks like [10]string.

Examples:

  var a [10]int

  x := [5]float64 {
       34,
       63,
       56,
       84,
       23
  }

The above example in PHP looks like:

$x = array(34, 63, 56, 84, 23);

or just

$x = [34, 63, 56, 84, 23];

Slice is a segment, not fixed of an Array.

Creation of slice is via make command.

x := make([]int, 5)

It also can be initialized from array by indexes.

 

x := a[3:] //the first 3 elements of a

x := a[2:5] // specific range, elements from 2 to 5

A map is an unordered collection of key-value pairs. Also known as an associative array, a hash table or a dictionary, maps are used to look up a value by its associated key.

var x map[string]int

x["Hello"] = 1

Custom Data Types

Struct:

A structure is a user defined data type which contains named fields. In Go structs are used to represents object by the association of method to pointer of this type.

type dog struct {
	breed string
	age int
	owner string
}

type cow struct {
	age int
	farm string
}

The dot operator is used to access each field by name. The above example in PHP will look like:

<?php
class Dog {
    private $breed;
    private $age;
    private $owner;
}

class Cow {
    private $age;
    private $owner;
}
Interfaces:

In Go an interface is two things: it is a set of methods, but it is also a type.
The interface{} type, the empty interface, is the source of much confusion. The interface{} type is the interface that has no methods. Since there is no implements keyword, all types implement at least zero methods, and satisfying an interface is done automatically, all types satisfy the empty interface. That means that if you write a function that takes an interface{} value as a parameter, you can supply that function with any value.

We’ll talk about Loops, Control Structures and some design patterns in future posts. Thanks for reading

TypeScript

Intro

TypeScript is an open source compiled superset language of Javascript maintained by Microsoft. Introduced in 2012 after several internal iterations, the project was born out of the desire to add some variable typing to Javascript. Hence, TypeScript.
While you may first recoil at the idea of another transpiled javascript library, let me explain some of the great features and speed increases you can get by including it in your workflow and you might change your mind.

How it Works

TypeScript is just a superset of JS that compiles to ES3, ES5 or ES6. Think of this as a higher level language that normalizes the features of ES5 & ES6 into a version compatible with your target language and polyfills missing features.
This means, if you are compiling to ES3, TS will turn your fancy ES6 class into the syntactic sugar required to replicate it in ES3. Also, it will do it better than you.

Why TypeScript is a good thing: you can have ES6 features, now

ES6 compatibility is woefully lacking for most browsers found in the wild, which is definitely appealing if you want to use some of those cool features you hear about… especially the ones that most people gripe about the lack of in JS (classes and inheritance) when compared to most other OOP languages.
Classes and Modules are now available to you, and down compiled . You can use the super cool (and often confusing on your first encounter) “arrow” functions notation for your Anonymous Functions. Rest functions where you can finally make your functions as flexible as you want them.
When you let TypeScript transpile your code you can have all of those amazing ES6 features with your current user base’s browsers! Yes, even Safari!

Why TypeScript is a good thing: You get type hints, type checking at compile time

Loose typing has always been a gripe of higher level languages like PHP and Javascript. At its core, the argument really comes down to keeping your code clean and safe by asserting you pass and ask for the correct types of variables. If your reading this, and enjoying it, I’m sure you have encountered the terrible spiral of type juggling and the concept of ‘falsy’ when looking for an optional variable input in a function.
Type annotations allow you to specify the exact type of input and output you are passing around your functions. This not only leads to implicit assertions of your types, but also allows for great real-time syntax checking if you are using an editor that supports it.
Also, the next time you try and pass a boolean variable to a function expecting a string, your compiler will complain “LOUDLY” and refuse to compile your crap code. Using explicit variable types is the best documentation you can provide and its built into the code you are writing.

How to Install / Use It

Install TSC via NPM
npm install -g typescript
Then follow along in the easy to understand QuickStart / HelloWorld from the TS team: http://www.typescriptlang.org/docs/tutorial.html
If you cannot install it, you can also try the TS playground: http://www.typescriptlang.org/docs/tutorial.html

Who is really using TypeScript?

Well, for one, Microsoft is using it on quite a few internal projects. The Angular 2 team actually wrote the majority of the new framework using TypeScript. Also, the popular project management tool Asana’s team made a rather well publicized switch to TypeScript recently.

Should I use TypeScript?

The simple answer is, sure. Why not. I would give it a shot and try and work it into your workflow and see how it goes. Thankfully it plays nice with vanilla JS as well.
Leave us a note in the comments if you actually use TypeScript, or have a good reason not to use TypeScript, in your work.

Let’s Go!

The Go programming language, also known as golang, is an open source project created by Robert Griesemer, Rob Pike, and Ken Thompson in 2007 and sponsored by Google as an intended to resolve common criticisms of other languages while maintaining their positive characteristics.

It’s heavily based on C, but designed to be more concise and secure. Go has become increasingly popular for seasoned developers and new programmers alike,

used in many open source and commercial software applications.

Some notable companies using Go within their applications include Google, Dropbox, CloudOS, MongoDB, Docker and Uber.

 

Go Language Basics

Go is a statically typed, compiled, garbage-collected, concurrent general purpose programming language. Go is considered as an object oriented programming language and it uses object composition instead of class inheritance.

Go was based on several languages besides C: Pascal, Modula, Oberon, Newsqueak, and Limbo.

It is a traditionally compiled, object oriented, functional language that features static typing, garbage collection, concurrency, memory safety, and high readability.

Some of the major advantages of Go include:

  • Concise, simple syntax.
  • Extremely fast compile times.
  • The ability to divide routine threads into sub threads, allowing for a high degree of concurrency.
  • Built-in support for strings and maps.
  • Go includes a huge standard library, including its own built-in web server.
  • The language supports most major operating systems and computer hardware.

 

Objects In Go

Since a standard definition does not exist, let’s use this one, “An object is an abstract data type that has state (data) and behaviour (code)”.

Go doesn’t have something like  `object`, even though it does have a type that matches the same definition of a data structure that integrates both code and behaviour.

In Go this is called a ‘struct’.

With struct we define a new data type containing the name of fields (attributes) that will keep the “state” of the object. To implement the behaviour of this object in Go,

we use functions bound to a pointer of this struct. Here’s an example to illustrate it:

image

 

Relationships between Objects In Go

Instead of inheritance Go strictly follows the composition over inheritance principle. Go accomplishes this through both subtyping (is-a) and object composition (has-a) relationships between structs and interfaces.

The mechanism Go uses to implement the principle of object composition is called embedded types. This way we have a field that is a subtype of other object, but this filed remains in a different entity.

Because of that Go provides two alternatives, “Pseudo sub typing” and “True sub typing”.

We accomplish this pseudo is-a relationship in go using what is called an Anonymous field.

Over the next posts I will bring you a more detailed explanation about this concepts while introduce you data types and language characteristics with some examples on each topic.

Remote PHP Debugging with Xdebug

Introduction

In our previous posts, we discussed how to use some tools to explore and debug legacy code. This blog post will explore one of these tools that I personally use quite often in depth: Xdebug and Remote Debugging.

We’ll explore the installation, the required settings tweaks, and some basic tools and workflows to get you started. The least fun and hardest part of this whole process is the installation.

Having xdebug up and running will speed up your code investigations and will really help you dig into troublesome code. It will also give you the best insight into code you aren’t familiar with works without resorting to die statements and var_dumps for small windows.

Development Only

Please only install this on your development and staging environments! Do not install this on any public facing server!

Remote Debugging

I want to take a minute and explain the concept of remote debugging with Xdebug. Until a few years ago, I would install XDebug only to get the “pretty error printing” features. While these features allowed some better control over how I was viewing errors and my var_dump results, it really added nothing I critically needed. Remote debugging now makes XDebug a short list of ‘need to install’ things when setting up a new environment.

Xdebug offers mechanisms to allow you to set breakpoints in your code to stop it’s execution and view the current state. This means you can say “stop here and let me take a look around at what the code is doing at this moment” on the server itself. You actually connect to the server and can poke around, set some conditional break points (where you stop execution when a variable is set to a certain value) and even evaluate some raw PHP on the server given certain conditions.

To accomplish this, you must connect a debugging tool to your server with a specified and exposed port and talk to it using a protocol provided by XDebug. Your debugger is the tool you use on your machine, XDebug is the tool/port/settings collection you use to connect to your server.

If this sounds like the basic IDE debugging tools you have used with other languages like C++ and JAVA (and also like something overcomplicated for being such a normal feature for other development stacks), it should. It’s pretty much the same thing. The biggest difference here is that this was not a widely used debugging method for hosted PHP. I’d like to help change that with this blog post.

Installing the Xdebug Extension

The xdebug project and github page offer some installation instructions that feel woefully lacking. Also, they offer little advice tailored to individual setups and environments. I’ll try and provide some examples of common installation methods.

Please note that these methods assume you are installing on the same server you host your development environment that serves the PHP code you wish to debug. This means, if you are running a vagrant box or docker container to host your code, install xdebug on this server instance. If you host your locally code on the same machine you are edit and maintain the code on, install xdebug on this machine. See the section above for some clarification on remote debugging.

All of these instruction assume you have administrator access and some level of comfortability with the *unix command line. If you do have access to your server in this capacity, or you are not comfortable with running these commands, you might want to find a grown up to help you.

pecl / pear

You can install Xdebug extension with the pecl tool and then tweak your php.ini file to include the installed extension. The official docs recommend this route first actually. The installation instructions are the same with the pear tool as they are for pecl. I have found this is the easiest installation method if you are running your server on a MacOS environment.

After you are sure you have pecl installed, run this command on your command line.

pecl install xdebug

apt-get / yum

If you are running your server on an Ubuntu/Debian/CentOS machine, you can install the xdebug with your specific package manager.

sudo apt-get install php5-xdebug

or

yum install php5-xdebug

Homebrew

This is a method I have never tried personally but I know there are some recipes specifically for installing xdebug with homebrew.

From what I read, you will need to add the homebrew-php repository and install this from the command line as well. Check out this repo link for more information.

Compiling it yourself

Another method I have never tried personally, but I know its possible. If you are want to do this yourself, you might be beyond the scope of this post. I’ll just point you to the project page for the most up to date information.

Update your php.ini file

Find your newly installed php extension and add this line to your php.ini file

zend_extension=“/usr/local/php/modules/xdebug.so”

Replace the “xdebug.so” file with whatever your tool installed. It’s also safe to create a symlink with the filename “xdebug.so” as well. If you have trouble finding this file, try the following command to find the extension file:

find / -name ’*xdebug*.so’ 2> /dev/null

Verifying your XDebug Installation

Restart apache and create a test file called test.php with the following lines of code and load it into your browser:

<?php

phpinfo();

Search for “xdebug” and you should see something like this in your browser:

image

If you see a line that looks like the one highlighted above, congrats, you have installed xdebug!

Port Forwarding

You will need to expose some ports on your server to allow connections from your debugging client. How you accomplish this will certainly depend on your individual environment setup, but I would like to note this to save you the time I lost trying to find out why I could not connect.

And we will explain the port you will need to be expose and forward in this next section…

Xdebug INI Settings

Here are some of the INI settings you will need to update in order to enable remote connections. These settings will be found in your php.ini file, or a possible xdebug.ini file if one was created by your install method.

  • xdebug.remote_host
    • This setting allows you to specify an address where you debugging client is connecting from.
    • In most cases, this will be set to “localhost”, but may differ in your development environment.
    • This setting is ignored if xdebug.remote_connect_back is set to TRUE. See more info below.
  • xdebug.remote_autostart
    • This setting enables remote debugging, turn this on!
  • xdebug.remote_port
    • This setting allows you to specify a port for your debug client to connect to the remote server with. You will need this value when configuring your remote debugging tool.
    • This is typically set to 9000 but you can update this to any port that isn’t being used if you feel contrary.
  • xdebug.var_display_max_children
    • This setting allows you to specify the amount of array children and object’s properties are shown when you use a var_dump or use your debugging client’s function trace tool.
    • By default this is set to 128, but you can set it to -1 if you want to remove the limit entirely.
  • xdebug.var_display_max_data
    • Like var_display_max_children, this setting allows you to set a  maximum string length that is shown when variables are displayed in var_dumps or function traces.
    • By default this is set to 128, but you can set it to -1 if you want to remove the limit entirely.
  • xdebug.var_display_max_depth
    • Another setting that allows you to set a limit when using var_dump or function tracing, but this one sets the nested levels of array elements and object properties displayed.
    • By default, this is set to 128, but again if you live dangerously you can remove the limit entirely and set it to -1.
  • xdebug.scream
    • Setting this value to true will disable the @ (the “shut up”) operator entirely.
    • This is super useful when you find out when you predecessor was just hiding a critical error behind the @ operator and you can finally go to be because you found the elusive notice showing the variable was never set in the first place and you had no idea and thats why you can’t get the page to load when you don’t have a cookie set in IE 9.
  • xdebug.remote_connect_back
    • Setting this value to true will allow you to connect and attach a remote debugging client to your server from any address.
    • This setting is great for shared development environments but is quite dangerous since it will just allow anyone to connect who tries. YES, anyone.
    • Also of note, this will override the xdebug.remote_host setting.

Remote Debugging Tools

Editors

PHPStorm & SublimeText

While I personally like to use the stand alone tools, I do know a lot of people who prefer to use these editors to remote debug.

While I’m sure a cursory google search can lead you to some better instructions on how to install and configure these tools, I thought it was worth mentioning since a lot of people use these tools and they offer the remote debugging tools you might want to use.

Stand Alone Tools & Helpers

MacGDBp

This is a tool I use on an almost daily basis. Its relatively small and lightweight, and gets out of the way when I am done. I also mentioned it in our last blog post. I do need to note that this tool does not seem to be updated frequently and occasionally crashes without warning. That being said, I still highly recommend it.

Chrome Xdebug Enabler

This is a simple chrome extension that allows you to toggle the xdebug remote debugging cookie for a given URL. This is great to quickly start and stop a remote debugging session.

It’s pretty much an unobtrusive button that lives in chrome. I would install it now if I were you.

Conclusion

I barely touched the surface of remote debugging using xdebug, but I hope I inspired you to install and configure it now. Stop using var_dump and die statements and debug like a grown up!