Lukas is a freelance web and mobile developer based in Manchester in the North of England. He's been developing in PHP since moving away from those early days in web development of using all manner of tools such as Java Server Pages, classic ASP and XML data islands, along with JavaScript - back when it really was JavaScript and Netscape ruled the roost. When he's not developing websites and mobile applications and complaining that this was all fields, Lukas likes to cook all manner of World foods.

Lukas's articles

  1. Working with Phone Numbers in JavaScript

    When you’re collecting data from users, there are two key challenges; collecting that information, and validating it. Some types of information are straightforward – someone’s age, for example, couldn’t really be simpler to collect and to validate. Names aren’t as straightforward as they sound, but provided you cater for edge cases and international variations – for example patronymics, the mononymous, or even just people with hyphenated surnames – you can’t go too far wrong (although plenty of applications and services do!). Email addresses, while theoretically very easy to validate, have their own challenges – yet nevertheless, there are plenty of regular expressions in the wild that aren’t quite right.

    And then there are telephone numbers. These are hard. Really hard. In this article I’ll discuss some of the challenges around collecting, validating, and displaying telephone numbers.

    Why Telephone Numbers are Different

    Perhaps you’re thinking that since telephone numbers tend to follow a pretty rigid format, such as this:

    [code]
    202-456-1111
    [/code]

    …that it ought to be simple to construct a simple regular expression to validate them. In fact, here’s one:

    [code]
    ^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
    [/code]

    Well, stop right there. For starters, here are just some variations of the number above, all of which are perfectly valid:

    [code]
    202 456 1111
    (202) 456 1111
    2024561111
    1-202-456-1111
    1-202-456-1111 x1234
    1-202-456-1111 ext1234
    1 (202) 456-1111
    1.202.456.1111
    1/202/456/1111
    12024561111
    +1 202 456 1111
    [/code]

    So based on that, we know that the regular expression apparoach isn’t as simple as we first thought – but that’s only the half of it. These examples are just for a US-based number. Sure, if you know that the number you’re collecting is going to be for a specific country, you may be able to use a regular expression. Otherwise, this approach won’t cut it.

    Let’s look at some of the other issues around telephone numbers, and why they make our job even harder.

    Numbers Change

    All sorts of external factors can have implications for telephone numbering. Whole countries come and go, introducing new country prefixes. New classifications of numbers introduce new numbering systems – premium-rate, local-rate, toll-free, and so on. When a carrier runs out of one set of numbers – like, sadly, premium-rate – they simply introduce a new prefix.

    Some changes have enormous implications; in the United Kingdom some years ago, for example, the entire regional numbering system underwent a drastic change, with virtually every area code getting an additional “1” inserted. Even then, the capital had a subtly different system. It was probably a decade before signage was changed across the country to reflect the changes.

    Then, of course, there was the enormous and unprecedented growth in mobile. No longer was the number of telephone numbers required largely limited to the number of households, but many times over. The continued strain on the pool of available numbers can only increase the likelihood of further changes.

  2. A Closer Look at Piwik: A Google Analytics Alternative

    A recent SitePoint article by Jacco Blankenspoor introduced a number of alternatives to the ubiquitous Google Analytics. Among them was Piwik — a self-hosted, open-source package that Jacco described as a “serious contender”. In this article, I’m going to look at Piwik in more detail, to assess that claim. Why use Piwik? It’s probably worth […]

  3. Using Solarium with SOLR for Search – Advanced

    This entry is part 4 of 4 in the series Using Solarium for SOLR Search

    This is the fourth and final part of a series on using Apache’s SOLR search implementation along with Solarium, a PHP library to integrate it into your application as if it were native.

    In the first three parts we installed and configured SOLR and Solarium and started building an example application for searching movies. We’ve also looked at faceted search.

    We’re going to wrap up the series by looking at some more advanced features of SOLR, and how to use them with Solarium.

    Highlighting Results with SOLR

    The Highlighting component allows you to highlight the parts of a document which have matched your search. Its behavior around what gets shown depends on the field – if it’s a title chances are it’ll show it in its entirety with the matched words present, and longer fields – such as a synopsis or the body of an article – it will highlight the words but using snippets; much like Google’s search results do.

    To set up highlighting, you first need to specify the fields to include. Then, you can set a prefix and corresponding postfix for the highlighted words or phrases. So for example, to make highlighted words and phrases bold:

    $hl = $query->getHighlighting();
    $hl->setFields(array('title', 'synopsis'));
    $hl->setSimplePrefix('<strong>');
    $hl->setSimplePostfix('</strong>');
    

    Alternatively, to add a background color:

    $hl = $query->getHighlighting();
    $hl->setFields(array('title', 'synopsis'));
    $hl->setSimplePrefix('<span style="background:yellow;">');
    $hl->setSimplePostfix('</span>');
    

    Or you can even use per-field settings:

    $hl = $query->getHighlighting();
    $hl->getField('title')->setSimplePrefix('<strong>')->setSimplePostfix('</strong>');
    $hl->getField('synopsis')->setSimplePrefix('<span style="background:yellow;">')->setSimplePostfix('</span>');
    

    Once you’ve configured the highlighting component in your search implementation, there’s a little more work to do involved in displaying it in your search results view.

    First, you need to extract the highlighted document from the highlighting component by ID:

    $highlightedDoc = $highlighting->getResult($document->id);
    

    Now, you can access all the highlighted fields by iterating through them, as properties of the highlighted document:

    if($highlightedDoc){
        foreach($highlightedDoc as $field => $highlight) {
            echo implode(' (...) ', $highlight) . '<br/>';
        }
    }
    

    Or, you can use getField():

    if($highlightedDoc){
        $highlightedTitle = $highlightedDoc->getField('title');
    }
    

    Highlighted fields don’t simply return text, however Instead, they’ll return an array of “snippets” of text. If there are no matches for that particular field – for example if your search matched on title but not synopsis – then that array will be empty.

    The code above will return a maximum of one snippet. To change this behavior, you can use the setSnippets() method:

    $hl = $query->getHighlighting();
    $hl->setSnippets(5);
    // . . . as before . . .
    

    For example, suppose you search for the word “star”. One of the results has a synopsis that reads as follows:

    This not to be missed movie theater event will feature one of the most memorable moments in TV history and exclusive clips about the making of The Best of Both Worlds and Star Trek: The Next Generation Season 3. Set in the 24th century, The Next Generation was created by Gene Roddenberry over 20 years after the original Star Trek series. The Next Generation became the longest running series of the Star Trek franchise, consisting of 178 episodes over 7 seasons. Star Trek: The Next Generation – The Best of Both Worlds is the first opportunity to see The Best of Both Worlds, one of the greatest TV episodes of all time, as a gloriously remastered full-length feature in select movie theaters nationwide.

  4. Using Solarium with SOLR for Search – Implementation

    This entry is part 3 of 4 in the series Using Solarium for SOLR Search

    This is the third article in a four-part series on using Solarium, in conjunction with Apache’s SOLR search implementation.

    In the first part I introduced the key concepts and we installed and set up SOLR. In part two we installed and configured Solarium, a library which enables us to use PHP to “talk” to SOLR as if it were a native component.

    Now we’re finally ready to start building the search mechanism, which is the subject of this installment.

    Let’s look at how to implement a really simple search:

    $query = $client->createSelect();
    $query->setQuery(Input::get('q'));
    

    Input::get('q') is simply Laravel’s way of grabbing a GET or POST variable named q which, you’ll remember, is the name of our search form element.

    Or better still, use a placeholder to escape the search phrase:

    $query->setQuery('%P1%', array(Input::get('q')));
    

    A placeholder is indicated by the % symbols. The letter “P” means “escape this as a Phrase”. The bound variables are passed as an array, and the number indicates the position in the array of the argument you wish to bind; bearing in mind that (perhaps unusually) 1 indicates the first item.

    To run the search:

    $resultset = $client->select($query);
    

    You can now retrieve the number of results using the getNumFound() method, for example:

    printf('Your search yielded %d results:', $resultset->getNumFound());
    

    $resultset is an instance of Solarium\QueryType\Select\Result\Result, which implements the Iterator interface – so you can iterate through the results as follows:

    foreach ($resultset as $document) {
        . . .
    }
    

    Each result is an instance of Solarium\QueryType\Select\Result\Document, which provides two ways in which you can access the individual fields – either as public properties, e.g.:

    <h3><?php print $document->title ?></h3>
    

    Or, you can iterate through the available fields:

    foreach($document AS $field => $value)
    {
        // this converts multi-value fields to a comma-separated string
        if(is_array($value)) $value = implode(', ', $value);
    
        print '<strong>' . $field . '</strong>: ' . $value . '<br />';        
    }
    

    Note that multi-value fields – such as cast – will return an array; so in the example above, it will simply collapse these fields into a comma-separated list.

  5. Using Solarium with SOLR for Search – Solarium and GUI

    This entry is part 2 of 4 in the series Using Solarium for SOLR Search

    This is the second article in a four part series on using Solarium, in conjunction with Apache’s SOLR search implementation.

    In the first part, I introduced the key concepts and we installed and set up SOLR. In this second part we’ll install Solarium, start building an example application, populate the search index and get into a position where we can start running searches.

    Creating the Application

    Create a new Laravel application via Composer:

    composer create-project laravel/laravel movie-search --prefer-dist
    

    Make the storage directory app/storage directory writeable.

    Installing Solarium

    You’ll recall from the first part that the Solarium Project provides a level of abstraction over the underlying SOLR requests which enables you to code as if SOLR were a native search implementation running locally, rather than worry about issuing HTTP requests or parsing the responses.

    By far the best way to install Solarium is using Composer:

    "solarium/solarium": "dev-develop"
    

    Alternatively you can download or clone it from Github.

    If you’re following along and building the movie search application, this will go in your newly created project’s composer.json file just as you would any other third-party package; there’s no Laravel service provider though, in this case.

    Configuring Solarium

    The constructor to the Solarium client takes an array of connection details, so create a configuration file – app/config/solr.php as follows:

  6. Using Solarium with SOLR for Search – Setup

    This entry is part 1 of 4 in the series Using Solarium for SOLR Search

    Apache’s SOLR is an enterprise-level search platform based on Apache Lucene. It provides a powerful full-text search along with advanced features such as faceted search, result highlighting and geospatial search. It’s extremely scalable and fault tolerant.

    Well known websites said to use SOLR to power their search functions include digg, Netflix, Instagram and Whitehouse.gov (source).

    While SOLR is written in Java, it’s accessible via HTTP, making it possible to integrate with whatever programming language you prefer. If you’re using PHP then the Solarium Project makes integration even easier, providing a level of abstraction over the underlying requests which enables you to use SOLR as if it were a native implementation running within your application.

    In this series, I’m going to introduce both SOLR and Solarium side-by-side. We’ll begin by installing and configuring SOLR and creating a search index. Then, we’ll look at how to index documents. Next, we’ll implement a basic search and then expand it with some more advanced features such as faceted search, result highlighting and suggestions.

    As we go along, we’re going to build a simple application for searching a collection of movies. You can grab the source code here, or see an online demo here.

    Basic Concepts and Operation

    Before we delve into the implementation, it’s worth looking at a few basic concepts and an overall view of what will happen.

    SOLR is a Java application which runs as a web service, typically in a servlet container such as Tomcat, Glassfish or JBoss. You can manipulate and query it over HTTP using XML, JSON, CSV or binary format – so you can use any programming language for your application. However, the Solarium library provides a level of abstraction, allowing you to call methods as if SOLR were a native implementation. For the purposes of this tutorial we’ll be running the SOLR on the same machine as our application, but in practice it could be located on a separate server.

    SOLR creates a search index of documents. Often that mirrors what we might consider a document in real-life; an article, blog post or even a full book. However a document can also represent any object applicable to your application – a product, a place, an event – or in our example application, a movie.

    At its most basic, SOLR allows you to perform full text searches on documents. Think search engines; you’ll typically search for a keyword, a phrase or a full title. You can only get so far with SQL’s LIKE clause; that’s where fulltext search comes in.

    You can also attach additional information to an indexed search document that doesn’t necessarily get picked up by a text-based search; for example, you can incorporate the price of a product, the number of rooms in a property or the date an item was added to the database.

    Facets are one of the most useful features of SOLR. You’ll probably have seen faceted search if you’ve ever shopped online; facets allow you to “drill down” search results by applying “filters”. For example, having searched an online bookstore you might use filters to limit the results to those books by a particular author, in a particular genre or in a particular format.

    An instance of SOLR runs with one or more cores. A core is a collection of configuration and indexes, each with its own schema. Typically, a single instance is specific to a particular application. Since different types of content can have very different structures and information – for example, consider the difference between a product, an article and a user – an application often has multiple cores within an SOLR instance.

    Installing SOLR

    I’m going to provide instructions for how to setup SOLR on a Mac; for other operating systems, consult the documentation – or alternatively, you can download Blaze, an appliance with SOLR pre-installed.

  7. Introduction to Kirby CMS

    Kirby is a lightweight CMS that probably fits somewhere between feature-rich platforms such as Drupal, and static site generators such as Jekyll. What makes Kirby quite different to most CMS’s – and closer to Jekyll in the process – is that it has no database. Instead, everything is stored as files; some for configuration, some […]

  8. Using JSON Web Tokens with Node.js

    Front end frameworks and libraries such as Ember, Angular, and Backbone are part of a trend towards richer, more sophisticated web application clients. As a consequence of this, server-side components are unburdened from many of their traditional responsibilities, in essence becoming more like API’s. This API approach allows a greater decoupling of the traditional “front end” and “back end” parts of an application. One set of developers can build the back end independently from the front end engineers, with the additional benefit that testing becomes simpler. This approach also makes it much easier to build, say, a mobile application that shares the same back end as your web application.

    One of the challenges when providing an API is authentication. In traditional web applications, the server responds to a successful authentication request by doing two things. First, it creates a session using some storage mechanism. Each session has its own identifier – usually a long, semi-random string – which is used to retreive information about the session on future requests. Secondly, that information is sent to the client by way of headers instructing it to set a cookie. The browser automatically attaches the session ID cookie to all subsequent requests, allowing the server to identify the user by retrieving the appropriate session from storage. This is how traditional web applications get around the fact that HTTP is stateless.

    APIs should be designed to be truly stateless. This means no login or logout methods and no sessions. API designers can’t rely on cookies either, as there is no guarantee that requests will be made via a web browser. Clearly, we need an alternative mechanism. This article looks at one possible mechanism designed to tackle the problem – JSON Web Tokens, or JWTs (pronounced jots). The examples in this article uses Node’s Express framework on the back end, and Backbone on the client.

    Background

    Let’s briefly look at a few common approaches to securing APIs.

    One is to use HTTP Basic Authentication. Defined in the official HTTP specification, this essentially involves setting a header on the server response which indicates authentication is required. The client must respond by attaching their credentials, including their password, to every subsequent request. If the credentials match, the user information is made available to the server application as as variable.

    The second approach is very similar, but using the application’s own authentication mechanism. This usually involves checking the supplied credentials against those in storage. As with HTTP Basic Authentication, this requires that the user’s credentials are supplied with each and every call.

    The third approach is OAuth (or OAuth2). Designed to a large extent for authenticating against third-party services, it can be rather challenging to implement, at least on the server-side.

    A fourth approach is using tokens. That’s what we’re going to look at in this article. We’ll look at an implementation that utilizes JavaScript on both the front and back ends.

    The Token Approach

    Instead of supplying credentials such as a username and password with every request, we can allow the client to exchange valid credentials for a token. This token gives the client access to resources on the server. Tokens are generally much longer and more obfuscated than a password. For example, the JWTs we’re going to be dealing with are on the order of ~150 characters. Once the token is obtained, it must be sent with every API call. However, this is still more secure than sending a username and password with every request, even over HTTPS.

    Think of the token like a security pass. You identify yourself at the front desk of a restricted building on arrival (supply your username and password), and if you can be successfully identified you’re issued a security pass. As you move around the building (attempt to access resources by making calls to the API) you are required to show your pass, rather than go through the initial identification process all over again.

    About JWTs

    JWTs are a draft specification, although in essence they are really just a more concrete implementation of an authentication and authorization mechanism that is already commonplace; that of exchanging tokens. A JWT is split into three parts, separated by periods. JWTs are URL-safe, meaning they can be used in query string parameters.

    The first part of a JWT is an encoded string representation of a simple JavaScript object which describes the token along with the hashing algorithm used. The example below illustrates a JWT using HMAC SHA-256.

    [js]
    {
    “typ” : “JWT”,
    “alg” : “HS256″
    }
    [/js]

    After encoding, the object becomes this string:

    [code]
    eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9
    [/code]

    The second part of the JWT forms the core of the token. It too represents a JavaScript object, which contains a few pieces of information. Some of these fields are required, and some are optional. An example, taken from the draft specification, is shown below.

    [js]
    {
    “iss”: “joe”,
    “exp”: 1300819380,
    “http://example.com/is_root”: true
    }
    [/js]

    This is called a JWT Claims Set. For the purposes of this article, we’re going to ignore the third parameter, but you can read more in the specification. The iss property is short for issuer, and specifies the person or entity making the request. Typically, this would be the user accessing the API. The exp field, short for expires, is used to limit the lifetime of the token. Once encoded, the JSON token looks like this:

    [code]
    eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ
    [/code]

    The third, and final, part of the JWT is a signature generated based on the header (part one) and the body (part two). The signature for our example JWT is shown below.

    [code]
    dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
    [/code]

    The resulting complete JWT looks like this:

    [code]
    eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
    [/code]

    There are a number of additional, optional properties supported in the specification. Among them are iat representing the time at which the token was issued, nbf (Not Before) to indicate the token should not be accepted before a certain time, and aud (audience) to indicate the recipients the token is intended for.

  9. Database Versioning with Ladder Migrations

    Version control systems are invaluable for tracking changes in your code, particularly when you’re working in a team. However, most applications don’t consist solely of application code. Managing changes to the database has always been a little more challenging, particularly when you’re adding new features which require changes to the schema.

    Suppose you’re working on a module and realize one of the database tables needs an additional column. You might be tempted to open up a database query tool or the command line and simply add the column. However, this doesn’t leave a record of the change in the same way as version-controlled application code would. This gets exacerbated when working in a team – if a colleague pulls your code changes without running those same database updates, then it’s entirely possible their version of the application will break. This becomes even more problematic when you’re releasing a product update, when it could break the application not just for your fellow developers, but for your users.

    One solution is to move responsibility for creating and modifying the database schema into code, using migrations. That way, changes can be managed along with the rest of your application, and features we take for granted in version control – such as being able to compare versions and keep an audit trail – can be used for database changes. It also allows these changes to be seamlessly incorporated into releases, since they can be made part of the same branch or tag.

    Many major frameworks have their own migration implementation, but for those that don’t – and if you’re not using any framework – there’s Ladder.

  10. A Review of the Brackets Editor

    This article is going to take a look at Brackets, an open-sourced editor originally developed by Adobe. It may not have had quite the same level of publicity and hype as Atom, GitHub’s new lightweight editor, but it’s a promising option for the front end developer.

    Target Audience

    It’s worth pointing out that Brackets is primarily aimed at front end developers and web designers. Although it’s essentially a text editor and therefore suitable for coding pretty much anything, it’s optimized for HTML, CSS, and JS (as well as derivatives such as SASS, Less, CoffeeScript, and so on). Ruby, Python, PHP developers, and the like might be better served looking elsewhere, whether that be for a fully-fledged IDE or something more lightweight such as Sublime or, indeed, Atom.

    What Makes Brackets Different?

    Brackets makes a big deal of the fact that it’s written using a combination of HTML, CSS, and JavaScript. While this may mean little for the casual user, those who wish to extend – or even hack it – have the opportunity to do so using technologies they’re probably already familiar with. The fact that it’s open-sourced also makes it stand out from the crowd. Sublime, for example, is a commercial product, while Atom is closed-source and won’t be free forever.

    Getting Brackets

    Brackets can be downloaded from the website, and is available for Mac OSX, Windows, and Linux (32 or 64-bit). For the purposes of this review, I’m running the 37th “sprint”, on Mac OSX.

    First Steps

    When you open Brackets for the first time, you’re thrown straight into an HTML-based tutorial file with accompanying CSS, which is a great way to start exploring.

    The Brackets editor

    The left-hand column lists the working files, and beneath that is a folder view. It’s like Sublime in that you can view a file with one click without actually opening it. A double-click opens the file for editing, adding it to the working files list.

    The right-hand column contains icons for opening Live Preview (which we’ll look at shortly) and for the Extension Manager. Many third-party extensions create their own icons and place them in this bar, so it can quickly become an invaluable launchpad.

    A Quick Feature Tour

    Let’s look at some of the key features of Brackets.

    Live Preview

    The Live Preview feature launches a new Chrome window showing the current page that not only doesn’t require a manual refresh when you change a file, but also as you type. It’s essentially Chrome’s Web Inspector, but with all the benefits of a self-contained editor. It’s a truly great feature, particularly if you have a splt-screen setup. It doesn’t just work with HTML files, either. If you make a change to a linked CSS file which impacts the current page, that too gets reflected immediately in the browser. If you’re editing a CSS file used by the currently visible page, highlighting rules causes the preview to highlight elements which are affected by them.

    Quick Edit

    The Quick Edit feature is context-specific. Let’s look at a few of its uses.

    CSS

    When you’re editing HTML, if you click a tag with a corresponding CSS declaration situated in a linked file and hit Ctrl / Command + E, an inline editor appears allowing you to quickly edit that rule. This is probably best illustrated with the following screenshot.

    Inline CSS editing

  11. Getting Started with PHP Underscore

    If you’ve ever used the Backbone framework for JavaScript, you’ll already be familiar with Underscore. Indeed, it’s become incredibly useful for JavaScript developers in general. But did you know that it’s been ported to PHP?

    In this article I’ll take a look at Underscore, what it can do, and provide some examples of where it might be useful.

    What is Underscore?

    Underscore describes itself as a “utility belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It’s the tie to go along with jQuery’s tux, and Backbone.js’s suspenders.”

    Most notably, Underscore provides a bunch of utilities for working with collections and arrays, some for working with objects, basic templating functionality and a number of other useful functions.

    The functions which operate on collections and arrays can be particularly useful when dealing with JSON, which makes it great for handling responses from web services.

  12. Getting Started with Assetic

    There was a time when asset management meant little more than inserting a <link> tag or two and a couple of <script> tags into your HTML.

    Nowadays, though, that approach just won’t cut it. There’s performance, for one thing. Assets are a significant performance drain both in terms of file size and the number of HTTP requests – optimizing both has become an essential part of the development process. This has been exacerbated by the proliferation of mobile devices.

    Also, as client-side applications have become more and more sophisticated, managing dependencies amongst scripts and libraries has become increasingly complex.

    Furthermore, technologies such as Less, Compass and Coffeescript require assets to be compiled, adding yet another step to the process of managing assets.

    In this article I’m going to look at a PHP package called Assetic which helps manage, compile and optimize assets such as scripts, stylesheets and images.

  13. Introduction to JadePHP

    There are dozens of templating engines out there, with options such as Smarty, Twig (used in the upcoming version of Drupal) and Blade (the default for Laravel) among the best known – as well as vanilla PHP, of course. Stepping away from PHP specifically, eRuby / ERB and Haml for Ruby / Ruby on Rails, and Javascript has scores of popular choices including Mustache, Handlebars, Hogan and EJS. Some have subtly different syntax, some more markedly so.

    One which differs quite significantly from most is Jade, an engine usually associated with Javascript applications – it’s supported out-of-the-box by Express for Node.js, for example. It’s Jade I’m going to look at in this article; or more specifically the PHP port JadePHP.

    Haml and Jade

    It would be remiss to talk about Jade without mentioning Haml, from which Jade takes its inspiration – and indeed there are several libraries for using Haml with PHP. Jade shares its overall philosophy, which is to make templating “beautiful” and use what the authors describe as templating “haiku”. Whatever that actually means, there’s no denying Haml and Jade do share some characteristics which make them fundamentally different to most templating languages.

    What’s the Difference?

    Most templating engines involve writing the target markup and “injecting” it with placeholders and / or basic logic – a superset, in a sense. Jade still has placeholders and logic, but also provides a shorthand for writing XML-like elements. Generally that means HTML, although you can also use it for things like RSS as well as XML itself.

    In fact if you wanted to, you could just use Jade as a shorthand for HTML without taking advantage of its more “traditional” templating features.

    How to use the Repository

    Rather frustratingly, the code is not currently available via Composer – although it should be a simple enough task to package it up, if anyone has an hour or two. You can get it to to work, however, by cloning the repository and include‘ing or require‘ing the included autoload.php.dist (the Github repository includes Symfony’s UniversalClassLoader).

    Here’s an example, adapted from the one in the project’s README, which assumes that the repository has been downloaded into a directory called jade:

    require('./jade/autoload.php.dist');
    
    use Everzet\Jade\Dumper\PHPDumper,
            Everzet\Jade\Visitor\AutotagsVisitor,
            Everzet\Jade\Filter\JavaScriptFilter,
            Everzet\Jade\Filter\CDATAFilter,
            Everzet\Jade\Filter\PHPFilter,
            Everzet\Jade\Filter\CSSFilter,
            Everzet\Jade\Parser,
            Everzet\Jade\Lexer\Lexer,
            Everzet\Jade\Jade;
    
    $dumper = new PHPDumper();
    $dumper->registerVisitor('tag', new AutotagsVisitor());
    $dumper->registerFilter('javascript', new JavaScriptFilter());
    $dumper->registerFilter('cdata', new CDATAFilter());
    $dumper->registerFilter('php', new PHPFilter());
    $dumper->registerFilter('style', new CSSFilter());
    
    // Initialize parser & Jade
    $parser = new Parser(new Lexer());
    $jade   = new Jade($parser, $dumper);
    
    $template = __DIR__ . '/template.jade';
    
    // Parse a template (both string & file containers)
    echo $jade->render($template);
    

    This will compile the file template.jade and echo its contents.

    Where you actually use this depends on your workflow, whether you’re using a framework, and so on. You could, perhaps, use a service such as Watchman, Guard or Resource Watcher to watch the filesystem for changes to your Jade templates, and compile them at the appropriate time during the development process.

  14. Abstract File Systems with Flysystem

    Reading and writing files is an integral aspect of any programming language, but the underlying implementation can vary enormously. For example, the finer details of writing data to the local filesystem compared to uploading over FTP is very different – yet conceptually, it’s very similar.

    In addition to old warhorses like FTP, online storage is increasingly ubiquitous and inexpensive – with scores of services available such as Dropbox, Amazon’s S3 and Rackspace’s Cloud Files – but these all use subtly different methods for reading and writing.

    That’s where flysystem comes in. It provides a layer of abstraction over multiple file systems, which means you don’t need to worry where the files are, how they’re stored, or need be concerned with low-level I/O operations. All you need to worry about are the high-level operations such as reading, writing and organizing into directories.

    Such abstraction also makes it simpler to switch from one system to another without having to rewrite vast swathes of application code. It also provides a logical approach to moving or copying data from one storage system to another, without worrying about the underlying implementation.

    You can use Dropbox, S3, Cloud Files, FTP or SFTP as if they were local; saving a file becomes the same process whether it’s being saved locally or transferred over the network. You can treat zip archives as if they were a bunch of folders, without worrying about the nitty gritty of creating and compressing the archives themselves.

  15. Selling Downloads with Stripe and Laravel

    Digital goods are an increasingly valuable commodity. Whether you're a designer selling templates or font files, a developer charging for packages of code or a musician selling MP3s, selling digital goods online is often far easier than physical goods – with much lower production costs and no delivery charges. In this article I'll show how […]

  16. Building a Live-score Widget Using PHP Web Sockets

    The introduction of web sockets makes it possible for web applications to handle near real-time data without resorting to "hacks" such as long-polling. One example of an application requiring up-to-the-minute data is sports scores. Even now, many websites which display this information use Flash applications, since Actionscript provides the facility to communicate over socket-based connections. […]

  17. Responsive Images Using Picturefill and PHP

    One of the key challenges with responsive web design, and a subject of much discussion in recent years, is how to deal with images. Setting a max-width on image elements enables designers to allow their size to adapt to the page dimensions, but in itself that approach can lead to far bigger images being downloaded […]

  18. Introduction to Redbean

    An Introduction to Redbean When it comes to RAD and prototyping, there are lots of tools available to help get projects up-and-running quickly. From quick-starts to micro-frameworks, from build tools such as Composer to one-click installers, and of course ORMs – there are all sorts of ways to speed up development time. I'm going to […]

  19. Creating a Subscription-Based Website with Laravel and Recurly, Part 2

    This entry is part 2 of 2 in the series Creating a Subscription-Based Website with Laravel and Recurly

    This entry is part 2 of 2 in the series Creating a Subscription-Based Website with Laravel and RecurlyIn the first part of this series we created the bare bones of a subscription-based website using Laravel. We also set the site up with roles, and granted a pending role to new users. We’re now at the […]

  20. Creating a Subscription-Based Website with Laravel and Recurly, Part 1

    This entry is part 1 of 2 in the series Creating a Subscription-Based Website with Laravel and Recurly

    This entry is part 1 of 2 in the series Creating a Subscription-Based Website with Laravel and RecurlyScheduling and processing payments is easy, but don’t think recurring payments are trivial. Things can get complicated very quickly. You need to decide how to handle failures (how many failed payment attempts does someone get?), billing details must […]

  21. Running Tasks in the Cloud with IronWorker

    In this article I’m going to show you how we can use IronWorker to run code in the Cloud, just as if it were being run inside our PHP application’s code. There are a number of advantages to running tasks in the cloud, for example: processor-intensive tasks can be offloaded from your web server better […]