Blog

  • Getting the Most Out of Your PHP Log Files: A Practical Guide

    It could rightfully be said that logs are one of the most underestimated and underutilized tools at a freelance php developer’s disposal. Despite the wealth of information they can offer, it is not uncommon for logs to be the last place a developer looks when trying to resolve a problem.
    In truth, PHP log files should in many cases be the first place to look for clues when problems occur. Often, the information they contain could significantly reduce the amount of time spent pulling out your hair trying to track down a gnarly bug.
    But perhaps even more importantly, with a bit of creativity and forethought, your logs files can be leveraged to serve as a valuable source of usage information and analytics. Creative use of log files can help answer questions such as: What browsers are most commonly being used to visit my site? What’s the average response time from my server? What was the percentage of requests to the site root? How has usage changed since we deployed the latest updates? And much, much more.
    PHP log files
    This article provides a number of tips on how to configure your log files, as well as how to process the information that they contain, in order to maximize the benefit that they provide.

    Although this article focuses technically on logging for PHP developers, much of the information presented herein is fairly “technology agnostic” and is relevant to other languages and technology stacks as well.

    Note: This article presumes basic familiarity with the Unix shell. For those lacking this knowledge, an Appendix is provided that introduces some of the commands needed for accessing and reading log files on a Unix system.

    Our PHP Log File Example Project

    As an example project for discussion purposes in this article, we will take Symfony Standard as a working project and we’ll set it up on Debian 7 Wheezy with rsyslogd, nginx, and PHP-FPM.

    composer create-project symfony/framework-standard-edition my "2.6.*"
    

    This quickly gives us a working test project with a nice UI.

    Tips for Configuring Your Log Files

    Here are some pointers on how to configure your log files to help maximize their value.

    Error Log Confguration

    Error logs represent the most basic form of logging; i.e., capturing additional information and detail when problems occur. So, in an ideal world, you would want there to be no errors and for your error logs to be empty. But when problems do occur (as they invariably do), your error logs should be one of the first stops you make on your debugging trail.
    Error logs are typically quite easy to configure.
    For one thing, all error and crash messages can be logged in the error log in exactly the same format in which they would otherwise be presented to a user. With some simple configuration, the end user will never need to see those ugly error traces on your site, while devops will be still able to monitor the system and review these error messages in all their gory detail. Here’s how to setup this kind of logging in PHP:

    log_errors = On
    error_reporting = E_ALL
    error_log = /path/to/my/error/log
    

    Another two lines that are important to include in a log file for a live site, to preclude gory levels of error detail from being to presented to users, are:

    display_errors = Off
    display_startup_errors = Off
    

    System Log (syslog) Confguration

    There are many generally compatible implementations of the syslog daemon in the open source world including:

    • syslogd and sysklogd – most often seen on BSD family systems, CentOS, Mac OS X, and others
    • syslog-ng – default for modern Gentoo and SuSE builds
    • rsyslogd – widely used on the Debian and Fedora families of operating systems

    (Note: In this article, we’ll be using rsyslogd for our examples.)
    The basic syslog configuration is generally adequate for capturing your log messages in a system-wide log file (normally /var/log/syslog; might also be /var/log/messages or /var/log/system.log depending on the distro you’re using).
    The system log provides several log facilities, eight of which (LOG_LOCAL0 through LOG_LOCAL7) are reserved for user-deployed projects. Here, for example, is how you might setup LOG_LOCAL0 to write to 4 separate log files, based on logging level (i.e., error, warning, info, debug):

    # /etc/rsyslog.d/my.conf
    local0.err      /var/log/my/err.log
    local0.warning  /var/log/my/warning.log
    local0.info     -/var/log/my/info.log
    local0.debug    -/var/log/my/debug.log
    

    Now, whenever you write a log message to LOG_LOCAL0 facility, the error messages will go to /var/log/my/err.log, warning messages will go to /var/log/my/warning.log, and so on. Note, though, that the syslog daemon filters messages for each file based on the rule of “this level and higher”. So, in the example above, all error messages will appear in all four configured files, warning messages will appear in all but the error log, info messages will appear in the info and debug logs, and debug messages will only go to debug.log.
    One additional important note; The - signs before the info and debug level files in the above configuration file example indicate that writes to those files should be perfomed asynchronously (since these operations are non-blocking). This is typically fine (and even recommended in most situations) for info and debug logs, but it’s best to have writes to the error log (and most prpobably the warning log as well) be synchronous.
    In order to shut down a less important level of logging (e.g., on a production server), you may simply redirect related messages to /dev/null (i.e., to nowhere):

    local0.debug    /dev/null # -/var/log/my/debug.log
    

    One specific customization that is useful, especially to support some of the PHP log file parsing we’ll be discussing later in this article, is to use tab as the delimiter character in log messages. This can easily be done by adding the following file in /etc/rsyslog.d:

    # /etc/rsyslog.d/fixtab.conf
    $EscapeControlCharactersOnReceive off
    

    And finally, don’t forget to restart the syslog daemon after you make any configuration changes in order for them to take effect:

    service rsyslog restart
    

    Server Log Confguration

    Unlike application logs and error logs that you can write to, server logs are exclusively written to by the corresponding server daemons (e.g., web server, database server, etc.) on each request. The only “control” you have over these logs is to the extent that the server allows you to configure its logging functionality. Though there can be a lot to sift through in these files, they are often the only way to get a clear sense of what’s going on “under the hood” with your server.
    Let’s deploy our Symfony Standard example application on nginx environment with MySQL storage backend. Here’s the nginx host config we will be using:

    server {
        server_name my.log-sandbox;
        root /var/www/my/web;
        location / {
            # try to serve file directly, fallback to app.php
            try_files $uri /app.php$is_args$args;
        }
        # DEV
        # This rule should only be placed on your development environment
        # In production, don't include this and don't deploy app_dev.php or config.php
        location ~ ^/(app_dev|config)\.php(/|$) {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
        }
        # PROD
        location ~ ^/app\.php(/|$) {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param HTTPS off;
            # Prevents URIs that include the front controller. This will 404:
            # https://domain.tld/app.php/some-path
            # Remove the internal directive to allow URIs like this
            internal;
        }
        error_log /var/log/nginx/my_error.log;
        access_log /var/log/nginx/my_access.log;
    }
    

    With regard to the last two directives above: access_log represents the general requests log, while error_log is for errors, and, as with application error logs, it’s worth setting up extra monitoring to be alerted to problems so you can react quickly.
    Note: This is an intentionally oversimplified nginx config file that is provided for example purposes only. It pays almost no attention to security and performance and shouldn’t be used as-is in any “real” environment.
    This is what we get in /var/log/nginx/my_access.log after typing https://my.log-sandbox/app_dev.php/ in browser and hitting Enter.

    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /app_dev.php/ HTTP/1.1" 200 6715 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/framework/css/body.css HTTP/1.1" 200 6657 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/framework/css/structure.css HTTP/1.1" 200 1191 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/css/demo.css HTTP/1.1" 200 2204 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/images/welcome-quick-tour.gif HTTP/1.1" 200 4770 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/images/welcome-demo.gif HTTP/1.1" 200 4053 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /bundles/acmedemo/images/welcome-configure.gif HTTP/1.1" 200 3530 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:28 +0300] "GET /favicon.ico HTTP/1.1" 200 6518 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    192.168.56.1 - - [26/Apr/2015:16:13:30 +0300] "GET /app_dev.php/_wdt/e50d73 HTTP/1.1" 200 13265 "http://my.log-sandbox/app_dev.php/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
    

    This shows that, for serving one page, the browser actually performs 9 HTTP calls. 7 of those, however, are requests to static content, which are plain and lightweight. However, they still take network resources and this is what can be optimized by using various sprites and minification techniques.
    While those optimisations are to be discussed in another article, what’s relavant here is that we can log requests to static contents separately by using another location directive for them:

    location ~ \.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js)$ {
        access_log /var/log/nginx/my_access-static.log;
    }
    

    Remember that nginx location performs simple regular expression matching, so you can include as many static contents extensions as you expect to dispatch on your site.
    Parsing such logs is no different than parsing application logs.

    Other Logs Worth Mentioning

    Two other PHP logs worth mentioning are the debug log and data storage log.

    The Debug Log

    Another convenient thing about nginx logs is the debug log. We can turn it on by replacing the error_logline of the config with the following (requires that the nginx debug module be installed):

    error_log /var/log/nginx/my_error.log debug;
    

    The same setting applies for Apache or whatever other webserver you use.
    And incidentally, debug logs are not related to error logs, even though they are configured in the error_logdirective.
    Although the debug log can indeed be verbose (a single nginx request, for example, generated 127KB of log data!), it can still be very useful. Wading through a log file may be cumbersome and tedious, but it can often quickly provide clues and information that greatly help accelerate the debugging process.
    In particular, the debug log can really help with debugging nginx configurations, especially the most complicated parts, like location matching and rewrite chains.
    Of course, debug logs should never be enabled in a production environment. The amount of space they use also and the amount of information that they store means a lot of I/O load on your server, which can degrade the whole system’s performance significantly.

    Data Storage Logs

    Another type of server log (useful for debugging) is data storage logs. In MySQL, you can turn them on by adding these lines:

    [mysqld]
    general_log = 1
    general_log_file = /var/log/mysql/query.log
    

    These logs simply contain a list of queries run by the system while serving database requests in chronological order, which can be helpful for various debugging and tracing needs. However, they should not stay enabled on production systems, since they will generate extra unnecessary I/O load, which affects performance.

    Writing to Your Log Files

    PHP itself provides functions for opening, writing to, and closing log files (openlog(), syslog(), and closelog(), respectively).
    There are also numerous logging libraries for the PHP developer, such as Monolog (popular among Symfonyand Laravel users), as well as various framework-specific implementations, such as the logging capabilities incorporated into CakePHP. Generally, libraries like Monolog not only wrap syslog() calls, but also allow using other backend functionality and tools.
    Here’s a simple example of how to write to the log:

    <?php
    openlog(uniqid(), LOG_ODELAY, LOG_LOCAL0);
    syslog(LOG_INFO, 'It works!');
    

    Our call here to openlog:

    • configures PHP to prepend a unique identifier to each system log message within the script’s lifetime
    • sets it to delay opening the syslog connection until the first syslog() call has occurred
    • sets LOG_LOCAL0 as the default logging facility

    Here’s what the contents of the log file would look like after running the above code:

    # cat /var/log/my/info.log
    Mar  2 00:23:29 log-sandbox 54f39161a2e55: It works!
    

    Maximizing the Value of Your PHP Log Files

    Now that we’re all good with theory and basics, let’s see how much we can get from logs making as few changes as possible to our sample Symfony Standard project.
    First, let’s create the scripts src/log-begin.php (to properly open and configure our logs) and src/log-end.php (to log information about successful completion). Note that, for simplicity, we’ll just write all messages to the info log.

    # src/log-begin.php
    <?php
    define('START_TIME', microtime(true));
    openlog(uniqid(), LOG_ODELAY, LOG_LOCAL0);
    syslog(LOG_INFO, 'BEGIN');
    syslog(LOG_INFO, "URI\t{$_SERVER['REQUEST_URI']}");
    $browserHash = substr(md5($_SERVER['HTTP_USER_AGENT']), 0, 7);
    syslog(LOG_INFO, "CLIENT\t{$_SERVER['REMOTE_ADDR']}\t{$browserHash}"); <br />
    # src/log-end.php
    <?php
    syslog(LOG_INFO, "DISPATCH TIME\t" . round(microtime(true) - START_TIME, 2));
    syslog(LOG_INFO, 'END');
    

    And let’s require these scripts in app.php:

    <?php
    require_once(dirname(__DIR__) . '/src/log-begin.php');
    syslog(LOG_INFO, "MODE\tPROD");
    # original app.php contents
    require_once(dirname(__DIR__) . '/src/log-end.php');
    

    For the development environment, we want to require these scripts in app_dev.php as well. The code to do so would be the same as above, except we would set the MODE to DEV rather than PROD.
    We also want to track what controllers are being invoked, so let’s add one more line in Acme\DemoBundle\EventListener\ControllerListener, right at the beginning of the ControllerListener::onKernelController() method:

    syslog(LOG_INFO, "CONTROLLER\t" . get_class($event->getController()[0]));
    

    Note that these changes total a mere 15 extra lines of code, but can collectively yield a wealth of information.

    Analyzing the Data in Your Log Files

    For starters, let’s see how many HTTP requests are required to serve each page load.
    Here’s the info in the logs for one request, based on the way we’ve configured our logging:

    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: BEGIN
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: URI    /app_dev.php/
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: CLIENT 192.168.56.1    1b101cd
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: MODE   DEV
    Mar  3 12:04:23 log-sandbox 54f58724b1ccc: CONTROLLER Acme\DemoBundle\Controller\WelcomeController
    Mar  3 12:04:25 log-sandbox 54f58724b1ccc: DISPATCH TIME  4.51
    Mar  3 12:04:25 log-sandbox 54f58724b1ccc: END
    Mar  3 12:04:25 log-sandbox 54f5872967dea: BEGIN
    Mar  3 12:04:25 log-sandbox 54f5872967dea: URI    /app_dev.php/_wdt/59b8b6
    Mar  3 12:04:25 log-sandbox 54f5872967dea: CLIENT 192.168.56.1    1b101cd
    Mar  3 12:04:25 log-sandbox 54f5872967dea: MODE   DEV
    Mar  3 12:04:28 log-sandbox 54f5872967dea: CONTROLLER Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController
    Mar  3 12:04:29 log-sandbox 54f5872967dea: DISPATCH TIME  4.17
    Mar  3 12:04:29 log-sandbox 54f5872967dea: END
    

    So now we know that each page load is actually served with two HTTP requests.
    Actually there are two points worth mentioning here. First, the two requests per page load is for using Symfony in dev mode (which I have done throughout this article). You can identify dev mode calls by searching for /app-dev.php/ URL chunks. Second, let’s say each page load is served with two subsequent requests to the Symfony app. As we saw earlier in the nginx access logs, there are actually more HTTP calls, some of which are for static content.
    OK, now let’s surf a bit on the demo site (to build up the data in the log files) and let’s see what else we can learn from these logs.

    How many requests were served in total since the beginning of the logfile?

    # grep -c BEGIN info.log
    10
    

    Did any of them fail (did the script shut down without reaching the end)?

    # grep -c END info.log
    10
    

    We see that the number of BEGIN and END records match, so this tells us that all of the calls were successful. (If the PHP script had not completed successfully, it would not have reached execution of the src/log-end.php script.)

    What was the percentage of requests to the site root?

    # `grep -cE "\s/app_dev.php/$" info.log`
    2
    

    This tells us that there were 2 page loads of the site root. Since we previously learned that (a) there are 2 requests to the app per page load and (b) there were a total of 10 HTTP requests, the percentage of requests to the site root was 40% (i.e., 2×2/10).

    Which controller class is responsible for serving requests to site root?

    # grep -E "\s/$|\s/app_dev.php/$" info.log | head -n1
    Mar  3 12:04:20 log-sandbox 54f58724b1ccc: URI  /app_dev.php/
    # grep 54f58724b1ccc info.log | grep CONTROLLER
    Mar  3 12:04:23 log-sandbox 54f58724b1ccc: CONTROLLER   Acme\DemoBundle\Controller\WelcomeController
    

    Here we used the unique ID of a request to check all log messages related to that single request. We thereby were able to determine that the controller class responsible for serving requests to site root is Acme\DemoBundle\Controller\WelcomeController.

    Which clients with IPs of subnet 192.168.0.0/16 have accessed the site?

    # grep CLIENT info.log | cut -d":" -f4 | cut -f2 | sort | uniq
    192.168.56.1
    

    As expected in this simple test case, only my host computer has accessed the site. This is of course a very simplistic example, but the capability that it demonstrates (of being able to analyse the sources of the traffic to your site) is obviously quite powerful and important.

    How much of the traffic to my site has been from FireFox?

    Having 1b101cd as the hash of my Firefox User-Agent, I can answer this question as follows:

    # grep -c 1b101cd info.log
    8
    # grep -c CLIENT info.log
    10
    

    Answer: 80% (i.e., 8/10)

    What is the percentage of requests that yielded a “slow” response?

    For purposes of this example, we’ll define “slow” as taking more than 5 seconds to provide a response. Accordingly:

    # grep "DISPATCH TIME" info.log | grep -cE "\s[0-9]{2,}\.|\s[5-9]\."
    2
    

    Answer: 20% (i.e., 2/10)

    Did anyone ever supply GET parameters?

    # grep URI info.log | grep \?
    

    No, Symfony standard uses only URL slugs, so this also tells us here that no one has attempted to hack the site.
    These are just a handful of relatively rudimentary examples of the ways in which logs files can be creatively leveraged to yield valuable usage information and even basic analytics.

    Other Things to Keep in Mind

    Keeping Things Secure

    Another heads-up is for security. You might think that logging requests is a good idea, in most cases it indeed is. However, it’s important to be extremely careful about removing any potentially sensitive user information before storing it in the log.

    Fighting Log File Bloat

    Since log files are text files to which you always append information, they are constantly growing. Since this is a well-known issue, there are some fairly standard approaches to controlling log file growth.
    The easiest is to rotate the logs. Rotating logs means:

    • Periodically replacing the log with a new empty file for further writing
    • Storing the old file for history
    • Removing files that have “aged” sufficiently to free up disk space
    • Making sure the application can write to the logs uniterrupted when these file changes occur

    The most common solution for this is logrotate, which ships pre-installed with most *nix distributions. Let’s see a simple configuration file for rotating our logs:

    /var/log/my/debug.log
    /var/log/my/info.log
    /var/log/my/warning.log
    /var/log/my/error.log
    {
        rotate 7
        daily
        missingok
        notifempty
        delaycompress
        compress
        sharedscripts
        postrotate
            invoke-rc.d rsyslog rotate > /dev/null
        endscript
    }
    

    Another, more advanced approach is to make rsyslogd itself write messages into files, dynamically created based on current date and time. This would still require a custom solution for removal of older files, but lets devops manage timeframes for each log file precisely. For our example:

    $template DynaLocal0Err,        "/var/log/my/error-%$NOW%-%$HOUR%.log"
    $template DynaLocal0Info,       "/var/log/my/info-%$NOW%-%$HOUR%.log"
    $template DynaLocal0Warning,    "/var/log/my/warning-%$NOW%-%$HOUR%.log"
    $template DynaLocal0Debug,      "/var/log/my/debug-%$NOW%-%$HOUR%.log"
    local1.err      -?DynaLocal0Err
    local1.info     -?DynaLocal0Info
    local1.warning  -?DynaLocal0Warning
    local1.debug    -?DynaLocal0Debug
    

    This way, rsyslog will create an individual log file each hour, and there won’t be any need for rotating them and restarting the daemon. Here’s how log files older than 5 days can be removed to accomplish this solution:

    find /var/log/my/ -mtime +5 -print0 | xargs -0 rm
    

    Remote Logs

    As the project grows, parsing information from logs gets more and more resource hungry. This not only means creating extra server load; it also means creating peak load on the CPU and disk drives at the times when you parse logs, which can degrade server response time for users (or in a worst case can even bring the site down).
    To solve this, consider setting up a centralized logging server. All you need for this is another box with UDP port 514 (default) open. To make rsyslogd listen to connections, add the following line to its config file:

    $UDPServerRun 514
    

    Having this, setting up the client is then as easy as:

    *.*   @HOSTNAME:514
    

    (where HOSTNAME is the host name of your remote logging server).

    Conclusion

    While this article has demonstrated some of the creative ways in which log files can offer way more valuable information than you may have previously imagined, it’s important to emphasize that we’ve only scratched the surface of what’s possible. The extent, scope, and format of what you can log is almost limitless. This means that – if there’s usage or analytics data you want to extract from your logs – you simply need to log it in a way that will make it easy to subsequently parse and analyze. Moreover, that analysis can often be performed with standard Linux command line tools like grep, sed, or awk.
    Indeed, PHP log files are a most powerful tool that can be of tremendous benefit.

    Resources

    Code on GitHub: https://github.com/isanosyan/toptal-blog-logs-post-example


    Appendix: Reading and Manipulating Log Files in the Unix Shell

    Here is a brief intro to some of the more common *nix command line tools that you’ll want to be familiar with for reading and manipulating your log files.

    • cat is perhaps the most simple one. It prints the whole file to the output stream. For example, the following command will print logfile1 to the console:
      cat logfile1
      
    • > character allows user to redirect output, for example into another file. Opens target stream in write mode (which means wiping target contents). Here’s how we replace contents of tmpfile with contents of logfile1:
      cat logfile1 > tmpfile
      
    • >> redirects output and opens target stream in append mode. Current contents of target file will be preserved, new lines will be added to the bottom. This will append logfile1 contents to tmpfile:
      cat logfile1 >> tmpfile
      
    • grep filters file by some pattern and prints only matching lines. Command below will only print lines of logfile1 containing Bingo message:
      grep Bingo logfile1
      
    • cut prints contents of a single column (by number starting from 1). By default searches for tab characters as delimiters between column. For example, if you have file full of timestamps in format YYYY-MM-DD HH:MM:SS, this will allow you to print only years:
      cut -d"-" -f1 logfile1
      
    • head displays only the first lines of a file
    • tail displays only the last lines of a file
    • sort sorts lines in the output
    • uniq filters out duplicate lines
    • wc counts words (or lines when used with the -l flag)
    • | (i.e., the “pipe” symbol) supplies output from one command as input to the next. Pipe is very convenient for combining commands. For example, here’s how we can find months of 2014 that occur within a set of timestamps:
      grep -E "^2014" logfile1 | cut -d"-" -f2 | sort | uniq
      

    Here we first match lines against regular expression “starts with 2014”, then cut months. Finally, we use combination of sort and uniq to print occurrences only once.

  • Building an IMAP Email Client with PHP

    Building an IMAP Email Client with PHP

    [pt_text]Developers sometimes run into tasks that require access to email mailboxes. In most cases, this is done using the Internet Message Access Protocol, or IMAP. As a PHP developer, I first turned to PHP’s built in IMAP library, but this library is buggy and impossible to debug or modify. It is also not possible to customize IMAP commands to make full use of the protocol’s abilities.
    So today, we will create a working IMAP email client from the ground up using PHP. We will also see how to use Gmail’s special commands.
    We will implement IMAP in a custom class, imap_driver. I will explain each step while building the class. You can download the whole imap_driver.php at the end of the article.

    Establishing a Connection

    IMAP is a connection-based protocol and typically operates over TCP/IP with SSL security, so before we can make any IMAP calls we must open the connection.
    We need to know the URL and port number of the IMAP server we want to connect to. This information is usually advertised in the service’s website or documentation. For example, for Gmail, the URL is ssl://imap.gmail.com on port 993.
    Since we want to know if initialization was successful, we will leave our class constructor empty, and all the connections will be made in a custom init() method, which will return false if the connection cannot be established:

    class imap_driver
    {
        private $fp;                      // file pointer
        public $error;                    // error message
        ...
        public function init($host, $port)
        {
            if (!($this->fp = fsockopen($host, $port, $errno, $errstr, 15))) {
                $this->error = "Could not connect to host ($errno) $errstr";
                return false;
            }
            if (!stream_set_timeout($this->fp, 15)) {
                $this->error = "Could not set timeout";
                return false;
            }
            $line = fgets($this->fp);     // discard the first line of the stream
            return true;
        }
        private function close()
        {
            fclose($this->fp);
        }
        ...
    }
    

    In the above code, I’ve set a timeout of 15 seconds, both for fsockopen() to establish the connection, and for the data stream itself to respond to requests once it is open. It is important to have a timeout for every call to the network because, often enough, the server won’t respond, and we must be able to handle such a freeze.
    I also grab the first line of the stream and ignore it. Usually this just a greeting message from the server, or a confirmation that it is connected. Check your particular mail service’s documentation to make sure this is the case.
    Now we want to run the above code to see that init() is successful:

    include("imap_driver.php");
    // test for init()
    $imap_driver = new imap_driver();
    if ($imap_driver->init('ssl://imap.gmail.com', 993) === false) {
        echo "init() failed: " . $imap_driver->error . "n";
        exit;
    }
    

    Basic IMAP Syntax

    Now that we have an active socket open to our IMAP server, we can start sending IMAP commands. Let us take a look at IMAP syntax.
    The formal documentation can be found in Internet Engineering Task Force (IETF) RFC3501. IMAP interactions typically consist of the client sending commands, and the server responding with an indication of success, along with whatever data may have been requested.
    The basic syntax for commands is:

    line_number command arg1 arg2 ...
    

    The line number, or “tag”, is a unique identifier for the command, that the server uses to indicate which command it is responding to should it be processing multiple commands at once.
    Here is an example, showing the LOGIN command:

    00000001 LOGIN example@gmail.com password
    

    The server’s response may begin with an “untagged” data response. For instance, Gmail responds to a successful login with an untagged response containing information about the server’s capabilities and options, and a command to fetch an email message will receive an untagged response containing the message body. In either case, a response should always end with a “tagged” command completion response line, identifying the line number of the command that the response applies to, a completion status indicator, and additional metadata about the command, if any:

    line_number status metadata1 metadata2 ...
    

    Here is how Gmail responds to the LOGIN command:

    • Success:
    * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS
    COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS
    00000001 OK example@gmail.com authenticated (Success)
    
    • Failure:
    00000001 NO [AUTHENTICATIONFAILED] Invalid credentials (Failure)
    

    The status can be either OK, indicating success, NO, indicating failure, or BAD, indicating an invalid command or bad syntax.

    Implementing Basic Commands:

    Let’s make a function to send a command to the IMAP server, and retrieve the response and endline:

    class imap_driver
    {
        private $command_counter = "00000001";
        public $last_response = array();
        public $last_endline = "";
        private function command($command)
        {
            $this->last_response = array();
            $this->last_endline  = "";
            fwrite($this->fp, "$this->command_counter $commandrn");            // send the command
            while ($line = fgets($this->fp)) {                                   // fetch the response one line at a time
                $line = trim($line);                                             // trim the response
                $line_arr = preg_split('/s+/', $line, 0, PREG_SPLIT_NO_EMPTY);  // split the response into non-empty pieces by whitespace
                if (count($line_arr) > 0) {
                    $code = array_shift($line_arr);                              // take the first segment from the response, which will be the line number
                    if (strtoupper($code) == $this->command_counter) {
                        $this->last_endline = join(' ', $line_arr);              // save the completion response line to parse later
                        break;
                    } else {
                        $this->last_response[] = $line;                          // append the current line to the saved response
                    }
                } else {
                    $this->last_response[] = $line;
                }
            }
            $this->increment_counter();
        }
        private function increment_counter()
        {
            $this->command_counter = sprintf('%08d', intval($this->command_counter) + 1);
        }
        ...
    }
    

    The LOGIN Command

    Now we can write functions for specific commands that call our command() function under the hood. Let’s write a function for the LOGIN command:

    class imap_driver
    {
        ...
        public function login($login, $pwd)
        {
            $this->command("LOGIN $login $pwd");
            if (preg_match('~^OK~', $this->last_endline)) {
                return true;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    Now we can test it like this. (Note that you must have an active email account to test against.)

    ...
    // test for login()
    if ($imap_driver->login('[email protected]', 'password') === false) {
        echo "login() failed: " . $imap_driver->error . "n";
        exit;
    }
    

    Note that Gmail is very strict about security by default: it will not allow us to access an email account with IMAP if we have default settings and try to access it from a country other than the account profile’s country. But it is easy enough to fix; just set less secure settings in your Gmail account, as described here.

    The SELECT Command

    Now let’s see how to select an IMAP folder in order to do something useful with our email. The syntax is similar to that of LOGIN, thanks to our command() method. We use the SELECT command instead, and specify the folder.

    class imap_driver
    {
        ...
        public function select_folder($folder)
        {
            $this->command("SELECT $folder");
            if (preg_match('~^OK~', $this->last_endline)) {
                return true;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    To test it, let’s try to select the INBOX:

    ...
    // test for select_folder()
    if ($imap_driver->select_folder("INBOX") === false) {
        echo "select_folder() failed: " . $imap_driver->error . "n";
        return false;
    }
    

    Implementing Advanced Commands

    Let’s look at how to implement a few of IMAP’s more advanced commands.

    The SEARCH Command

    A common routine in email analysis is to search for emails in a given date range, or search for flagged emails, and so on. The search criteria must be passed to the SEARCH command as an argument, with space as a separator. For example, if we want to get all emails since November 20th, 2015, we must pass the following command:

    00000005 SEARCH SINCE 20-Nov-2015
    

    And the response will be something like this:

    * SEARCH 881 882
    00000005 OK SEARCH completed
    

    Detailed documentation of possible search terms can be found here The output of a SEARCH command is a list of UIDs of emails, separated by whitespace. A UID is a unique identifier of an email in the user’s account, in chronological order, where 1 is the oldest email. To implement the SEARCH command we must simply return the resulting UIDs:

    class imap_driver
    {
        ...
        public function get_uids_by_search($criteria)
        {
            $this->command("SEARCH $criteria");
            if (preg_match('~^OK~', $this->last_endline)
            && is_array($this->last_response)
            && count($this->last_response) == 1) {
                $splitted_response = explode(' ', $this->last_response[0]);
                $uids              = array();
                foreach ($splitted_response as $item) {
                    if (preg_match('~^d+$~', $item)) {
                        $uids[] = $item;                        // put the returned UIDs into an array
                    }
                }
                return $uids;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    To test this command, we will get emails from the last three days:

    ...
    // test for get_uids_by_search()
    $ids = $imap_driver->get_uids_by_search('SINCE ' . date('j-M-Y', time() - 60 * 60 * 24 * 3));
    if ($ids === false)
    {
        echo "get_uids_failed: " . $imap_driver->error . "n";
        exit;
    }
    

    The FETCH Command with BODY.PEEK

    Another common task is to get email headers without marking an email as SEEN. From the IMAP manual, thecommand for retrieving all or part of an email is FETCH. The first argument indicates which part we are interested in, and typically BODY is passed, which will return the entire message along with its headers, and mark it as SEEN. The alternative argument BODY.PEEK will do the same thing, without marking the message as SEEN.
    IMAP syntax requires our request to also specify, in square brackets, the section of the email that we want to fetch, which in this example is [HEADER]. As a result, our command will look like this:

    00000006 FETCH 2 BODY.PEEK[HEADER]
    

    And we will expect a response that looks like this:

    * 2 FETCH (BODY[HEADER] {438}
    MIME-Version: 1.0
    x-no-auto-attachment: 1
    Received: by 10.170.97.214; Fri, 30 May 2014 09:13:45 -0700 (PDT)
    Date: Fri, 30 May 2014 09:13:45 -0700
    Message-ID: <CACYy8gU+UFFukbE0Cih8kYRENMXcx1DTVhvg3TBbJ52D8OF6nQ@mail.gmail.com>
    Subject: The best of Gmail, wherever you are
    From: Gmail Team <mail-noreply@google.com>
    To: Example Test <example@gmail.com>
    Content-Type: multipart/alternative; boundary=001a1139e3966e26ed04faa054f4
    )
    00000006 OK Success
    

    In order to build a function for fetching headers, we need to be able to return the response in a hash structure (key/value pairs):

    class imap_driver
    {
        ...
        public function get_headers_from_uid($uid)
        {
            $this->command("FETCH $uid BODY.PEEK[HEADER]");
            if (preg_match('~^OK~', $this->last_endline)) {
                array_shift($this->last_response);                  // skip the first line
                $headers    = array();
                $prev_match = '';
                foreach ($this->last_response as $item) {
                    if (preg_match('~^([a-z][a-z0-9-_]+):~is', $item, $match)) {
                        $header_name           = strtolower($match[1]);
                        $prev_match            = $header_name;
                        $headers[$header_name] = trim(substr($item, strlen($header_name) + 1));
                    } else {
                        $headers[$prev_match] .= " " . $item;
                    }
                }
                return $headers;
            } else {
                $this->error = join(', ', $this->last_response);
                $this->close();
                return false;
            }
        }
        ...
    }
    

    And to test this code we just specify the UID of the message we are interested in:

    ...
    // test for get_headers_by_uid
    if (($headers = $imap_driver->get_headers_from_uid(2)) === false) {
        echo "get_headers_by_uid() failed: " . $imap_driver->error . "n";
        return false;
    }
    

    Gmail IMAP Extensions

    Gmail provides a list of special commands that can make our life much easier. The list of Gmail’s IMAP extension commands is available here. Let’s review a command that, in my opinion, is the most important one:X-GM-RAW. It allows us to use Gmail search syntax with IMAP. For example, we can search for emails that are in the categories Primary, Social, Promotions, Updates, or Forums.
    Functionally, X-GM-RAW is an extension of the SEARCH command, so we can reuse the code that we have above for the SEARCH command. All we need to do is add the keyword X-GM-RAW and criteria:

    ...
    // test for gmail extended search functionality
    $ids = $imap_driver->get_uids_by_search(' X-GM-RAW "category:primary"');
    if ($ids === false) {
        echo "get_uids_failed: " . $imap_driver->error . "n";
        return false;
    }
    

    The above code will return all UIDs that are listed in the “Primary” category.
    Note: As of December 2015, Gmail often confuses the “Primary” category with the “Updates” category on some accounts. This is a Gmail bug that hasn’t been fixed yet.

    Conclusion

    You’ve got mail. Now what? Read how to build a custom IMAP email client in PHP, and check the mail on your terms.
    Overall, the custom socket approach provides more freedom to the developer. It makes it possible to implement all commands in IMAP RFC3501. It will also give you better control over your code, since you don’t have to wonder what’s happening “behind the scenes.”

    The full imap_driver class that we implemented in this article can be found here. It can be used as-is, and it will take only a few minutes for a developer to write a new function or request to their IMAP server. I’ve also included a debug feature in the class for a verbose output.

  • The Vital Guide to PHP Interviewing

    The Vital Guide to PHP Interviewing

    The Vital Guide to PHP Interviewing

    Ubiquitous…that is definitely one word you could use to describe PHP in relation to the web. It really is everywhere. In terms of server-side programming languages, it is by far the most widely used, powering more than 80% of today’s websites (with the next runner up, ASP.NET, trailing way behind at a mere 17%).
    Why? What makes PHP so popular and widely-used? While there’s no single answer to this question, PHP’s ease of use is certainly a significant contributing factor. PHP newbies can get up-to-speed and build dynamic PHP-based content into their web sites with a minimum of programming expertise required.
    But therein lies much of the challenge of finding highly-skilled PHP developers. PHP’s relatively low barrier-to-entry and 20 year history means that PHP developers have become practically as ubiquitous as the technology itself. Yet while many can legitimately claim to “know” PHP, those who are true experts in the language are capable of producing software that is much more scalable, functional, robust, and maintainable.

    So how do you distinguish those who have real competency in PHP from those with just a cursory knowledge, let alone those who are in the top 1% of candidates?
    Toward that goal, this guide offers a sampling of effective questions to help evaluate the breadth and depth of a candidate’s mastery of PHP. It is important to bear in mind, though, that these sample questions are intended merely as a guide. Not every “A” candidate worth hiring will be able to properly answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains as much of an art as it does a science (see In Search of the Elite Few).
    Note that we have tried to keep this guide focused on modern PHP (i.e., versions 5.3 and beyond), but there are references to concepts and functions that have been around for a long time and should be familiar to any qualified PHP developer.

    Key PHP Concepts and Paradigms

    There are a number of key concepts and paradigms that are essential for a PHP expert to be well-versed in. Here are some examples.
    Q: Describe a closure in PHP. Provide examples of when, why, and how they can be used.
    Closures become useful when some piece of logic needs to be performed in a limited scope but retain the ability to interact with the environment external to that scope. The first building block of a closure is the anonymous, or lambda style, function which has no name associated with it. For example:

    # The 2nd argument to array_walk is an anonymous function
    array_walk($array, function($dog) {
        echo $dog->bark();
    });
    

    Although they themselves have no name associated with them, anonymous functions can be assigned to a variable or passed around as callbacks by higher order functions that require them. For example:

    # Define an anonymous function and assign it to a variable
    # named $dogs_bark.
    $dogs_bark = function($dog) {
        echo $dog->bark();
    }
    array_walk($array, $dogs_bark);
    

    Under the hood in PHP, anonymous functions are implemented using the Closure class.
    The contents of an anonymous function exist within their own scope, independent of the scope in which they were created. However, it is possible to explicitly bind one or more variables from the external scope to be referenceable within the anonymous function via the use clause in the function definition. Let’s illustrate:

    class Dog {
        public function bark() { echo 'woof'; }
    }
    $dogs_bark = function($dog) use (&$collar) { # bind by reference
        if ($collar == 'fitsWell'){
             echo $dog->bark(); # 'woof'
        } else {
             echo 'no bark';    # collar is too tight to bark
        }
    };
    $dog = new Dog;
    $collar = 'fitsWell'; # external variable
    $dogs_bark($dog); # 'woof'
    $collar = 'tight';
    $dogs_bark($dog); # 'no bark'
    

    This ability to access these external variables within a closure becomes particularly useful when using higher order functions. Take for example our array_walk usage from above which, like other functions of this type, operates in a very specific way on the subject variables which it is passed. As the function iterates over the $array, only the current value and key are passed to the anonymous function callback. There is no opportunity to pass in the $collar variable without the closure and it’s use clause . We could use the globalkeyword, but would needlessly pollute the global namespace with a variable that only makes sense in our very limited scope.
    Closures have additional object oriented uses as well. PHP 5.4 brings new methods to the Closure class’ interface. Specifically, the new bind and bindTo methods can be used to bind to new objects for the closure to operate on, e.g.:

    Closure::bindTo($newthis, $newscope);
    

    This method will actually duplicate the closure itself and bind its scope to that new object, so $this actually references $newthis in the object context. To help illustrate, let’s modify the $dogs_bark function to use $this and then bind it to a new Dog object:

    # define the closure, but not bound yet to any object
    $dogs_bark = function() {
        echo $this->sound;  # where this is a property
    };
    $new_dog = new Dog();
    # now create a new closure bound to the $new_dog object
    $new_closure = $dogs_bark->bindTo($new_dog);
    $new_closure();   # echoes the sound
    

    The fact that a closure can be assigned to a variable and now has access to $this is quite powerful. In particular, this means that it can become a callable property of another object and essentially become a method of that object. For example:

    $dog = new Dog();
    $dog->closure = $dogs_bark;
    $dog->closure();
    

    This makes it possible to change and add to the behavioral capabilities of an object at runtime without the need to alter the defining class signature. Very useful when functionality enhancements are needed, but the actual code cannot be touched or where the need for the enhanced functionality is limited in scope.
    Q: Explain the use and purpose of the global keyword in PHP. Provide an example of a case where its use would be appropriate, as well as one where it would not be.
    In the days of “PHP gone by”, the language’s object oriented implementation was much less sophisticated than it is today. It is therefore not uncommon to find older “legacy” PHP code that makes fairly extensive use of the global keyword. In many ways, overuse of global variables “flies in the face” of modern object-oriented programming (OOP) best practices, as it may lead to intertwined dependencies between classes, difficulty decoupling disparate units of logic from one another, and pollution of the global namespace with variables that have no (or very limited) use in that context.
    Consider the following simple example:

    class Dog {
        function bark() {
            global $sounds;
            return $sounds->bark();
        }
    }
    

    This introduces a hidden dependency of the Dog class on the global $sounds object. While there may be cases where this would be justified (e.g., a system with one single well-defined set of sounds that is never modified), generally speaking, it would be much better to explicitly pass the relevant $sounds object to the Dog class’ constructor, which would then be stored and used within that instance of the class; e.g.:

    class Dog {
        protected $sounds;
        function __construct($sounds) {
            $this->sounds = $sounds;
        }
        public function bark() {
            return $this->getSounds()->bark();
        }
        public function getSounds() {
            return $this->sounds;
        }
    }
    

    But as is true with most things in coding, never say never. There are, in fact, a number of robust and stable products out there written in PHP that make heavy use of globals. The WordPress Codex, which powers roughly 20% of the websites on the web (and rising yearly), Joomla! 1.5 (which is still in wide use), and theiLance Enterprise Auction system are all examples of projects that have been around for years and make use of ‘mature’ globals. Similarly, there may be situations where the use of globals in your code is appropriate, but their use should always be approach with caution.
    Q: Describe namespacing in PHP and why it is useful.
    One of the newer additions to PHP’s support for OOP is the namespace. As the name implies, a namespace defines a scope in a program where class, interface, function, variable, and constant definitions won’t produce name collisions with similarly named items in other namespaces.
    Prior to PHP 5.4, class names would often become quite long in an attempt to match the package hierarchy and avoid name collisions. For example, let’s say we have a Dogs class defined in the model of the Dog_Poundapplication. Without namespacing, we might feel compelled to provide a verbose name for our class such as the following:

    class Dog_Pound_Model_Dogs {  # wow, that's a mouthful!
        function getDogs();
    }
    

    Namespacing helps alleviate this issue by enabling the developer to explicitly specify the namespace within which all named items (classes, variables, etc.) are to be defined. With namespacing, the above verbose class name could be replaced with:

    namespace dog_poundmodel;  # specify the current namespace
    class Dogs {   # only "Dogs" defined in dog_poundmodel
        function getDogs();
    }
    $dogs = new Dogs; # unambiguous since only one in this namespace
    

    Relative namespace references are supported as well. For example, when in the dog_pound namespace, you can use the following to instantiate your class:

    $dogs = new modelDogs  # only one "model" defined in dog_pound
    

    In addition, named items in other namespaces can be imported in other files and can then be referenced directly. This is done via the use operator as follows:

    namespace thisnewnamespace;  # our current namespace
    # import Dogs from dog_poundmodel namespace and reference it
    use dog_poundmodelDogs;
    $dogs = new Dogs;
    

    Q: What are traits? Describe their major characteristics and why they are useful. Give an example of a trait declaration and a class that uses multiple traits.
    Traits are an excellent addition to PHP 5.4 that allow behaviors to be added to a class, without needing to extend a parent class to inherit the desired functionality (prior to PHP 5.4, this could only be done via a mixinclass pattern at runtime). Additionally, you can make use of multiple Traits in a single class. This makes them a powerful aid in the organization and separation of concerns in the codebase and, as such, helps to honor thecomposition over inheritance design principle.
    Here are a couple of simple trait definition examples:

    trait Movement {
        public function topSpeed() {
            $this->speed = 100;
            echo "Running at 100 %!" . PHP_EOL;
        }
        public function stop() {
            $this->speed = 0;
            echo "Stopped moving!" . PHP_EOL;
        }
    }
    trait Speak {
        public function makeSound(){
            echo $this->sound . PHP_EOL;
        }
    }
    

    The use keyword is once again employed, this time for importing from another namespace to include one or more traits in a class definition. For example:

    class Dog {
        use Movement, Speak;  // Dog now has these capabilities!
        protected $sound;
        function __construct() {
            $this->sound = 'bark';
        }
    }
    $dog = new Dog();
    $dog->topSpeed();  // from Movement trait
    $dog->stop();      // from Movement trait
    $dog->makeSound(); // from Speak trait
    

    PHP at Your Fingertips

    Committing to memory what can easily be found in a language specification or API document is no indicator of proficiency. But that said, someone who is intimately familiar with a programming language will have its syntactical and functional details and nuances at his or her fingertips. Here are some questions that help evaluate this dimension of a candidate’s expertise.
    Q: Describe the relationship between php://input and $_POST. How would you access the php://inputstream?
    In the simplest terms, the $_POST superglobal is the formatted or parsed content of the body of a request made to the server with the post method.

    POST /php-hiring-guide/php-post.php HTTP/1.1
    Host: toptal.com
    Referer: http:///toptal.php/php-hiring-guide/php.php
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 63
    article_name=PHP Hiring Guide&tag_line=You are hired!&action=Submit
    

    The body of the request can be accessed through the PHP’s input stream the same as any other file:

    $input = file_get_contents("php://input");
    

    Q: Name and define at least five superglobals that begin with $_. Describe their relationship to the $GLOBALS variable.

    • $_POST – a hash of key value pairs sent to the server with the ‘post’ method
    • $_GET – a hash of key value pairs sent to the server with the ‘get’ method
    • $_REQUEST – an amalgamation of $_GET and $_POST
    • $_SERVER – a hash of variables set specifically by the web server, and relevant to the execution of the program
    • $_ENV – a hash of variables related to the host machine and it’s configuration
    • $_SESSION – a hash of variables that are meant to be persisted between page views or separate application executions
    • $_COOKIE – a hash of variables that are to be stored with the client
    • $_FILES – a special type of request hash that holds input data related to an uploaded set of files

    Akin to the global keyword in PHP is the $GLOBALS super global variable. As the name suggests, superglobals are automatic global variables and as such are stored in $GLOBALS. For example, the $_ENV superglobal could alternatively be accessed via $GLOBALS["_ENV"].
    Q: Explain the purpose and usage of the __get, __set, __isset, __unset, __call, and __callStatic“magic” methods. When, how, and why (and perhaps why not) should each be used?
    The first four methods in our list, __get, __set, __isset, and __unset are used for property overloading of an object. They let us define how the outside world is able to interact with properties that have a private or protected visibility, and properties that don’t even exist in our object.

    # 'whiskers' is not defined in the Dog class but is handled by
    # the Dog class' __get method as follows:
    function __get($name) {
        if ($name == 'whiskers') {
            # only create one whiskersService per instance
            if (! isset($this->whiskersService)) {
                $this->whiskersService = new Whiskers($this);
            }
            # so calls to 'whiskers' will load the wiskersService
            return  $this->whiskersService->load();
        }
    }
    

    A caller can then simply retrieve the whiskers property like so:

    $hairs = $dog->whiskers;
    

    By using the __get method to “intercept” this reference to a seemingly public property we are able to obscure the implementation details of one or more of the object’s properties.
    Use of the __set method is similar. For example:

    function __set($name, $value) {
        if ($name == 'whiskers') {
            if ($value instanceOf Whisker) {
                $this->whiskersService->setData($value);
                return $this->whiskersService->getData();
            } else {
                throw new WhiskerException("That's not a whisker");
                return false;
            }
        }
    }
    

    A caller can then simply set the whiskers property like so:

    $dog->whiskers = $hairs;
    

    This statement automatically invokes the __set method, using 'whiskers' as its first argument and the right side of the assignment as the second argument.
    Lastly, the __isset and __unset methods complete the quartet. They each take just one argument, the $name of the property to be evaluated or operated on; e.g.:

    function __isset($name) {
        if ($name == 'whiskers') {
            return (bool) is_object($this->whiskersService) &&
                                    !empty($this->whiskersService->getData());
        }
    }
    function __unset($name) {
        if ($name == 'whiskers' && is_object($this->whiskersService)) {
            # we don't want to completely kill the service:
            $this->whiskersService->reset();
        }
    }
    

    The other two methods, __call and __callStatic, perform a similar function for classes, but give us method overloading. Through their use we can define how a class should react when an undefined, protected, or private method is called.
    In a __call implementation where we we want to ensure all “non-visible” method calls get returned the payload from the whiskersService we might do something like:

    public function __call($method, $args) {
        return $this->whiskersService->load();
    }
    

    __callStatic has the same arguments, the same functionality and allow for this same interaction, but outside of a specific object context. This means that if we have this method defined we can use the ClassName::notVisibleMethod() syntax; e.g.:

    public function __callStatic($method, $args) {
        if (!is_object(static::$whiskersService)) {
            static::$whiskersService = new Whiskers(__CLASS__);
        }
        return static::$whiskersService->load();
    }
    $hairs = Dog::whiskers();
    

    In the above set of examples, we have encapsulated the whiskers implementation from the outside world and made it the only available object exposed in this way. The clients of such properties and methods do not need to know anything about the underlying whiskersService or how the Dogs class is storing its data at all.
    Collectively, these methods increase our ability to flexibly compose objects. The opportunity for object abstraction and encapsulation, and thus reusable, more compact code (and ultimately a more manageable system as a result) are also increased.
    Care should be taken, though, in using these convenient methods, as the benefits can come at a cost. They are slower than straight access to an otherwise public property in question, and also slower than defined getters and setters. They also hamper use of certain useful capabilities (such as object reflection, autocomplete in your IDE, automatic documentation utilities like PHPDocumentor, and so on). So if these are facilities you want or need to rely on, you may consider defining methods and properties explicitly instead. As with most things, there’s no across-the-board right answer. The pros and cons should be evaluated on a case-by-case basis.
    Q: Describe one or more Standard PHP Library (SPL) data structures. Give usage examples.
    Most of PHP development deals with getting and processing data from one source or another, such as a local database, local files, a remote API, etc. As such, developers spend a great deal of time getting, organizing, moving, and manipulating that data. In some cases, an array just won’t cut it in terms of memory usage and performance and therefore better data structures are called for.
    Also, with so much talk and focus on frameworks (this page could be filled with names of PHP frameworks!), it could be difficult to find a developer who has a great deal of experience with the particular framework that your project is using. The net effect of a such an active development community is that the distribution of developers working with a particular framework starts to shrink, and could make it harder for you to find that specific skill.
    One area to focus on, and where you be reasonably sure that a PHP expert will have familiarity, is in the use of and general makeup of the Standard PHP Library (SPL). If the candidate has a solid background here, the chances of success for that candidate working into and adding value to your application are greater, regardless of the specific frameworks being used in your environment.
    Specifically, a candidate should be familiar with some or all of the nine SPL data structures listed in the PHP Manual. Many provide highly similar functionality to one another, but the slight variations make each one more perfectly suited to a particular use. Here’s a brief overview:

    • SplDoublyLinkedList. Each element in this list holds links to the node before it and the node after it in the list. Picture that you are on line at the bank, but you are only able to see the person in front and the person behind you. That is analogous to the ‘link’ relationship between elements in a SplDoublyLinkedList. Inserting an element into the list is akin to someone cutting in front of you at the bank (but you then suddenly forget who was in front of you, and that person also forgets you entirely). Enables efficient transversal through a dataset and lets you list and add large amounts of data, with no internal need to re-hash.
    • SplQueue and SplStack. Very similar to the SplDoublyLinkedList are the SplQueue and SplStack. Both of these are essentially SplDoublyLinkedLists with different iterator flags (IT_MODE_LIFO is “Last In First Out” and IT_MODE_FIFO is “First In First Out”), which govern which order the elements are read in and what to do with those elements after they have been processed. One other distinction is that the SplQueue API might be considered a bit more intuitive, supplying an enqueue() method (rather than push()) and a dequeue()method (rather than shift()).
    • SplHeap. Represented internally as a binary tree, where each node in the tree has a maximum of two child nodes. It is an abstract class which must be extended to define a compare() method. This method is then used to perform real time sorting whenever a value is inserted into the tree.
    • SplMaxHeap and SplMinHeap. Concrete implementations of the SplHeap abstract class. SplMaxHeapprovides a compare() method that maintains values in order from highest to lowest, whereas SplMinHeapprovides a compare() method that maintains values in order from lowest to highest.
    • SplPriorityQueue. Similar to an SplHeap, but sorting is done based on an additional “priority” value supplied for each member.
    • SplFixedArray. Similar to a regular array, but indices can only be integers and the length of the array is fixed. It provides improved speed when implementing an array. There is no processing speed benefit over an array, the interface is optimized so that the objects don’t need to be hashed manually when adding elements.
    • SplObjectStorage. Provides an interface for mapping objects to data or simply providing a container for a set of objects. Essentially, it can use an object much like an associative array key to relate that object to some data or to no data at all.

    Q: What will $x be equal to after the statement $x = 3 + "15%" + "$25"?
    The correct answer is 18. Now let’s explain why.
    PHP supports automatic type conversion based on the context in which a variable or value is being used.
    If you perform an arithmetic operation on an expression that contains a string, that string will be interpreted as the appropriate numeric type for the purposes of evaluating the expression. So, if the string begins with one or more numeric characters, the remainder of the string (if any) will be ignored and the numeric value is interpreted as the appropriate numeric type. On the other hand, if the string begins with a non-numeric character, then it will evaluate to zero.
    With that understanding, we can see that "15%" evaluates to the numeric value 15 and "$25" evaluates to the numeric value zero, which explains why the result of the statement $x = 3 + "15%" + "$25" is 18 (i.e., 3 + 15 + 0).
    Depending on who you ask, automatic type conversion is either a great feature or one of the worst pitfalls of the PHP language. On the one hand, when used consciously and properly, it can be very convenient for the developer (e.g., I don’t need to write any code to convert “15” to 15 before using it in an arithmetic operation). On the other hand, it can easily lead to headfakes and hard-to-track-down bugs when it is employed inadvertently, since no error message or warning will be generated.
    Q: Explain the significance of using the static keyword when invoking a method or property, including how it differs from the self keyword? When would you use it and why? Provide an example.
    As of PHP 5.3.0, PHP implements a feature called late static bindings. “Late binding” comes from the fact that static:: will not be resolved using the class where the method is defined but will rather be determined using runtime information and scope. (Incidentally, the term “static” is a bit of a misnomer in that this is not limited to being used with static methods.)
    Consider the following example:

    class Dog {
        static $whoami = 'dog';
        static $sound = 'bark';
        function makeSounds() {
            echo self::makeSound() . ', ';
            echo static::makeSound() . PHP_EOL;
        }
        function makeSound() {
            echo static::$whoami . ' ' . static::$sound;
        }
    }
    Dog::makeSounds();
    

    Unsurprisingly, this will output “dog bark, dog bark”.
    But now let’s extend this example to include the following:

    class Puppy extends Dog {
        static $whoami = 'puppy';
        static $sound = 'woof';
        function makeSound(){
            echo static::$whoami . ' whimper';
        }
    }
    Puppy::makeSounds();
    

    You may be surprised to learn that this will output “puppy woof, puppy whimper”. To understand why, let’s revisit the makeSounds() method in the Dog class.
    The makeSounds() method in the Dog class first invokes self::makeSound(). self:: instructs PHP to always use the scope of the same class (in this case, the Dog class). Therefore, calling self::makeSound() from within Dog’s makeSounds() method will always invoke Dog’s version of makeSound(). This is true even when we call Puppy::makeSounds() since Puppy has no makeSounds() method of its own and instead relies on Dog’s version. This is why the call from Puppy::makeSounds() to self::makeSound() outputs “puppy woof”.
    Next, the makeSounds() method in the Dog class invokes static::makeSound(). static:: behaves differently from self::. static:: instructs PHP to use the version in the scope of the class that invoked the method at runtime (in this case, the Puppy class). Hence, when the call to static::makeSound() is made, it invokes Puppy’s version of that method. This is why the call from Puppy::makeSounds() to static::makeSound() outputs “puppy whimper”.

    PHP Under-the-Hood

    Understanding how PHP works “under the hood” is one of the primary defining characteristics of a PHP expert. Such a candidate will understand not only how to do something, but the various options available, and the performance and functional ramifications of each.
    Q: How does PHP build an array internally?
    Central to much of PHP development is the array. These are good for most uses where an iterable data structure is needed. Internally in PHP, arrays are stored, like many other data structures, as hash tables. PHP is written in C where there is no such thing as an associative array: arrays in C can only have integer indices. Therefore, a hash function is used to translate PHP array indices (both integer and string) into appropriate numeric indices and the array values are stored at that location or bucket in the hash table.
    The process of finding bucket entries based on a hash of the array keys is of O(1) complexity (using Big O notation). This because no iteration over the hash is needed, since the hash function produces the exact location in the table. (Note that this changes slightly if there is more than one element in the bucket.)
    PHP automatically increases the size of an array “on demand”. Specifically, when an element is added to an array, if addition of the element would cause the array to exceed its currently allocated size, PHP responds by doubling the memory allocation. The corresponding hash table needs to be completely rehashed as a result.
    Let’s consider what that means for just a second: Adding values to an array can in some cases be as complex as iterating over that entire new array, and in that same situation you have doubled the memory footprint of that structure. Given this, where datasets begin to get large and memory is an issue, it may be wise to consider an alternative to an array, where loading the data for processing happens on a more as needed basis.
    Q: What is the difference between the ArrayAccess and ArrayObject?
    ArrayAccess is simply an interface definition that requires any class that implements it to define the following methods: offsetGet, offsetSet, offsetExists, and offsetUnset.
    ArrayObject, on the other hand, is an instantiable class that implements the ArrayAccess interface. A nice usage convenience of an ArrayObject is that its elements can either be accessed the same as a standard array (i.e., via the familiar [] notation; e.g., $dogs['sound']) or via the offsetGet(propertyName) method (e.g., $dogs->offsetGet('sound')).
    Q: What is a generator? When might you use it instead of an iterator or a plain array. What do yield and send do?
    A generator looks much like any other function in PHP and shares some similarities with closures. When called for the first time in an iterable context (e.g., a foreach statement), the generator returns an object that is an instance of the Generator class, which in turn implements the Iterator interface. The values for iteration are generated in real-time eliminating the need to load an entire data set into memory before hand. That means that the result can be iterated over in much the same way that an array can, but with some important differences; namely they:

    • Can only be used in a forward run, meaning that one can’t iterate backwards over the values or start at the beginning. Calling the rewind() method on the generator will throw an exception.
    • Are slower than processing a pre-populated array (the generator is doing extra processing to produce the value).
    • Are extremely memory efficient.

    One of the chief differences between a generator function and other PHP functions or closures is that they don’t make use of return to provide their results. Instead, yield is used to pass values out of the generator (e.g., yield $dog;). In fact, specifying a value on a return statement in a generator will produce a parser error, but an empty return statement will simply stop the generator altogether.
    yield pauses execution and returns the current value to the scope of the structure that is using the generator. That structure has the opportunity to send information back to the generator at that same point in its execution via the send method (e.g., $generator->send(-1);).
    With that basic explanation, let’s take a look at a simple example of a generator’s use.
    First, let’s define our generator:

    function dog_generator() {
        foreach (range(0, 2) as $value) {
            # some fake data source
            $dog = DogHelper::getDogFromDataSource($value);
            # catch input from send or use $dog
            $input = (yield $dog);
            if ($input == -1) {
                return; // stop the generator
            }
        }
    }
    

    Note that, in the above example, we are assigning the result of the yield method call to a variable and must therefore wrap the yield in parentheses in order for it to be syntactically valid.
    And now here’s an example of how we would use the above generator:

    # Get an instance of the generator and assign it to a variable
    $generator = dog_generator();
    foreach ($generator as $dog) { # $dog is a result of 'yield'
        echo $dog . PHP_EOL;
        // we wanted to find the terrier
        if ($dog == 'Terrier') {
            # send an input into the generator via 'yield'
            $generator->send(-1);
            echo 'We found the Terrier, stop the show.';
        }
    }
    

    When we run the above code our example stops when it finds “Terrier”. For example:

    Dalmatian
    Terrier
    We found the Terrier, stop the show.
    

    The key benefits of a generator are ease of implementation, increased readability of code, and overall improved performance and memory usage.
    So generally speaking, it’s best to use a generator where there is no need to rewind or iterate back over the values again in another part of the program. On the other hand, if memory is not a concern, then a simple array of the values is much faster.

    The Big Picture

    Q: List some of the major differences between (or sequential additions and improvements to) PHP 5.3, PHP 5.4 and PHP 5.5.
    PHP 5.3 was released back in June 2009 but is still in wide circulation. Key new features in this release included: closures, lambda style functions, namespacing, and late static binding.
    PHP 5.4 was released in March 2012, introducing Traits, as well as the ability to declare an array with a shortened [] syntax (e.g., $array = ['shih tzu', 'rottweiler']). In addition, register_globals was removed in this version.
    PHP 5.5 was released in June 2013 and is the current release. This version adds support for generators (and their related yield and send keywords), as well as adding finally to the try/catch exception handling syntax. APC Cache is gone in favor of OpCache (based on the Zend Optimizer). PHP 5.5 also takes the array literal even further and supports syntax such as ['shih tzu', 'rottweiler'][1] (which returns “rottweiler”) as well as the handy notation of strings interpreted as arrays (e.g., '6, 5, 4'[0], which returns “6”).

    Wrap-up

    Finding PHP developers can be relatively easy, but finding stellar PHP developers is a formidable challenge. The questions presented in this guide can serve as useful tools in your overall recruiting toolbox to better identify those who have mastered the language. Finding such candidates is well worth the effort, as they will undoubtedly have a significant positive impact on your team’s productivity and results.

  • Grape Gem Tutorial: How To Build A REST-Like API In Ruby

    As Ruby On Rails developers, we often need to extend our applications with API endpoints to support JavaScript-heavy Rich Internet clients or native iPhone and Android apps. There are also some cases where the application’s sole purpose is to serve the iPhone/Android apps via a JSON API.
    In this tutorial, I demonstrate how to use Grape – a REST-like API micro-framework for Ruby – to build backend support in Rails for a JSON API. Grape is designed to run as a mountable rack engine tocomplement our web applications, without interfering with them.

    Use Case

    The use case we will focus on for this tutorial is an application capable of capturing and reviewing pair programming sessions. The application itself will be written for iOS in ObjectiveC and will need to communicate with a backend service for storing and retrieving the data. Our focus in this tutorial is on creation of a robust and secure backend service that supports a JSON API.
    The API will support methods for:

    • Logging in to the system
    • Querying pair programming session reviews

    NOTE: In addition to providing the ability to query pair programming session reviews, the real API would also need to provide a facility for submitting pair programming reviews for inclusion in the database. Since supporting that via the API is beyond the scope of this tutorial, we will simply assume that the database has been populated with a sample set of pair programming reviews.
    Key technical requirements include:

    • Every API call must return valid JSON
    • Every failed API call must be recorded with adequate context and information to subsequently be reproducible, and debugged if necessary

    Also, since our application will need to serve external clients, we will need to concern ourselves with security. Toward that end:

    • Each request should be restricted to a small subset of developers we track
    • All requests (other than login/signup) need to be authenticated

    Test Driven Development And RSpec

    We will use Test Driven Development (TDD) as our software development approach to help ensure the deterministic behavior of our API.
    For testing purposes we will use RSpec, a well known testing framework in the RubyOnRails community. I will therefore refer in this article to “specs” rather than “tests”.
    A comprehensive testing methodology consists of both “positive” and “negative” tests. Negative specs will specify, for example, how the API endpoint behaves if some parameters are missing or incorrect. Positive specs cover cases where the API is invoked correctly.

    Getting Started

    Let’s put down the foundation for our backend API. First, we need to create a new rails application:

    rails new toptal_grape_blog
    

    Next, we’ll install RSpec by adding rspec-rails into our gemfile:

    group :development, :test do
      gem 'rspec-rails', '~> 3.2'
    end
    

    Then from our command line we need to run:

    rails generate rspec:install
    

    We can also leverage some existing open source software for our testing framework. Specifically:

    Step 1: Add these into our gemfile:

    ...
    gem 'devise'
    ...
    group :development, :test do
    ...
      gem 'factory_girl_rails', '~> 4.5'
    ...
    end
    

    Step 2: Generate a user model, initialize the devise gem, and add it to the user model (this enables the user class to be used for authentication).

    rails g model user
    rails generate devise:install
    rails generate devise user
    

    Step 3: Include the factory_girl syntax method in our rails_helper.rb file in order to use the abbreviated version of user creation in our specs:

    RSpec.configure do |config|
      config.include FactoryGirl::Syntax::Methods
    

    Step 4: Add the grape gem to our DSL and install it:

    gem 'grape'
    bundle
    

    User Login Use Case And Spec

    Our backend will need to support a basic login capability. Let’s create the skeleton for our login_spec, assuming that a valid login request consists of a registered email address and password pair:

    require 'rails_helper'
    describe '/api/login' do
      context 'negative tests' do
        context 'missing params' do
          context 'password' do
          end
          context 'email' do
          end
        end
        context 'invalid params' do
          context 'incorrect password' do
          end
          context 'with a non-existent login' do
          end
        end
      end
      context 'positive tests' do
        context 'valid params' do
        end
      end
    end
    

    If either of the parameters is missing, the client should receive an HTTP return status code of 400 (i.e., Bad Request), along with an error message of ‘email is missing’ or ’password is missing’.
    For our test, we will create a valid user and set the user’s email and password as original parameters for this test suite. Then we will customize this parameter hash for every specific spec by either omitting the password/email or overriding it.
    Let’s create the user and the parameter hash at the beginning of the spec. We will put this code after the describe block:

    describe '/api/login' do
      let(:email) { user.email }
      let(:password) { user.password }
      let!(:user) { create :user }
      let(:original_params) { { email: email, password: password } }
      let(:params) { original_params }
      ...
    

    We can then extend our ‘missing params’/’password’ context as follows:

    let(:params) { original_params.except(:password) }
    it_behaves_like '400'
    it_behaves_like 'json result'
    it_behaves_like 'contains error msg', 'password is missing'
    

    But instead of repeating the expectations across the ‘email’ and ‘password’ contexts, we can use the same shared examples as expectations. For this, we need to uncomment this line in our rails_helper.rb file:

    Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
    

    We then need to add the 3 RSpec shared examples into spec/support/shared.rb:

    RSpec.shared_examples 'json result' do
      specify 'returns JSON' do
        api_call params
        expect { JSON.parse(response.body) }.not_to raise_error
      end
    end
    RSpec.shared_examples '400' do
      specify 'returns 400' do
        api_call params
        expect(response.status).to eq(400)
      end
    end
    RSpec.shared_examples 'contains error msg' do |msg|
      specify "error msg is #{msg}" do
        api_call params
        json = JSON.parse(response.body)
        expect(json['error_msg']).to eq(msg)
      end
    end
    

    These shared examples are calling the api_call method which enables us to define the API endpoint only once in our spec (in keeping with the DRY principle). We define this method as follows:

    describe '/api/login' do
    ...
      def api_call *params
        post "/api/login", *params
      end
    ...
    

    We will also need to customize the factory for our user:

    FactoryGirl.define do
      factory :user do
        password "Passw0rd"
        password_confirmation { |u| u.password }
        sequence(:email) { |n| "test#{n}@example.com" }
      end
    end
    

    And finally, before running our specs we need to run our migrations:

    rake db:migrate
    

    Bear in mind, though, that the specs will still fail at this point, since we haven’t yet implemented our API endpoint. That’s next.

    Implementing The Login API Endpoint

    For starters, we’ll write an empty skeleton for our login API (app/api/login.rb):

    class Login < Grape::API
      format :json
      desc 'End-points for the Login'
      namespace :login do
        desc 'Login via email and password'
        params do
          requires :email, type: String, desc: 'email'
          requires :password, type: String, desc: 'password'
        end
        post do
        end
      end
    end
    

    Next, we’ll write an aggregator class which aggregates the API endpoints (app/api/api.rb):

    class API < Grape::API
      prefix 'api'
      mount Login
    end
    

    OK, now we can mount our API in the routes:

    Rails.application.routes.draw do
    ...
      mount API => '/'
    ...
    end
    

    Now let’s add the code to check for the missing parameters. We can add that code to api.rb by rescuing from Grape::Exceptions::ValidationErrors.

    rescue_from Grape::Exceptions::ValidationErrors do |e|
      rack_response({
        status: e.status,
        error_msg: e.message,
      }.to_json, 400)
    end
    

    For the invalid password, we will check if the http response code is 401 which means unauthorized access. Let’s add this to the ‘incorrect password’ context:

    let(:params) { original_params.merge(password: 'invalid') }
    it_behaves_like '401'
    it_behaves_like 'json result'
    it_behaves_like 'contains error msg', 'Bad Authentication Parameters'
    

    The same logic is then added to the ‘with a non-existent login’ context as well.
    We then implement the logic which handles the invalid authentication attempts into our login.rb as follows:

    post do
      user = User.find_by_email params[:email]
      if user.present? && user.valid_password?(params[:password])
      else
        error_msg = 'Bad Authentication Parameters'
        error!({ 'error_msg' => error_msg }, 401)
      end
    end
    

    At this point all of the negative specs for the login api will behave properly, but we still need to support the positive specs for our login api. Our positive spec will expect the endpoint to return an HTTP response code of 200 (i.e., success) with valid JSON and a valid token:

    it_behaves_like '200'
    it_behaves_like 'json result'
    specify 'returns the token as part of the response' do
      api_call params
      expect(JSON.parse(response.body)['token']).to be_present
    end
    

    Let’s also add the expectation for the response code 200 to spec/support/shared.rb:

    RSpec.shared_examples '200' do
      specify 'returns 200' do
        api_call params
        expect(response.status).to eq(200)
      end
    end
    

    In case of successful login we are going to return the first valid authentication_token together with the user’s email in this format:

    {‘email’:<the_email_of_the_user>, ‘token’:<the users first valid token>}
    

    If there is no such token yet then we will create one for the current user:

    ...
    if user.present? && user.valid_password?(params[:password])
      token = user.authentication_tokens.valid.first || AuthenticationToken.generate(user)
      status 200
    else
    ...
    

    In order for this to work, we will need an AuthenticationToken class which belongs to the user. We will generate this model, then run the corresponding migration:

    rails g model authentication_token token user:references expires_at:datetime
    rake db:migrate
    

    We also need to add the corresponding association to our user model:

    class User < ActiveRecord::Base
      has_many :authentication_tokens
    end
    

    Then we will add the valid scope to the AuthenticationToken class:

    class AuthenticationToken < ActiveRecord::Base
      belongs_to :user
      validates :token, presence: true
      scope :valid,  -> { where{ (expires_at == nil) | (expires_at > Time.zone.now) } }
    end
    

    Note that we used Ruby syntax in the where statement. This is enabled by our use of the squeel gem which enables support for Ruby syntax in activerecord queries.
    For a validated user, we are going to create an entity that we’ll refer to as the “user with token entity”, leveraging the features of the grape-entity gem.
    Let’s write the spec for our entity and put it in the user_with_token_entity_spec.rb file:

    require 'rails_helper'
    describe Entities::UserWithTokenEntity do
      describe 'fields' do
        subject(:subject) { Entities::UserWithTokenEntity }
        specify { expect(subject).to represent(:email)}
        let!(:token) { create :authentication_token }
        specify 'presents the first available token' do
          json = Entities::UserWithTokenEntity.new(token.user).as_json
          expect(json[:token]).to be_present
        end
      end
    end
    

    Next let’s add the entities to user_entity.rb:

    module Entities
      class UserEntity < Grape::Entity
        expose :email
      end
    end
    

    And finally, add another class to user_with_token_entity.rb:

    module Entities
      class UserWithTokenEntity < UserEntity
        expose :token do |user, options|
          user.authentication_tokens.valid.first.token
        end
      end
    end
    

    Since we don’t want tokens to remain valid indefinitely, we have them expire after one day:

    FactoryGirl.define do
      factory :authentication_token do
        token "MyString"
        expires_at 1.day.from_now
        user
      end
    end
    

    With this all done, we can now return the expected JSON format with our newly written UserWithTokenEntity:

    ...
    user = User.find_by_email params[:email]
    if user.present? && user.valid_password?(params[:password])
      token = user.authentication_tokens.valid.first || AuthenticationToken.generate(user)
      status 200
      present token.user, with: Entities::UserWithTokenEntity
    else
    ...
    

    Cool. Now all of our specs are passing and the functional requirements of the basic login api endpoint are supported.

    Pair Programming Session Review API Endpoint: Getting Started

    Our backend will need to allow authorized developers who have logged in to query pair programming session reviews.
    Our new API endpoint will be mounted to /api/pair_programming_session and will return the reviews belonging to a project. Let’s begin by writing a basic skeleton for this spec:

    require 'rails_helper'
    describe '/api' do
      describe '/pair_programming_session' do
        def api_call *params
          get '/api/pair_programming_sessions', *params
        end
        context 'invalid params' do
        end
        context 'valid params' do
        end
      end
    end
    

    We will write a corresponding empty API endpoint (app/api/pair_programming_sessions.rb) as well:

    class PairProgrammingSessions < Grape::API
      format :json
      desc 'End-points for the PairProgrammingSessions'
      namespace :pair_programming_sessions do
        desc 'Retrieve the pairprogramming sessions'
        params do
          requires :token, type: String, desc: 'email'
        end
        get do
        end
      end
    end
    

    Then let’s mount our new api (app/api/api.rb):

    ...
      mount Login
      mount PairProgrammingSessions
    end
    

    Let’s expand the spec, and the API endpoint, against the requirements one by one.

    Pair Programming Session Review API Endpoint: Validation

    One of our most important non-functional security requirements was to restrict API access to a small subset of developers we track, so let’s specify that:

    ...
    def api_call *params
      get '/api/pair_programming_sessions', *params
    end
    let(:token) { create :authentication_token }
    let(:original_params) { { token: token.token} }
    let(:params) { original_params }
    it_behaves_like 'restricted for developers'
    context 'invalid params' do
    ...
    

    Then we will create a shared_example in our shared.rb to confirm that the request is coming from one of our registered developers:

    RSpec.shared_examples 'restricted for developers' do
      context 'without developer key' do
        specify 'should be an unauthorized call' do
          api_call params
          expect(response.status).to eq(401)
        end
        specify 'error code is 1001' do
          api_call params
          json = JSON.parse(response.body)
          expect(json['error_code']).to eq(ErrorCodes::DEVELOPER_KEY_MISSING)
        end
      end
    end
    

    We will also need to create an ErrorCodes class (in app/models/error_codes.rb):

    module ErrorCodes
      DEVELOPER_KEY_MISSING = 1001
    end
    

    Since we expect our API to expand in the future, we are going to implement an authorization_helper which can be reused across all API endpoints in the application to restrict access to registered developers only:

    class PairProgrammingSessions < Grape::API
      helpers ApiHelpers::AuthenticationHelper
      before { restrict_access_to_developers }
    

    We are going to define the method restrict_access_to_developers in the ApiHelpers::AuthenticationHerlpermodule (app/api/api_helpers/authentication_helper.rb). This method will simply check if the key Authorization under the headers contains a valid ApiKey. (Every developer wanting access to the API will require a valid ApiKey. This could either be provided by a system administrator or via some automated registration process, but that mechanism is beyond the scope of this article.)

    module ApiHelpers
      module AuthenticationHelper
        def restrict_access_to_developers
          header_token = headers['Authorization']
          key = ApiKey.where{ token == my{ header_token } }
          Rails.logger.info "API call: #{headers}tWith params: #{params.inspect}" if ENV['DEBUG']
          if key.blank?
            error_code = ErrorCodes::DEVELOPER_KEY_MISSING
            error_msg = 'please aquire a developer key'
            error!({ :error_msg => error_msg, :error_code => error_code }, 401)
            # LogAudit.new({env:env}).execute
          end
        end
      end
    end
    

    We then need to generate the ApiKey model and run the migrations: rails g model api_key token rake db:migrate
    With this done, in our spec/api/pair_programming_spec.rb we can check if the user is authenticated:

    ...
    it_behaves_like 'restricted for developers'
    it_behaves_like 'unauthenticated'
    ...
    

    Let’s also define an unauthenticated shared example which can be reused across all specs (spec/support/shared.rb):

    RSpec.shared_examples 'unauthenticated' do
      context 'unauthenticated' do
        specify 'returns 401 without token' do
          api_call params.except(:token), developer_header
          expect(response.status).to eq(401)
        end
        specify 'returns JSON' do
          api_call params.except(:token), developer_header
          json = JSON.parse(response.body)
        end
      end
    end
    

    This shared example needs the token in the developer header so let’s add that to our spec (spec/api/pair_programming_spec.rb):

    ...
    describe '/api' do
      let(:api_key) { create :api_key }
      let(:developer_header) { {'Authorization' => api_key.token} }
    ...
    

    Now, in our app/api/pair_programming_session.rb, let’s attempt to authenticate the user:

    ...
    class PairProgrammingSessions < Grape::API
      helpers ApiHelpers::AuthenticationHelper
      before { restrict_access_to_developers }
      before { authenticate! }
    ...
    

    Let’s implement the authenticate! method in the AuthenticationHelper (app/api/api_helpers/authentication_helper.rb):

    ...
    module ApiHelpers
      module AuthenticationHelper
        TOKEN_PARAM_NAME = :token
        def token_value_from_request(token_param = TOKEN_PARAM_NAME)
          params[token_param]
        end
        def current_user
          token = AuthenticationToken.find_by_token(token_value_from_request)
          return nil unless token.present?
          @current_user ||= token.user
        end
        def signed_in?
          !!current_user
        end
        def authenticate!
          unless signed_in?
            AuditLog.create data: 'unauthenticated user access'
            error!({ :error_msg => "authentication_error", :error_code => ErrorCodes::BAD_AUTHENTICATION_PARAMS }, 401)
          end
        end
    ...
    

    (Note that we need to add the error code BAD_AUTHENTICATION_PARAMS to our ErrorCodes class.)
    Next, let’s spec what happens if the developer calls the API with an invalid token. In that case the return code will be 401 signaling an ‘unauthorized access’. The result should be JSON and an auditable should be created. So we add this to spec/api/pair_programming_spec.rb:

    ...
    context 'invalid params' do
      context 'incorrect token' do
        let(:params) { original_params.merge(token: 'invalid') }
        it_behaves_like '401'
        it_behaves_like 'json result'
        it_behaves_like 'auditable created'
        it_behaves_like 'contains error msg', 'authentication_error'
        it_behaves_like 'contains error code', ErrorCodes::BAD_AUTHENTICATION_PARAMS
      end
    end
    ...
    

    We will add the “auditable created”, “contains error code”, and “contains error msg” shared examples to spec/support/shared.rb:

    ...
    RSpec.shared_examples 'contains error code' do |code|
      specify "error code is #{code}" do
        api_call params, developer_header
        json = JSON.parse(response.body)
        expect(json['error_code']).to eq(code)
      end
    end
    RSpec.shared_examples 'contains error msg' do |msg|
      specify "error msg is #{msg}" do
        api_call params, developer_header
        json = JSON.parse(response.body)
        expect(json['error_msg']).to eq(msg)
      end
    end
    RSpec.shared_examples 'auditable created' do
      specify 'creates an api call audit' do
        expect do
          api_call params, developer_header
        end.to change{ AuditLog.count }.by(1)
      end
    end
    ...
    

    We also need to create an audit_log model:

    rails g model audit_log backtrace data user:references
    rake db:migrate
    

    Pair Programming Session Review API Endpoint: Returning Results

    For an authenticated and authorized user, a call to this API endpoint should return a set of pair programming session reviews grouped by project. Let’s modify our spec/api/pair_programming_spec.rb accordingly:

    ...
    context 'valid params' do
    it_behaves_like '200'
    it_behaves_like 'json result'
    end
    ...
    

    This specifies that a request submitted with valid api_key and valid parameters returns an HTTP code of 200 (i.e., success) and that the result is returned in the form of valid JSON.
    We are going to query and then return in JSON format those pair programming sessions where any of the participant is the current user (app/api/pair_programming_sessions.rb):

    ...
    get do
    sessions = PairProgrammingSession.where{(host_user == my{current_user}) | (visitor_user == my{current_user})}
    sessions = sessions.includes(:project, :host_user, :visitor_user, reviews: [:code_samples, :user] )
    present sessions, with: Entities::PairProgrammingSessionsEntity
    end
    ...
    

    The pair programming sessions are modeled as follows in the database:

    • 1-to-many relationship between projects and pair programming sessions
    • 1-to-many relationship between pair programming sessions and reviews
    • 1-to-many relationship between reviews and code samples

    Let’s generate the models accordingly and then run the migrations:

    rails g model project name
    rails g model pair_programming_session project:references host_user:references visitor_user:references
    rails g model review pair_programming_session:references user:references comment
    rails g model code_sample review:references code:text
    rake db:migrate
    

    Then we need to modify our PairProgrammingSession and Review classes to contain the has_manyassociations:

    class Review < ActiveRecord::Base
      belongs_to :pair_programming_session
      belongs_to :user
      has_many :code_samples
    end
    class PairProgrammingSession < ActiveRecord::Base
      belongs_to :project
      belongs_to :host_user, class_name: :User
      belongs_to :visitor_user, class_name: 'User'
      has_many :reviews
    end
    

    NOTE: In normal circumstances, I would generate these classes by writing specs for them first ,but since that is beyond the scope of this article, I will skip that step.
    Now we need to write those classes which are going to transform our models to their JSON representations (referred to as grape-entities in grape terminology). For simplicity, we will use 1-to-1 mapping between the models and grape-entities.
    We begin by exposing the code field from the CodeSampleEntity (in api/entities/code_sample_entity.rb):

    module Entities
      class CodeSampleEntity < Grape::Entity
        expose :code
      end
    end
    

    Then we expose the user and associated code_samples by reusing the already defined UserEntity and the CodeSampleEntity:

    module Entities
      class ReviewEntity < Grape::Entity
        expose :user, using: UserEntity
        expose :code_samples, using: CodeSampleEntity
      end
    end
    

    We also expose the name field from the ProjectEntity:

    module Entities
      class ProjectEntity < Grape::Entity
        expose :name
      end
    end
    

    Finally, we assemble the entity into a new PairProgrammingSessionsEntity where we expose the project, the host_user, the visitor_user and the reviews:

    module Entities
      class PairProgrammingSessionsEntity < Grape::Entity
        expose :project, using: ProjectEntity
        expose :host_user, using: UserEntity
        expose :visitor_user, using: UserEntity
        expose :reviews, using: ReviewEntity
      end
    end
    

    And with that, our API is fully implemented!

    Generating Test Data

    For testing purposes, we’ll create some sample data in db/seeds.rb. This file should contain all the record creation needed to seed the database with its default values. The data can then be loaded with rake db:seed(or created with the db when db:setup is invoked). Here’s an example of what this could include:

    user_1 = User.create email: '[email protected]', password: 'password', password_confirmation: 'password'
    user_2 = User.create email: '[email protected]', password: 'password', password_confirmation: 'password'
    user_3 = User.create email: '[email protected]', password: 'password', password_confirmation: 'password'
    ApiKey.create token: '12345654321'
    project_1 = Project.create name: 'Time Sheets'
    project_2 = Project.create name: 'Toptal Blog'
    project_3 = Project.create name: 'Hobby Project'
    session_1 = PairProgrammingSession.create project: project_1, host_user: user_1, visitor_user: user_2
    session_2 = PairProgrammingSession.create project: project_2, host_user: user_1, visitor_user: user_3
    session_3 = PairProgrammingSession.create project: project_3, host_user: user_2, visitor_user: user_3
    review_1 = session_1.reviews.create user: user_1, comment: 'Please DRY a bit your code'
    review_2 = session_1.reviews.create user: user_1, comment: 'Please DRY a bit your specs'
    review_3 = session_2.reviews.create user: user_1, comment: 'Please DRY your view templates'
    review_4 = session_2.reviews.create user: user_1, comment: 'Please clean your N+1 queries'
    review_1.code_samples.create code: 'Lorem Ipsum'
    review_1.code_samples.create code: 'Do not abuse the single responsibility principle'
    review_2.code_samples.create code: 'Use some shared examples'
    review_2.code_samples.create code: 'Use at the beginning of specs'
    

    Now our application is ready for use and we can launch our rails server.

    Testing the API

    We will use Swagger to do some manual browser-based testing of our API. A few setup steps are required for us to be able to make use of Swagger though.
    First, we need to add a couple of gems to our gemfile:

    ...
    gem 'grape-swagger'
    gem 'grape-swagger-ui'
    ...
    

    We then run bundle to install these gems.
    We also need to add these to assets to our assets pipeline (in config/initializers/assets.rb):

    Rails.application.config.assets.precompile += %w( swagger_ui.js )
    Rails.application.config.assets.precompile += %w( swagger_ui.css )
    

    Finally, in app/api/api.rb we need to mount the swagger generator:

    ...
      add_swagger_documentation
    end
    ...
    

    Now we can take advantage of Swagger’s nice UI to explore our API by simply going to https://localhost:3000/api/swagger.
    Swagger presents our API endpoints in a nicely explorable way. If we click on an endpoint, Swagger lists its operations. If we click on an operation, Swagger shows its required and optional parameters and their data types.
    One remaining detail though before we proceed: Since we restricted use of the API developers with a valid api_key, we won’t be able to access the API endpoint directly from the browser because the server will require a valid api_key in the HTTP header. We can accomplish this for testing purposes in Google Chrome by making use of the Modify Headers for Google Chrome plugin. This plugin will enable us to edit the HTTP header and add in a valid api_key (we’ll use the dummy api_key of 12345654321 that we included in our database seed file).
    OK, now we’re ready to test!
    In order to call the pair_programming_sessions API endpoint, we first need to log in. We’ll just use of the email and password combinations from our database seed file and submit it via Swagger to the login API endpoint, as shown below.

    As you can see above, the token belonging to that user is returned, indicating that the login API is working as functioning properly as intended. We can now use that token to successfully perform the GET /api/pair_programming_sessions.json operation.

    As shown, the result is returned as a properly-formatted hierarchical JSON object. Notice that the JSON structure reflects two nested 1-to-many associations, since the project has multiple reviews, and a review has multiple code samples. If we wouldn’t return the structure in this way, then the caller of our API would need to separately request the reviews for each project which would require submitting N queries to our API endpoint. With this structure, we therefore solve the N+1 query performance issue.

    Wrap-up

    As shown herein, comprehensive specs for your API help ensure that the implemented API properly and adequately addresses the intended (and unintended!) use cases.
    While the example API presented in this tutorial is fairly basic, the approach and techniques we have demonstrated can serve as the foundation for more sophisticated APIs of arbitrary complexity using the Grapegem. This tutorial has hopefully demonstrated that Grape is a useful and flexible gem that can help facilitate implementation of a JSON API in your Rails applications. Enjoy!

  • Cold Dive into React Native: A Beginner’s Tutorial

    When React Native was announced, the first reactions were overwhelmingly positive. Traditionally, when we think about web technologies in the mobile space, things like Apache Cordova spring to mind which allow us to package web sites or web applications as applications for mobile platforms. In this tutorial, we will take a look at React Native’s architecture, the philosophy behind React Native, and how it differs from other solutions in the same space. By the end of the article, we will have transformed a React “Hello World” application into a React Native one.

    Let us start by saying that React Native is a relatively new technology. It has been officially available since March 2015, been in private beta since the start of the year, and internally used at Facebook for a while before that. The saying “Rome wasn’t built in a day” generally applies to technology as well. Tools like “grunt” and platforms like “node” took years to mature. In the web world things are moving quickly, and with a huge number of frameworks, packages, and tools coming out every day, developers tend to get a little more sceptical and don’t want to jump on every hype bandwagon only to realize that they ended up in a vendor lock-in situation. We will get into what makes React Native special, why it is a technology worth getting into, and cover a few instances where it’s not all unicorns and rainbows.

    Under the Hood

    When talking about web technologies on mobile, available solutions usually fall in one of the following categories.

    Bundling Web Applications in a Mobile Web Browser

    The web application lives in a mobile browser, typically called a WebView. Without any major refactoring, a web site or web application works on the mobile device. We may need to consider mobile browser events such as tapping or listening to device orientation changes and the smaller screen for a complete user experience, but we have a working mobile version with minimal effort. Cordova/PhoneGap is the most popular option in this category. Unfortunately this option has a big downside: in some cases, applications developed using Cordova are significantly slower than native applications, especially for graphical-heavy applications. In other cases, the mobile operating system doesn’t actually provide all the features in the WebView that are available in the mobile browser. The user experience can also differ from native applications, this may happen due to the application or the platform itself. This problem may range from scrollbars not feeling the same to having a noticeable delay when tapping on elements.

    Compiling to Native Technologies

    A completely different solution is to create a native codebase in the end. This happens by transforming the original source code into another programming language. We trade in native performance for an abstraction layer with some uncertainties. In cases of closed-source solutions, we are not even sure what happens under the hood and with what kind of black box we are dealing with. In other cases we are not sure how much the next mobile operating system update will break our code and when fixes or updates will be available. A popular example of this category would be HaXe.

    Using a JavaScript Layer

    Here we use JavaScript engine of the mobile environment and execute our JavaScript there. Native controls are mapped to JavaScript objects and functions, so when we were to call a function called “fancyButtonRightHere()”, a button would appear on the screen. NativeScript or Appcelerator Titanium are well-known examples of this category.

    React Native could be classified as something from the third category. For the iOS version, React Native uses “JavaScriptCore” under the hood which is the default JavaScript engine on iOS. “JavaScriptCore” is also the JavaScript engine in Apple’s Safari browsers. OS X and iOS developers can actually directly interface with it if they want to.

    One big difference is that React Native runs the JavaScript code in a separate thread, so the user interface does not block and animations should be silky and smooth.

    React is the Key Feature

    It is worth noting that React in React Native is not put there by accident. For React Native, we need an understanding of what exactly React offers. The following concepts work the same in both React and React Native, although these code examples are tailored to be run in the browser.

    Single Rendering Entry Point

    When we take a look at a simple React component, the first thing we may notice is that the component has a “render” function. In fact, React throws an error if there is no render function defined inside the component.

    var MyComponent = function() {
      this.render = function() {
        // Render something here
      };
    };
    

    The special thing is that we don’t mess with DOM elements here, but we return a XML-based construct that represents what will be rendered in the DOM. This XML-based construct is called JSX.

    var MyComponent = function() {
      this.render = function() {
        return <div className="my-component">Hello there</div>;
      };
    };
    

    A special JSX transformer takes all of that XML-looking code and converts it into functions. This is what the component after the transformation will look like:

    var MyComponent = function() {
      this.render = function() {
         return React.createElement("div", {
           className: "my-component"
         }, "Hello there");
      };
    };
    

    The biggest advantage is that by taking a quick look at the component, we always know what it’s supposed to do. For example a “<FriendList />” component might render a number of “<Friend />” components. We can’t render our components anywhere else than inside of the “render” function, so there is never the concern that we don’t know where exactly our rendered component came from.

    Unidirectional Data Flow

    To build the content of a component, React provides properties or props for short. Similar to XML attributes, we pass in the props directly to a component and can then use the props inside the constructed component.

    var Hello = function(props) {
      this.render = function() {
        return <div className="my-component">Hello {props.name}</div>;
      };
    };
    var Greeter = function() {
      this.render = function() {
        return <Hello name="there" />
      }
    };
    

    This leads to our components being in a tree-like structure and we are only allowed to pass data when constructing child elements.

    Re-Render on Changes

    In addition to props, components can also have an internal state. The most prominent example of that behavior would be a click counter that updates its value when a button is pressed. The number of clicks itself would be saved in the state.
    Each of the prop and state change triggers a complete re-render of the component.

    Virtual DOM

    Now when everything is re-rendered when the props or state changes, how come React itself is performing that well? The magic ingredient is “Virtual DOM”. Whenever something is needed to be re-rendered, a virtual representation of the updated DOM is generated. The Virtual DOM consists of light representations of elements modeled after the component tree, making the process of generating them much more efficient than generating real DOM elements. Before applying the changes to the real DOM, checks are done to determine where exactly in the component tree the changes happened, a diff is created, and only those specific changes are applied.

    Getting Started with this React Native Tutorial

    There are certain prerequisites that are needed in order to develop for React Native. Since iOS is currently the only supported platform, we need Mac OS X and Xcode, at least version 6.3. io.js – a Node.js compatible platform – is needed. What helps is installing watchman through the brew package manager with brew install watchman. While this is not necessarily needed, it helps when dealing with a lot of files inside our React Native project.

    React Native: The Sanest Mobile Application Development Framework.

    To install React Native, we simply need to install the React Native command-line application with npm install -g react-native-cli. Calling the react-native command then helps us creat a new React Native application. Running react-native init HelloWorld creates a folder called “HelloWorld” in which the boilerplate code can be found.

    Transforming a React Application

    With React being the key feature and the core principles coming from the React library, let’s take a look at what we need to transform a minimal React “Hello World” application into a React Native one.

    We use some ES2015 features in this code example, specifically classes. It is completely feasible to stick with “React.createClass” or use a function form similar to the popular module pattern.

    var React = require('react');
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <div className="box" onClick={this.clickMe.bind(this)}>Hello {this.props.name}. Please click me.</div>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Step 1: Embrace CommonJS Modules

    In the first step we need to change requiring the React module to use “react-native” instead.

    var React = require('react-native');
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <div className="box" onClick={this.clickMe.bind(this)}>Hello {this.props.name}. Please click me.</div>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    What is usually a part of the tooling pipeline when developing a React web application is an integral part of React Native.

    Step 2: There is no DOM

    Not surprisingly, there is no DOM on mobile. Where we previously used “<div />” we need to use “<View />” and where we used “<span />” the component we need here is “<Text />”.

    var React = require('react-native');
    var {View} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View className="box" onClick={this.clickMe.bind(this)}>Hello {this.props.name}. Please click me.</View>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    While it’s quite convenient to put text directly in “<div />” elements, in the native world text can’t be put directly in a “<View />”. For that we need to insert a “<Text />” component.

    var React = require('react-native');
    var {View, Text} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View className="box" onClick={this.clickMe.bind(this)}>
            <Text>Hello {this.props.name}. Please click me.</Text>
          </View>
        );
      }
    }
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Step 3: Inline Styles Are the Way to Go

    React Native allows us to use the Flexbox modeling instead of messing around with “float” and “inline-block” that we are so familiar with in the web world. The interesting thing is that React Native does not use CSS.

    var React = require('react-native');
    var {View, Text, StyleSheet} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View style={styles.box} onClick={this.clickMe.bind(this)}>
            <Text>Hello {this.props.name}. Please click me.</Text>
          </View>
        );
      }
    }
    var styles = StyleSheet.create({
      box: {
        borderColor: 'red',
        backgroundColor: '#fff',
        borderWidth: 1,
        padding: 10,
        width: 100,
        height: 100
      }
    });
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Using inline styles seems bewildering at first. It is similar to the transition React developers had to go through when being confronted with JSX and previously using templating engines like Handlebars or Jade.
    The idea is that we don’t have stylesheets globally in the way we use CSS. We declare the stylesheets directly at component level, and so we have all the information we need to see what our component does, the layout it creates, and the styles it applies.

    var React = require('react-native');
    var {Text} = React;
    var Headline = function(props) {
      this.render = () => <Text style={headlineStyle.text}>{props.caption}</Text>;
    };
    var headlineStyles = StyleSheet.create({
      text: {
        fontSize: 32,
        fontWeight: 'bold'
      }
    });
    module.exports = Headline;
    

    Step 4: Handling Events

    The equivalent to clicking in web pages is tapping an element on the mobile device. Let’s change our code so that the “alert” pops up when we tap the element.

    var React = require('react-native');
    var {View, Text, StyleSheet, TouchableOpacity} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <TouchableOpacity onPress={this.clickMe.bind(this)}>
            <View style={styles.box}>
              <Text>Hello {this.props.name}. Please click me.</Text>
            </View>
          </TouchableOpacity>
        );
      }
    }
    var styles = StyleSheet.create({
      box: {
        borderColor: 'red',
        backgroundColor: '#fff',
        borderWidth: 1,
        padding: 10,
        width: 100,
        height: 100
      }
    });
    React.render(<HelloThere name="Component" />, document.getElementById('content'));
    

    Instead of events being directly available on “<View />” components, we need to explicitly use elements that trigger events, in our case a touch event when pressing the view. There are different types of touchable components available, each of them providing a different visual feedback.

    Step 5: Registering the Application

    When developing with React for the browser, we just need to define a mount point, call “React.render”, and let React do its magic. In React Native, this is a little bit different.

    var React = require('react-native');
    var {View, Text, StyleSheet, TouchableOpacity, AppRegistry} = React;
    class HelloThere extends React.Component {
      clickMe() {
        alert('Hi!');
      }
      render() {
        return (
          <View style={styles.container}>
            <TouchableOpacity onPress={this.clickMe.bind(this)}>
              <View style={styles.box}>
                <Text>Hello {this.props.name}. Please click me.</Text>
              </View>
            </TouchableOpacity>
          </View>
        );
      }
    }
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      },
      box: {
        borderColor: 'red',
        backgroundColor: '#fff',
        borderWidth: 1,
        padding: 10,
        width: 100,
        height: 100
      }
    });
    var MainComponent = function() {
      this.render = function() {
        return <HelloThere name="Component" />;
      }
    };
    AppRegistry.registerComponent('MainComponent', function() {
      return MainComponent;
    });
    

    We have to register the component for the Objective-C side of things which is done using the “AppRegistry” object. The name we give has to match with the name inside the Xcode project.

    Our Hello World React Native application has significantly more lines of code than its web counterpart, but on the other side React Native takes separation of concern a bit further especially because styles are defined with the component.

    As a side note, we shouldn’t rebind the “clickMe” method to the “this” context in the “render” method, especially if our React (Native) application grows to be a bit more complex. It rebinds the method on every render call which can become quite a lot. The alternative is to bind the method inside the constructor.

    Running the Application

    To run the application, we need to replace the contents of the “index.ios.js” file with the piece of code of our transformed application from the last step. Then we just need to open the Xcode project and press the big Run button. First a terminal will open with the React Native server, and then the simulator window will appear. The React Native server creates a bundle, which the native application will then fetch. This allows for a web development-like rapid development cycle, where changes will be reflected almost instantly in the simulator. After the terminal has popped up, our application will then show up in the simulator. Pressing CMD+D will show a development menu.

    Clicking on the box will then show an alert:

    For distribution, having an application that points to a local development server would not be working out for us. For this reason, we can create the bundle for usage when the React Native server isn’t running with the command react-native bundle. In that case we need to update the “didFinishLaunchingWithOptions” method of “AppDelegate” to use the offline bundle.
    This example application is also available on Github.

    Working with React Native

    Another thing worth mentioning is that we not only use React concepts and JavaScript for our mobile applications, but some of workflows web developers are used to are also available with React Native. When coming from web development, we are used to developer tools, inspecting elements, and live reloading.
    The way React Native works is that it puts all of our JavaScript files in a bundle. This bundle is either served from a server or bundled together with the application. The first is incredibly useful for development in the Simulator, as we can enable live reloading. The developer menu React provides is by no means as mighty as the Chrome Developer Tools, but it provides a very web-like developer experience with live reloading and debugging with the Chrome (or Safari) developer tools.

    Web developers are familiar with JSFiddle or JSBin, an online playground for quick web tests. There is a similar environment, RNPlay, which allows us to try out React Native in a web browser and see the result from a simulator streamed in the web browser.

    Can I Use React Native?

    In its current state, a few things are still in fluctuation and not up to the expectation you might have from using other frameworks. These are mainly advanced gesture recognition.

    You might want to refrain from completely rewriting your mobile applications in React Native just yet. In React, one of the big advantages is that React does not impose on what workflow you want to use, as it just represents the view layer. Do you want to define your own Grunt pipeline? Or would you rather use Webpack? And will you use Backbone.js for your model needs? Or do you want go with plain JavaScript objects? Answers to all of these questions are totally up to you, because React does not put any restriction on these choices. One recommendation for React from the official website is: “since React makes no assumptions about the rest of your technology stack, it’s easy to try it out on a small feature in an existing project.”

    To a certain degree, this is true for React Native as well. Mobile developers can integrate React Native as a part of their application, take advantage of the web-inspired development workflow, and choose to integrate the library on a larger scale if needs be.

    React Native is not a cross-platform development framework by any means, the philosophy behind it is “Learn once, write anywhere”. While you might end up sharing some code across platforms, but there will always be code you may need to re-implement depending on the platform you are targeting.

    However, one thing is certain: React Native isn’t going away. Facebook has a massive stake in it having multiple React Native powered applications in app stores. The community around React Native is growing, and with each new release there are more contributors, issues, and pull requests.

  • Concurrency and Fault Tolerance Made Easy: An Akka Tutorial with Examples

    The challenge

    Writing concurrent programs is hard. Having to deal with threads, locks, race conditions, and so on is highly error-prone and can lead to code that is difficult to read, test, and maintain.
    Many therefore prefer to avoid multithreading altogether. Instead, they employ single-threaded processes exclusively, relying on external services (such as databases, queues, etc.) to handle any needed concurrent or asynchronous operations. While this approach is in some cases a legitimate alternative, there are many scenarios in which it is simply not a viable option. Many real-time systems – such as trading or banking applications, or real-time games – don’t have the luxury of waiting for a single-threaded process to complete (they need the answer now!). Other systems are so compute- or resource-intensive that they would take an inordinate amount of time (hours or even days in some cases) to run without introducing parallelization into their code.
    One fairly common single-threaded approach (widely used in the Node.js world, for example) is to use an event-based, non-blocking paradigm. While this does help performance by avoiding context switches, locks, and blocking, it still does not address the issues of using multiple processors concurrently (doing so would require launching, and coordinating between, multiple independent processes).
    So does this mean you have no choice but to journey deep into the bowels of threads, locks, and race conditions in order to build a concurrent application?
    Thanks to the Akka framework, the answer is no. This tutorial introduces Akka examples and explores the ways in which it facilitates and simplifies the implementation of concurrent, distributed applications.

    What is the Akka Framework?

    This post introduces Akka and explores the ways in which it facilitates and simplifies the implementation of concurrent, distributed applications.

    Akka is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant applications on the JVM. Akka is written in Scala, with language bindings provided for both Scala and Java.
    Akka’s approach to handling concurrency is based on the Actor Model. In an actor-based system, everything is an actor, in much the same way that everything is an object in object-oriented design. A key difference, though – particularly relevant to our discussion – is that the Actor Model was specifically designed and architected to serve as a concurrent model whereas the object-oriented model is not. More specifically, in a Scala actor system, actors interact and share information, without any presupposition of sequentiality. The mechanism by which actors share information with one another, and task one another, is message passing.

    All the complexity of creating and scheduling threads, receiving and dispatching messages, and handling race conditions and synchronization, is relegated to the framework to handle transparently.

    Akka creates a layer between the actors and the underlying system such that actors simply need to process messages. All the complexity of creating and scheduling threads, receiving and dispatching messages, and handling race conditions and synchronization, is relegated to the framework to handle transparently.
    Akka strictly adheres to the The Reactive Manifesto. Reactive applications aim at replacing traditional multithreaded applications with an architecture that satisfies one or more of the following requirements:

    • Event-driven. Using Actors, one can write code that handles requests asynchronously and employs non-blocking operations exclusively.
    • Scalable. In Akka, adding nodes without having to modify the code is possible, thanks both to message passing and location transparency.
    • Resilient. Any application will encounter errors and fail at some point in time. Akka provides “supervision” (fault tolerance) strategies to facilitate a self-healing system.
    • Responsive. Many of today’s high performance and rapid response applications need to give quick feedback to the user and therefore need to react to events in an extremely timely manner. Akka’s non-blocking, message-based strategy helps achieve this.

    What is an Actor in Akka?

    An actor is essentially nothing more than an object that receives messages and takes actions to handle them. It is decoupled from the source of the message and its only responsibility is to properly recognize the type of message it has received and take action accordingly.
    Upon receiving a message, an actor may take one or more of the following actions:

    • Execute some operations itself (such as performing calculations, persisting data, calling an external web service, and so on)
    • Forward the message, or a derived message, to another actor
    • Instantiate a new actor and forward the message to it

    Alternatively, the actor may choose to ignore the message entirely (i.e., it may choose inaction) if it deems it appropriate to do so.
    To implement an actor, it is necessary to extend the akka.actor.Actor trait and implement the receive method. An actor’s receive method is invoked (by Akka) when a message is sent to that actor. Its typical implementation consists of pattern matching, as shown in the following Akka example, to identify the message type and react accordingly:

    import akka.actor.Actor
    import akka.actor.Props
    import akka.event.Logging
    class MyActor extends Actor {
      def receive = {
        case value: String => doSomething(value)
        case _ => println("received unknown message")
      }
    }
    

    Pattern matching is a relatively elegant technique for handling messages, which tends to produce “cleaner” and easier-to-navigate code than a comparable implementation based on callbacks. Consider, for example, a simplistic HTTP request/response implementation.
    First, let’s implement this using a callback-based paradigm in JavaScript:

    route(url, function(request){
      var query = buildQuery(request);
      dbCall(query, function(dbResponse){
        var wsRequest = buildWebServiceRequest(dbResponse);
        wsCall(wsRequest, function(wsResponse) {
          sendReply(wsResponse);
        });
      });
    });
    

    Now let’s compare this to a pattern-matching-based implementation:

    msg match {
      case HttpRequest(request) => {
        val query = buildQuery(request)
        dbCall(query)
      }
      case DbResponse(dbResponse) => {
        var wsRequest = buildWebServiceRequest(dbResponse);
        wsCall(dbResponse)
      }
      case WsResponse(wsResponse) => sendReply(wsResponse)
    }
    

    While the callback-based JavaScript code is admittedly compact, it is certainly harder to read and navigate. In comparison, the pattern-matching-based code makes it more immediately apparent what cases are being considered and how each is being handled.

    The Actor System

    Taking a complex problem and recursively splitting it into smaller sub-problems is a sound problem solving technique in general. This approach can be particularly beneficial in computer science (consistent with theSingle Responsibility Principle), as it tends to yield clean, modularized code, with little or no redundancy, that is relatively easy to maintain.
    In an actor-based design, use of this technique facilitates the logical organization of actors into a hierarchical structure known as an Actor System. The actor system provides the infrastructure through which actors interact with one another.
    An example of the way the actor system works in the Akka framework.
    In Akka, the only way to communicate with an actor is through an ActorRef. An ActorRef represents a reference to an actor that precludes other objects from directly accessing or manipulating that actor’s internals and state. Messages may be sent to an actor via an ActorRef using one of the following syntax protocols:

    • ! (“tell”) – sends the message and returns immediately
    • ? (“ask”) – sends the message and returns a Future representing a possible reply

    Each actor has a mailbox to which its incoming messages are delivered. There are multiple mailbox implementations from which to choose, with the default implementation being FIFO.
    An actor contains many instance variables to maintain state while processing multiple messages. Akka ensures that each instance of an actor runs in its own lightweight thread and that messages are processed one at a time. In this way, each actor’s state can be reliably maintained without the developer needing to explicitly worry about synchronization or race conditions.
    Each actor is provided with the following useful information for performing its tasks via the Akka Actor API:

    • sender: an ActorRef to the sender of the message currently being processed
    • context: information and methods relating to the context within which the actor is running (includes, for example, an actorOf method for instantiating a new actor)
    • supervisionStrategy: defines the strategy to be used for recovering from errors
    • self: the ActorRef for the actor itself
    Akka ensures that each instance of an actor runs in its own lightweight thread and that messages are processed one at a time. In this way, each actor’s state can be reliably maintained without the developer needing to explicitly worry about synchronization or race conditions.

    To help tie these tutorials together, let’s consider a simple example of counting the number of words in a text file.
    For purposes of our Akka example, we’ll decompose the problem into two subtasks; namely, (1) a “child” task of counting the number of words on a single line and (2) a “parent” task of summing those per-line word counts to get the total number of words in the file.
    The parent actor will load each line from the file and then delegate to a child actor the task of counting the words in that line. When the child is done, it will send a message back to the parent with the result. The parent will receive the messages with the word counts (for each line) and keep a counter for the total number of words in the entire file, which it will then return to its invoker upon completion.
    (Note that the Akka tutorial code samples provided below are intended to be didactic only and therefore do not necessarily concern themselves with all edge conditions, performance optimizations, and so on. Also, a complete compilable version of the code samples shown below is available in this gist.)
    Let’s first look at a sample implementation of the child StringCounterActor class:

    case class ProcessStringMsg(string: String)
    case class StringProcessedMsg(words: Integer)
    class StringCounterActor extends Actor {
      def receive = {
        case ProcessStringMsg(string) => {
          val wordsInLine = string.split(" ").length
          sender ! StringProcessedMsg(wordsInLine)
        }
        case _ => println("Error: message not recognized")
      }
    }
    

    This actor has a very simple task: consume ProcessStringMsg messages (containing a line of text), count the number of words on the specified line, and return the result to the sender via a StringProcessedMsg message. Note that we have implemented our class to use the ! (“tell”) method to send the StringProcessedMsgmessage (i.e., to send the message and return immediately).
    OK, now let’s turn our attention to the parent WordCounterActor class:

    1.  case class StartProcessFileMsg()
    2.
    3.  class WordCounterActor(filename: String) extends Actor {
    4.
    5.    private var running = false
    6.    private var totalLines = 0
    7.    private var linesProcessed = 0
    8.    private var result = 0
    9.    private var fileSender: Option[ActorRef] = None
    10.
    11.   def receive = {
    12.     case StartProcessFileMsg() => {
    13.       if (running) {
    14.         // println just used for example purposes;
    15.         // Akka logger should be used instead
    16.         println("Warning: duplicate start message received")
    17.       } else {
    18.         running = true
    19.         fileSender = Some(sender) // save reference to process invoker
    20.         import scala.io.Source._
    21.         fromFile(filename).getLines.foreach { line =>
    22.           context.actorOf(Props[StringCounterActor]) ! ProcessStringMsg(line)
    23.           totalLines += 1
    24.         }
    25.       }
    26.     }
    27.     case StringProcessedMsg(words) => {
    28.       result += words
    29.       linesProcessed += 1
    30.       if (linesProcessed == totalLines) {
    31.         fileSender.map(_ ! result)  // provide result to process invoker
    32.       }
    33.     }
    34.     case _ => println("message not recognized!")
    35.   }
    36. }
    

    Many things are going on in here, so let’s examine each of them in more detail (note that the line numbers referenced in the discussion that follows are based on the above code sample)…
    First, notice that the name of the file to process is passed to the WordCounterActor constructor (line 3). This indicates that the actor is only to be used to process a single file. This also simplifies the coding job for the developer, by avoiding the need to reset state variables (running, totalLines, linesProcessed, and result) when the job is done, since the instance is only used once (i.e., to process a single file) and then discarded.
    Next, observe that the WordCounterActor handles two types of messages:

    • StartProcessFileMsg (line 12)
      • Received from the external actor that initially initiates the WordCounterActor.
      • When received, the WordCounterActor first checks that it is not receiving a redundant request.
      • If the request is redundant, WordCounterActor generates a warning and nothing more is done (line 16).
      • If the request is not redundant:
        • WordCounterActor stores a reference to the sender in the fileSender instance variable (note that this is an Option[ActorRef] rather than an Option[Actor] – see line 9). This ActorRef is needed in order to later access and respond to it when processing the final StringProcessedMsg (which is received from a StringCounterActor child, as described below).
        • WordCounterActor then reads the file and, as each line in the file is loaded, a StringCounterActorchild is created and a message containing the line to be processed is passed to it (lines 21-24).
    • StringProcessedMsg (line 27)
      • Received from a child StringCounterActor when it completes processing the line assigned to it.
      • When received, the WordCounterActor increments the line counter for the file and, if all lines in the file have been processed (i.e., when totalLines and linesProcessed are equal), it sends the final result to the original fileSender (lines 28-31).

    Once again, notice that in Akka, the sole mechanism for inter-actor communication is message passing. Messages are the only thing that actors share and, since actors can potentially access the same messages concurrently, it is important for them to be immutable, in order to avoid race conditions and unexpected behaviors.

    Case classes in Scala are regular classes that provide a recursive decomposition mechanism via pattern matching.

    It is therefore common to pass messages in the form of case classes since they are immutable by default and because of how seamlessly they integrate with pattern matching.
    Let’s conclude the example with the code sample to run the whole app.

    object Sample extends App {
      import akka.util.Timeout
      import scala.concurrent.duration._
      import akka.pattern.ask
      import akka.dispatch.ExecutionContexts._
      implicit val ec = global
      override def main(args: Array[String]) {
        val system = ActorSystem("System")
        val actor = system.actorOf(Props(new WordCounterActor(args(0))))
        implicit val timeout = Timeout(25 seconds)
        val future = actor ? StartProcessFileMsg()
        future.map { result =>
          println("Total number of words " + result)
          system.shutdown
        }
      }
    }
    
    In concurrent programming, a “future” is a essentially a placeholder object for a result that is not yet known.

    Notice how this time the ? method is used to send a message. In this way, the caller can use the returnedFuture to print the final result when this is available and to exit the program by shutting down the ActorSystem.

    Akka fault tolerance and supervisor strategies

    In an actor system, each actor is the supervisor of its children. If an actor fails to handle a message, it suspends itself and all of its children and sends a message, usually in the form of an exception, to its supervisor.

    In Akka, supervisor strategies are the primary and straightforward mechanism for defining the fault tolerant behavior of your system.

    In Akka, the way in which a supervisor reacts to and handles exceptions that percolate up to it from its children is referred to as a supervisor strategy. Supervisor strategies are the primary and straightforward mechanism by which you define the fault tolerant behavior of your system.
    When a message signifying a failure reaches a supervisor, it can take one of the following actions:

    • Resume the child (and its children), keeping its internal state. This strategy can be applied when the child state was not corrupted by the error and it can continue functioning correctly.
    • Restart the child (and its children), clearing its internal state. This strategy can be used in the opposite scenario of the one just described. If the child state has been corrupted by the error, it is necessary the reset its state before it can be used in the Future.
    • Stop the child (and its children) permanently. This strategy can be employed in cases where the error condition is not believed to be rectifiable, but does not jeopardize the rest of the operation being performed, which can be completed in the absence of the failed child.
    • Stop itself and escalate the error. Employed when the supervisor does not know how to handle the failure and so it escalates it to its own supervisor.

    Moreover, an Actor can decide to apply the action just to the failed children or to its siblings as well. There are two pre-defined strategies for this:

    • OneForOneStrategy: Applies the specified action to the failed child only
    • AllForOneStrategy: Applies the specified action to all of its children

    Here’s a simple example, using the OneForOneStrategy:

    import akka.actor.OneForOneStrategy
    import akka.actor.SupervisorStrategy._
    import scala.concurrent.duration._
    override val supervisorStrategy =
     OneForOneStrategy() {
       case _: ArithmeticException      => Resume
       case _: NullPointerException     => Restart
       case _: IllegalArgumentException => Stop
       case _: Exception                => Escalate
     }
    

    If no strategy is specified, the following default strategy is employed:

    • If there was an error while initializing the actor or if the actor was killed, the actor is stopped.
    • If there was any other kind of exception, the actor is simply restarted.

    The Akka-supplied implementation of this default strategy is as follows:

    final val defaultStrategy: SupervisorStrategy = {
      def defaultDecider: Decider = {
        case _: ActorInitializationException ⇒ Stop
        case _: ActorKilledException         ⇒ Stop
        case _: Exception                    ⇒ Restart
      }
      OneForOneStrategy()(defaultDecider)
    }
    

    Akka allows for the implementation of custom supervisor strategies, but as the Akka documentation warns, do so with caution as incorrect implementations may lead to problems such as blocked actor systems (i.e. permanently suspended actors).

    Location transparency

    The Akka architecture supports location transparency, enabling actors to be entirely agnostic to where the messages that they receive originated. The sender of the message may reside in the same JVM as the actor or in a separate JVM (either running on the same node or a different node). Akka enables each of these cases to be handled in a manner that is completely transparent to the actor (and therefore the developer). The only caveat is that messages sent across multiple nodes must be serializable.

    The Akka architecture supports location transparency, enabling actors to be entirely agnostic to where the messages that they receive originated.

    Actor systems are designed to run in a distributed environment without requiring any specialized code. Akka only requires the presence of a configuration file (application.conf) that specifies the nodes to send messages to. Here’s a simple example of a configuration file:

    akka {
      actor {
        provider = "akka.remote.RemoteActorRefProvider"
      }
      remote {
        transport = "akka.remote.netty.NettyRemoteTransport"
        netty {
          hostname = "127.0.0.1"
          port = 2552
        }
      }
    }
    

    A few parting tips…

    We have seen how the Akka framework helps achieve concurrency and high performance. However, as this tutorial pointed out, there are a few points to keep in mind when designing and implementing your system in order to exploit the power of Akka to its fullest:

    • To the greatest extent possible, each actor should be assigned the smallest task possible (as previously discussed, following the Single Responsibility Principle)
    • Actors should handle events (i.e., process messages) asynchronously and should not block, otherwise context switches will happen which can adversely affect performance. Specifically, it is best to perform blocking operations (IO, etc.) in a Future so as not to block the actor; i.e.:
        case evt => blockingCall() // BAD
        case evt => Future {
          blockingCall()           // GOOD
        }
      
    • Be sure your messages are all immutable, since the actors that pass them to one another will all be running concurrently in their own threads. Mutable messages are likely to result in unexpected behavior.
    • Since messages sent between nodes must be serializable, it is important to bear in mind that the larger the messages are, the longer it will take to serialize, send, and deserialize them, which can negatively impact performance.

    Conclusion

    Akka, written in Scala, simplifies and facilitates the development of highly-concurrent, distributed, and fault tolerant applications, hiding much of the complexity from the developer. Doing Akka full justice would require much more than this single tutorial, but hopefully this introduction and its examples were sufficiently captivating to get you to want to read more.
    Amazon, VMWare, and CSC are but a few examples of leading companies who are actively using Akka. Visit the official Akka website to learn more and to explore whether Akka could be the right answer for your project as well.

  • Getting Started with Docker: Simplifying Devops

    If you like whales, or are simply interested in quick and painless continuous delivery of your software to production, then I invite you to read this introductory Docker Tutorial. Everything seems to indicate that software containers are the future of IT, so let’s go for a quick dip with the container whales Moby Dock andMolly.

    Docker, represented by a logo with a friendly looking whale, is an open source project that facilitates deployment of applications inside of software containers. Its basic functionality is enabled by resource isolation features of the Linux kernel, but it provides a user-friendly API on top of it. The first version was released in 2013, and it has since become extremely popular and is being widely used by many big players such as eBay, Spotify, Baidu, and more. In the last funding round, Docker has landed a huge $95 million.

    Transporting Goods Analogy

    The philosophy behind Docker could be illustrated with a following simple analogy. In the international transportation industry, goods have to be transported by different means like forklifts, trucks, trains, cranes, and ships. These goods come in different shapes and sizes and have different storing requirements: sacks of sugar, milk cans, plants etc. Historically, it was a painful process depending on manual intervention at every transit point for loading and unloading.

    It has all changed with the uptake of intermodal containers. As they come in standard sizes and are manufactured with transportation in mind, all the relevant machineries can be designed to handle these with minimal human intervention. The additional benefit of sealed containers is that they can preserve the internal environment like temperature and humidity for sensitive goods. As a result, the transportation industry can stop worrying about the goods themselves and focus on getting them from A to B.

    And here is where Docker comes in and brings similar benefits to the software industry.

    How Is It Different from Virtual Machines?

    At a quick glance, virtual machines and Docker containers may seem alike. However, their main differences will become apparent when you take a look at the following diagram:

    Applications running in virtual machines, apart from the hypervisor, require a full instance of the operating system and any supporting libraries. Containers, on the other hand, share the operating system with the host. Hypervisor is comparable to the container engine (represented as Docker on the image) in a sense that it manages the lifecycle of the containers. The important difference is that the processes running inside the containers are just like the native processes on the host, and do not introduce any overheads associated with hypervisor execution. Additionally, applications can reuse the libraries and share the data between containers.
    As both technologies have different strengths, it is common to find systems combining virtual machines and containers. A perfect example is a tool named Boot2Docker described in the Docker installation section.

    Docker Architecture

    Docker Architecture
    At the top of the architecture diagram there are registries. By default, the main registry is the Docker Hub which hosts public and official images. Organizations can also host their private registries if they desire.
    On the right-hand side we have images and containers. Images can be downloaded from registries explicitly (docker pull imageName) or implicitly when starting a container. Once the image is downloaded it is cached locally.
    Containers are the instances of images – they are the living thing. There could be multiple containers running based on the same image.
    At the centre, there is the Docker daemon responsible for creating, running, and monitoring containers. It also takes care of building and storing images. Finally, on the left-hand side there is a Docker client. It talks to the daemon via HTTP. Unix sockets are used when on the same machine, but remote management is possible via HTTP based API.

    Installing Docker

    For the latest instructions you should always refer to the official documentation.
    Docker runs natively on Linux, so depending on the target distribution it could be as easy as sudo apt-get install docker.io. Refer to the documentation for details. Normally in Linux, you prepend the Docker commands with sudo, but we will skip it in this article for clarity.
    As the Docker daemon uses Linux-specific kernel features, it isn’t possible to run Docker natively in Mac OS or Windows. Instead, you should install an application called Boot2Docker. The application consists of a VirtualBox Virtual Machine, Docker itself, and the Boot2Docker management utilities. You can follow the official installation instructions for MacOS and Windows to install Docker on these platforms.

    Using Docker

    Let us begin this section with a quick example:

    docker run phusion/baseimage echo "Hello Moby Dock. Hello Molly."
    

    We should see this output:

    Hello Moby Dock. Hello Molly.
    

    However, a lot more has happened behind the scenes than you may think:

    • The image ‘phusion/baseimage’ was download from Docker Hub (if it wasn’t already in local cache)
    • A container based on this image was started
    • The command echo was executed within the container
    • The container was stopped when the command exitted

    On first run, you may notice a delay before the text is printed on screen. If the image had been cached locally, everything would have taken a fraction of a second. Details about the last container can be retrieved by by running docker ps -l:

    CONTAINER ID		IMAGE					COMMAND				CREATED			STATUS				PORTS	NAMES
    af14bec37930		phusion/baseimage:latest		"echo 'Hello Moby Do		2 minutes ago		Exited (0) 3 seconds ago		stoic_bardeen
    

    Taking the Next Dive

    As you can tell, running a simple command within Docker is as easy as running it directly on a standard terminal. To illustrate a more practical use case, throughout the remainder of this article, we will see how we can utilize Docker to deploy a simple web server application. To keep things simple, we will write a Java program that handles HTTP GET requests to ‘/ping’ and responds with the string ‘pongn’.

    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    import com.sun.net.httpserver.HttpExchange;
    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;
    public class PingPong {
        public static void main(String[] args) throws Exception {
            HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
            server.createContext("/ping", new MyHandler());
            server.setExecutor(null);
            server.start();
        }
        static class MyHandler implements HttpHandler {
            @Override
            public void handle(HttpExchange t) throws IOException {
                String response = "pongn";
                t.sendResponseHeaders(200, response.length());
                OutputStream os = t.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }
    }
    

    Dockerfile

    Before jumping in and building your own Docker image, it’s a good practice to first check if there is an existing one in the Docker Hub or any private registries you have access to. For example, instead of installing Java ourselves, we will use an official image: java:8.
    To build an image, first we need to decide on a base image we are going to use. It is denoted by FROMinstruction. Here, it is an official image for Java 8 from the Docker Hub. We are going to copy it into our Java file by issuing a COPY instruction. Next, we are going to compile it with RUN. EXPOSE instruction denotes that the image will be providing a service on a particular port. ENTRYPOINT is an instruction that we want to execute when a container based on this image is started and CMD indicates the default parameters we are going to pass to it.

    FROM java:8
    COPY PingPong.java /
    RUN javac PingPong.java
    EXPOSE 8080
    ENTRYPOINT ["java"]
    CMD ["PingPong"]
    

    After saving these instructions in a file called “Dockerfile”, we can build the corresponding Docker image by executing:

    docker build -t toptal/pingpong .
    

    The official documentation for Docker has a section dedicated to best practices regarding writing Dockerfile.

    Running Containers

    When the image has been built, we can bring it to life as a container. There are several ways we could run containers, but let’s start with a simple one:

    docker run -d -p 8080:8080 toptal/pingpong
    

    where -p [port-on-the-host]:[port-in-the-container] denotes the ports mapping on the host and the container respectively. Furthermore, we are telling Docker to run the container as a daemon process in the background by specifying -d. You can test if the web server application is running by attempting to access ‘https://localhost:8080/ping’. Note that on platforms where Boot2docker is being used, you will need to replace ‘localhost’ with the IP address of the virtual machine where Docker is running.
    On Linux:

    curl https://localhost:8080/ping
    

    On platforms requiring Boot2Docker:

    curl $(boot2docker ip):8080/ping
    

    If all goes well, you should see the response:

    pong
    

    Hurray, our first custom Docker container is alive and swimming! We could also start the container in an interactive mode -i -t. In our case, we will override the entrypoint command so we are presented with a bash terminal. Now we can execute whatever commands we want, but exiting the container will stop it:

    docker run -i -t --entrypoint="bash" toptal/pingpong
    

    There are many more options available to use for starting up the containers. Let us cover a few more. For example, if we want to persist data outside of the container, we could share the host filesystem with the container by using -v. By default, the access mode is read-write, but could be changed to read-only mode by appending :ro to the intra-container volume path. Volumes are particularly important when we need to use any security information like credentials and private keys inside of the containers, which shouldn’t be stored on the image. Additionally, it could also prevent the duplication of data, for example by mapping your local Maven repository to the container to save you from downloading the Internet twice.
    Docker also has the capability of linking containers together. Linked containers can talk to each other even if none of the ports are exposed. It can be achieved with –link other-container-name. Below is an example combining mentioned above parameters:

    docker run -p 9999:8080
        --link otherContainerA --link otherContainerB
        -v /Users/$USER/.m2/repository:/home/user/.m2/repository
        toptal/pingpong
    

    Other Container and Image Operations

    Unsurprisingly, the list of operations that one could apply to the containers and images is rather long. For brevity, let us look at just a few of them:

    • stop – Stops a running container.
    • start – Starts a stopped container.
    • commit – Creates a new image from a container’s changes.
    • rm – Removes one or more containers.
    • rmi – Removes one or more images.
    • ps – Lists containers.
    • images – Lists images.
    • exec – Runs a command in a running container.

    Last command could be particularly useful for debugging purposes, as it lets you to connect to a terminal of a running container:

    docker exec -i -t <container-id> bash
    

    Docker Compose for the Microservice World

    If you have more than just a couple of interconnected containers, it makes sense to use a tool like docker-compose. In a configuration file, you describe how to start the containers and how they should be linked with each other. Irrespective of the amount of containers involved and their dependencies, you could have all of them up and running with one command: docker-compose up.

    Docker in the Wild

    Let’s look at three stages of project lifecycle and see how our friendly whale could be of help.

    Development

    Docker helps you keep your local development environment clean. Instead of having multiple versions of different services installed such as Java, Kafka, Spark, Cassandra, etc., you can just start and stop a required container when necessary. You can take things a step further and run multiple software stacks side by side avoiding the mix-up of dependency versions.
    With Docker, you can save time, effort, and money. If your project is very complex to set up, “dockerise” it. Go through the pain of creating a Docker image once, and from this point everyone can just start a container in a snap.
    You can also have an “integration environment” running locally (or on CI) and replace stubs with real services running in Docker containers.

    Testing / Continuous Integration

    With Dockerfile, it is easy to achieve reproducible builds. Jenkins or other CI solutions can be configured to create a Docker image for every build. You could store some or all images in a private Docker registry for future reference.
    With Docker, you only test what needs to be tested and take environment out of the equation. Performing tests on a running container can help keep things much more predictable.
    Another interesting feature of having software containers is that it is easy to spin out slave machines with the identical development setup. It can be particularly useful for load testing of clustered deployments.

    Production

    Docker can be a common interface between developers and operations personnel eliminating a source of friction. It also encourages the same image/binaries to be used at every step of the pipeline. Moreover, being able to deploy fully tested container without environment differences help to ensure that no errors are introduced in the build process.
    You can seamlessly migrate applications into production. Something that was once a tedious and flaky process can now be as simple as:

    docker stop container-id; docker run new-image
    

    And if something goes wrong when deploying a new version, you can always quickly roll-back or change to other container:

    docker stop container-id; docker start other-container-id
    

    … guaranteed not to leave any mess behind or leave things in an inconsistent state.

    Summary

    A good summary of what Docker does is included in its very own motto: Build, Ship, Run.

    • Build – Docker allows you to compose your application from microservices, without worrying about inconsistencies between development and production environments, and without locking into any platform or language.
    • Ship – Docker lets you design the entire cycle of application development, testing, and distribution, and manage it with a consistent user interface.
    • Run – Docker offers you the ability to deploy scalable services securely and reliably on a wide variety of platforms.

    Have fun swimming with the whales!

  • Meteor Tutorial: Building Real-Time Web Applications with Meteor

    Meteor is a full-stack JavaScript framework for web and mobile applications. It has been around since 2011, and has gained a strong reputation among Meteor developers for being an ideal, easy-to-use solution for rapid prototyping. However, lately developers have realized Meteor isn’t just for prototyping anymore: it’s ready to be used for commercial development. With the arsenal of packages that it provides, the solid mongoDB/node.js foundation that it relies on, and the coding flexibility that it offers; Meteor makes it easy to buildrobust, secure real-time web applications, handling everything from the browser app to the server or database.
    meteor tutorial
    This Meteor tutorial will walk you through making a basic web application in Meteor – a simple catalog that lets users login and manage a list of books.
    Why use Meteor? The short answer is, “because Meteor is fun”. It makes developing web applications simple. It is easy to learn, and it lets you focus more on the functionality of your application than the basics of syncing data and serving pages.
    It also has lots of behaviors conveniently built in. Meteor automatically performs live updates, so data changes show up immediately in your browser window, and even code changes to the application itself are pushed to all browsers and devices in “real-time”. Meteor has built-in latency compensation, is easy to deploy, and has easy-to-install “packages” that handle all sorts of functionality.
    Even though it’s a relatively new framework, lots of startups are already building Meteor apps, including relatively large-scale services like Respondly and Telescope.

    Meteor Installation and Scaffolding

    Installing Meteor on *nix systems is a one-liner:

    curl https://install.meteor.com/ | sh
    

    Although there is still no official support, their preview for Windows is coming along nicely. Rumors are that Windows support will ship with 1.1, due out in April or May of 2015. As you may expect from a smart framework like Meteor, bootstrapping an application requires a single line of command to be invoked:

    meteor create book-list
    

    This will create a directory named “book-list”, and populate it with some boilerplate and dependent code. To run the application, enter the newly created directory and execute:

    meteor
    

    Open https://localhost:3000 in your web browser, and you’ll see the following:
    welcome to meteor
    You can also check out the “version 0” of our application on MeteorPad, a site that’s like JSFiddle for Meteor: Book List: Default App
    Meteor stores its views in HTML files. If we open “book-list.html”, we will see:

    <head>
      <title>book-list</title>
    </head>
    <body>
      <h1>Welcome to Meteor!</h1>
      {{> hello}}
    </body>
    <template name="hello">
      <button>Click Me</button>
      <p>You've pressed the button {{counter}} times.</p>
    </template>
    

    Meteor uses “Blaze”, a templating engine, to render responses from these HTML files. The double braces should be familiar to anyone who has used Handlebars.js (or other similar templating engines), and they serve a similar function here. Blaze examines the expressions inside each pair of double braces and replaces each one with the value that these expressions yield.
    This simple example program has just two double-braced expressions:

    • The first, “{{> hello}}”, tells Blaze to include a template called “hello”. That template is defined at the bottom of the file, in the <template name=”hello”> section.
    • The second, “{{counter}}”, is a little more complicated. To see where this “counter” value is coming from we need to open “book-list.js”:
    if (Meteor.isClient) {
      // counter starts at 0
      Session.setDefault('counter', 0);
      Template.hello.helpers({
        counter: function () {
          return Session.get('counter');
        }
      });
      Template.hello.events({
        'click button': function () {
          // increment the counter when button is clicked
          Session.set('counter', Session.get('counter') + 1);
        }
      });
    }
    if (Meteor.isServer) {
      Meteor.startup(function () {
        // code to run on server at startup
      });
    }
    

    Some things require explaining here. First, the split into “if (Meteor.isClient)” and “if (Meteor.isServer)”. Recall that meteor is a full-stack framework, so the code that you write is run on both the server and the client. These conditionals allow us to limit that: the first block runs only on the client, and the second one runs only on the server.
    Second, there’s the “Session.setDefault” call – this initializes a session variable called “counter” in the browser. Session variables act a bit like globals in Meteor (for good and for ill). However, that session variable is not showing up directly in “{{counter}}”. Instead, that “counter” expression is a “helper”, one that’s defined in the “Template.hello.helpers” section. This helper simply grabs the session variable’s value and returns it.
    Note that the helper is “reactive”. This means that any time the session variable changes, Meteor automatically re-runs this helper function that’s referencing it, and Blaze automatically updates the browser with the new content.
    The client code also monitors events, via “Template.hello.events”. We identify the event by event type and selector (in this case, “click button”), and then tell Meteor what that event should do. In this case, the session variable is incremented, which re-runs the helper function and in turn re-renders the content.

    Displaying Static Data

    All of this is well and good, but it’s not the Meteor application we want for this tutorial.
    Let’s start tweaking this application – we’ll display a static, hard-coded list of books. For now, we’ll stash the list of books in a session variable. In the “isClient” code, we’ll use “Template.hello.rendered” to set the session variable as soon as the bookList template is rendered:

      Template.hello.rendered = function() {
        Session.setDefault('books', [
          {title: "To Kill a Mockingbird", author: "Harper Lee"},
          {title: "1984", author: "George Orwell"},
          {title: "The Lord of the Rings", author: "J. R. R. Tolkien"},
          {title: "The Catcher in the Rye", author: "J. D. Salinger"},
          {title: "The Great Gatsby", author: "F. Scott Fitzgerald"}
        ]);
      };
    

    Then, we return that session variable with a new helper in the “hello” template:

      Template.hello.helpers({
        books: function () {
          return Session.get('books');
        }
      });
    

    And display it on screen via variable interpolation in the “hello” template:

    <template name="hello">
      <h3>Here are your books:</h3>
      {{ books }}
    </template>
    

    You can check out this code in action on Meteorpad: Book-List: Show Session Variable
    The first thing to notice is that the Meteor server automatically detected the changes to our codebase, pushed the new code to the clients, and prompted the client to reload. Even after we’ve deployed an application, we can deploy changes and automatically update our clients via hot-code pushes.
    deploy changes automatically
    So far, this is what we get:
    incorrect data display
    Oops, we’re displaying the data wrong. Blaze gets points for accuracy here (why yes, it is an array of objects), but we’re going to have to be a bit more clever if we want to display our list of books in a useful way. Fortunately, Blaze makes it very easy to work with arrays of data using the “#each” directive:

     <h3>Here are your books:</h3>
      <UL>
        {{#each books}}
            <LI><i>{{title}}</i> by {{author}}</LI>
        {{/each}}
      </UL>
    

    In Blaze, “#each” works a bit like Angular’s “ng-repeat” directive – it iterates through the array structure, setting the current context to the current object in the array, and repeatedly displaying the HTML inside the “{{#each …}}”. This is what our list of books look like now:
    correct data display
    On MeteorPad: Show Session Variable Properly

    Some Cleaning Up

    Before going any further, let’s clean up our code a little.
    Meteor allows tremendous leeway in how you organize your codebase. As you will see, there are only a few hard-and-fast rules: wherever you put your HTML and JavaScript, Meteor will find it. This flexibility is nice, but it does mean it’s more incumbent on you to organize your code in a way that makes sense, so you’re not stuck maintaining a giant disordered mess.
    First, let us rename this “hello” template to something meaningful, like “bookList”, and replace the boilerplate HTML with this:

    <head>
      <title>book-list</title>
    </head>
    <body>
      {{> bookList}}
    </body>
    <template name="bookList">
      <h3>Here are some books:</h3>
      <UL>
        {{#each books}}
            <LI><i>{{title}}</i> by {{author}}</LI>
        {{/each}}
      </UL>
    </template>
    

    Second, let us split up the “client” and “server” parts into separate files. In our application directory, we’ll set up a “client” subdirectory and a “server” subdirectory – Meteor will know automatically to run the “/client/” files on the client, and run the “/server/” files on the server. It’s a good convention to put template code in a JavaScript file named after the template, so let’s put our client code into “client/bookList.js”. We can put our currently empty server-startup code in “server/startup.js”. Finally, let’s move out the “
    Note that even after all this switching around, Meteor will still automatically find all of our HTML and JavaScript files. So long as a file is somewhere in “/client/”, Meteor will know to run it on the client. So long as a file is somewhere in “/server/”, meteor will know to run it on the server. Again, it is up to the developer to keep things organized.
    So now our code should look like this:

    book-list.html:

    <head>
      <title>book-list</title>
    </head>
    <body>
      {{> bookList}}
    </body>
    

    client/bookList.html:

    <template name="bookList">
      <h3>Here are some books:</h3>
      <UL>
        {{#each books}}
            <LI><i>{{title}}</i> by {{author}}</LI>
        {{/each}}
      </UL>
    </template>
    

    client/bookList.js:

    Template.bookList.rendered = function() {
      Session.setDefault('books', [
        {title: "To Kill a Mockingbird", author: "Harper Lee"},
        {title: "1984", author: "George Orwell"},
        {title: "The Lord of the Rings", author: "J. R. R. Tolkien"},
        {title: "The Catcher in the Rye", author: "J. D. Salinger"},
        {title: "The Great Gatsby", author: "F. Scott Fitzgerald"}
      ]);
    };
    Template.bookList.helpers({
      books: function () {
        return Session.get('books');
      }
    });
    

    server/startup.js:

    Meteor.startup(function () {
        // code to run on server at startup
    });
     ~~~
    Check it out on MeteorPad: [Initial Code Cleanup](http://meteorpad.com/pad/MwvMcsBAzfbWwEXp3/Book-List:%20Initial%20Code%20Cleanup)
    Verify that everything's running correctly by checking the browser window and then we're good to move on to the next step.
    ## Using the Database in Meteor
    The Meteor server runs on top of a MongoDB database. In this section of our tutorial, we will move the static list of books out of the session variable and into that database.
    First, delete the Template.bookList.rendered code, so that we're no longer putting stuff into that session variable. Next, we should add that list of books to the database as fixture data when the server initializes. As you'd expect for MongoDB, Meteor stores data in "collections". So, we'll create a new collection for our books. To keep things simple we will name it "books". It turns out that both the client and the server will want to know about this collection, so we'll put this code in a new subfolder: "/lib/". Meteor knows automatically that files in "/lib/" run on the client and the server.
    We'll create a file called "lib/collections/books.js", and give it just one line of code:
    ~~~ js
    Books = new Meteor.Collection("books");
    

    Within the browser window pointed at https://localhost:3000, go to the developer console and check the value of “Books”. It should now be a Mongo collection! Try running “Books.find().fetch()”, and you’ll get an empty array – which makes sense, since we haven’t added any books to it yet. We can try adding items to it in the console:

    Books.insert({title: "To Kill a Mockingbird", author: "Harper Lee"})
    

    Adding things in the console is rather tedious. Instead, we’ll set things up so that when the server starts up we automatically insert fixture data into the database. So let’s go back to “server/startup.js”, and add this:

    Meteor.startup(function () {
        if (!Books.findOne()) {
            Books.insert({title: "To Kill a Mockingbird", author: "Harper Lee"});
            Books.insert({title: "1984", author: "George Orwell"});
            Books.insert({title: "The Lord of the Rings", author: "J. R. R. Tolkien"});
            Books.insert({title: "The Catcher in the Rye", author: "J. D. Salinger"});
            Books.insert({title: "The Great Gatsby", author: "F. Scott Fitzgerald"});
        }
    });
    

    Now, when the server starts up, if there’s no data present we’ll add the fixture data. We can verify this by going back to our terminal, stopping the meteor server, and running this command:

    meteor reset
    

    Note: you will rarely need this command, because it resets – i.e., clears– the database Meteor is using. If your Meteor application has any user data in the database, you shouldn’t run this command. But in this case, we’ll just clear out whatever test data we have.
    Now we’ll start the server again:

    meteor
    

    On startup, Meteor will run the startup routine, see that the database is empty, and add the fixture data. At this point, if we go to the console and type “Books.find().fetch()”, we get the five books we had before.
    All that’s left for this step is to display the books on screen. Fortunately, that is as simple as replacing “return Session.get(‘books’);” with the following in “books” helper:

    return Books.find();
    

    And we’re back in business! The application is now displaying data from a database cursor, instead of from the session variable.
    Check it out on MeteorPad: Moving to the Database

    Security Concerns

    I’ll preface this by saying: “don’t do this”.
    What do you think would happen if somebody fired up this app in their browser, went to the console, and typed in “Books.remove({})”?
    The answer is: they’d wipe out the collection.
    So, that’s a pretty large security problem – our users have too muchaccess to our database. Any client can access the whole database. Not only that, any client can make any change to the whole database, including that “.remove({})” data wipeout.
    This is not good, so let’s fix it.
    Meteor uses so-called “packages” for adding functionality. What modules are to Node.js, and gems are to Ruby, packages are a bundled goodness of functionality for Meteor. There are packages for all sorts of things. To browse through what’s available, check out atmosphere.js.
    The default meteor app that we made with “meteor create” includes two packages called “autopublish” and “insecure”. The first package makes it so that clients have automatic access to the whole database, and the second makes it so that users can perform any actions on that database.
    Let’s remove those. We can do that by running the following from the app directory:

    meteor remove autopublish insecure
    

    When that’s done, you’ll see the book-list data disappear from the screen (since you no longer have access to it), and if you try a “Books.insert” call, you’ll get the error: “insert failed: Access denied”. On MeteorPad: Security Overkill
    If you take nothing else from this Meteor tutorial, please remember this: when you’re deploying a Meteor app, be sure you remove the packages autopublish and insecure. Meteor has many good security precautions, but all of them are for naught if you leave those two packages installed.
    So, why does Meteor automatically include these packages at all, if they’re such a security hazard? The reason is that, especially for beginners, those two packages make it easier to get started – you can easily debug and tweak the database from a browser’s console. But it’s a good practice to ditch autopublish and insecure as soon as possible.

    Publish and Subscribe

    So we fixed that gaping security hole, but we’ve introduced two problems. First, we now have no access to the database. Second, we have no way of interacting with the database.
    Let’s tackle the first problem here. Meteor provides secure access to a database by having the server “publish” a subset of the database, and having the client “subscribe” to that publication.
    First, let’s create “/server/publications.js”:

    Meteor.publish('books', function() {
      return Books.find({});
    });
    

    And we’ll create “/client/subscriptions.js”:

    Meteor.subscribe('books');
    

    Check it out on MeteorPad: Publish and Subscribe
    The server “publishes” a cursor that has access to all the data, and the client “subscribes” to it on the other end. The client uses this subscription to populate a mirrored copy of the database with all of the cursor’s data. When we access “Books.find().fetch()”, we see all five objects, and we see them displayed on screen as before.
    The difference now is that it’s really easy to limit what the clients can access. Try switching the publication “find()” to a subset of the data:

    Meteor.publish('books', function() {
      return Books.find({}, {limit:3});
    });
    

    Now the client only ever sees three of the five books, and there’s no way to get to the rest. Not only is this a great boon for security (I don’t get to see everybody else’s bank accounts), but you can use it to parcel out data and avoid overloading a client.

    Adding New Books

    We’ve seen how to give clients read-access to the database in a limited, secure way. Now, let’s look at the second problem: how do we let users alter the database without allowing them to do anything they want? Getting rid of the package insecure made it so clients have no access at all – let’s try allowing the addition of books again. In meteor, we do this by adding a “method” to the server. Let’s add a method, one that adds a new book, to “/lib/collections/books.js”:

    Meteor.methods({
      addBook: function(bookData) {
        var bookID = Books.insert(bookData);
        return bookID;
      }
    });
    

    As you can see, this takes in “bookData” – in this case, that’s an object with “title” and “author” fields – and adds it to the database. Once your client reloads, we can then call this method from the client. You can go to the console and enter something like this:

    Meteor.call('addBook', {title: "A Tale of Two Cities", author: "Charles Dickens"})
    

    And presto! You get another book on the list of books. Using the console is intolerably clunky, so let’s go ahead and add a simple form to the end of the “bookList” template that will let us add new books:

    <form class="add-book">
    	Title:<br>
    	<input type="text" name="title">
    	<br>
    	Author:<br>
    	<input type="text" name="author">
    	<input type="submit" value="Add Book">
    </form>
    

    And we can hook that up to JavaScript using an event case, like we had in the original test application:

    Template.bookList.events({
      "submit .add-book": function(event) {
        event.preventDefault(); // this prevents built-in form submission
        Meteor.call('addBook', {title: event.target.title.value, author: event.target.author.value})
      }
    });
    

    You can see this in action on MeteorPad: Methods
    When we had insecure and autopublish in place, clients could access and alter the whole database. Now with insecure and autopublish gone, but with publications, subscriptions, and methods, clients can access the database and interact with it in a controlled manner.
    On a side note: you can also address security issues in Meteor by using “allow and deny rules”. You can find out more about those and some reasons I prefer the above approach instead atdiscovermeteor.com.

    User Authentication

    It may look like we’ve just circled back around to where we started, but there’s one important difference: it’s really easy for us to now limit access to the database. To see how this works, let’s try adding users to this app. We’ll add a login system to our app, and then instead of having all clients work with one system-wide list of books, we’ll make it so each user can only add to or read their own list of books.
    Go to the app directory, and install two packages:

    meteor add accounts-ui accounts-password
    

    There. You’ve just added a login system to the app. Now we just need to add the login UI to book-list.html. Put this single line at the top of the body:

    {{> loginButtons}}
    

    You should see a login prompt at the top of the screen:
    login prompt
    Notice that if you click the login link, it’ll ask for an email address and password. We can switch that to simple username/password login system by creating “/client/config.js” with the following in it:

    Accounts.ui.config({
        passwordSignupFields: "USERNAME_ONLY"
    });
    

    At this point, you can type “Meteor.userId()” in the console, and it will return “null”. You can try clicking the link to create an account. Calling “Meteor.userId()” should now return an ID string. The server has access to this same piece of information (as “this.userId”), so it’s trivial to make the “add books” method force the user to be logged in and include a userID field:

    Meteor.methods({
      addBook: function(bookData) {
        if (this.userId) {
            bookData.userID = this.userId;
            var bookID = Books.insert(bookData);
            return bookID;
        }
      }
    });
    

    All that remains now is to limit the client, showing only the books that this user has added. We use the publication’s ability to narrow down what the client has access to:

    Meteor.publish('books', function() {
        return Books.find({userID: this.userId});
    });
    

    Now, the publication only finds books from this particular user. We can even access the userId from Blaze expressions as “{{currentUser}}”; and we can use this, with an “{{#if}}” directive (which does exactly what you think it does), to only show data when the user is logged in:

    <template name="bookList">
      {{#if currentUser}}
        <h3>Here are your books:</h3>
        <UL>
          {{#each books}}
              <LI><i>{{title}}</i> by {{author}}</LI>
          {{/each}}
        </UL>
        <form class="add-book">
        	Title:<br>
        	<input type="text" name="title">
        	<br>
        	Author:<br>
        	<input type="text" name="author">
        	<input type="submit" value="Add Book">
        </form>
      {{else}}
        <h3>Please log in to see your books</h3>
      {{/if}}
    </template>
    

    Check out the final result on MeteorPad: Users

    Deployment

    Now we can deploy this Meteor application to the Internet. We do this by going to the application directory on a terminal and executing:

    meteor deploy <your app's name>.meteor.com
    

    Make sure you replace “<your app’s name>” with an actual, short name for the application instance. Running this command will prompt you to set up an account with Meteor, and then it will put your new application on Meteor’s test servers so that you can try it out on the Internet.
    For a quick demo, this meteor.com solution is all you need. The Meteor team hasn’t announced any explicit limits to storage or bandwidth on their servers. The only notable limitation is that if your app goes unused for a long time, the site takes a few seconds to spin up for the next user.
    That said, meteor.com is not intended for commercial use. But when you go to production, there are platform-as-a-service companies likeModulus and Digital Ocean that make deploying Meteor apps easy. Should you want to deploy a meteor app to your own server, “meteor up” makes that process straightforward, too.

    Next Steps

    Congratulations! In your quest to learn Meteor you’ve now made and deployed a very simple real-time Meteor web application. Obviously, this is just a tiny first step into a whole universe of features and functionality. If you like what you’ve seen so far, I highly recommendYour First Meteor Application by David Turnbull, which walks readers through creating a more complicated application, with more information about meteor features along the way. It’s available as a Kindle book for a small price, and as a free PDF on Turnbull’s web site.
    You’ll also want to explore the packages that are available for Meteor. Nine times out of ten, the answer to “how do I do <x> in Meteor?” is “there’s a package for that”. “How do I add routing to my application?” You use Iron Router. “How do I provide a RESTful API?” You useRESTivus. “How do I include unit testing?” You use Velocity. “How do I add schema validations?” You use Collection2. You can easily get lost on Atmosphere.js looking at all the available packages.

    Why Not Use Meteor?

    As you can see from this tutorial, Meteor is simple and fun to write applications on, but I’d be remiss if I didn’t mention the drawbacks.
    Meteor is still relatively immature. It hit 1.0 this past October, and that leads to some problems. If you’re looking to do something obscure, it’s possible nobody’s written a package for that functionality yet. The packages that do exist are more likely to have bugs, simply because they haven’t been around long enough to suss out all of the problems.
    Scaling can also be somewhat unknown with Meteor. There are plenty of Meteor sites that scale up to reasonable amounts of users, but few very large sites – nothing on the order of Facebook or LinkedIn, with tens or hundreds of millions of users.
    However, for most applications Meteor is a perfect choice, as it is a chance to cut down on development time and to participate in the start of something great.

  • Getting Started with Your First Ember.js App

    As modern web applications do more and more on the client-side (the fact itself that we now refer to them as “web applications” as opposed to “web sites” is quite telling), there has been rising interest in client-side frameworks. There are a lot of players in this field but for applications with lots of functionality and many moving parts, two of them stand out in particular: Angular.js and Ember.js.
    We already published a comprehensive [Angular.js tutorial][https://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app], so we’re going to focus on Ember.js in this post, in which we’ll build a simple Ember application to catalog your music collection. You’ll be introduced to the framework’s main building blocks and get a glimpse into its design principles. Should you want to see the source code while reading, it’s available as rock-and-roll on Github.

    What are we going to build?

    Here’s what our Rock & Roll app is going to look like in its final version:
    Final version of app with ember.js
    On the left, you’ll see that we have a list of artists and, on the right, a list of songs by the selected artist (you can also see that I have good taste in music, but I digress). New artists and songs can be added simply by typing in the text box and pressing the adjacent button. The stars beside each song serve to rate it, à la iTunes.
    We could break down the app’s rudimentary functionality into the following steps:

    1. Clicking ‘Add’ adds a new artist to the list, with a name specified by the ‘New Artist’ field (same goes for songs for a given artist).
    2. Emptying the ‘New Artist’ field disables the ‘Add’ button (same goes for songs for a given artist).
    3. Clicking an artist’s name lists their songs on the right.
    4. Clicking the stars rates a given song.

    We have a long way to go to get this working, so let’s start.

    Routes: the key to the Ember.js app

    One of the distinguishing features of Ember is the heavy emphasis it puts on URLs. In many other frameworks, having separate URLs for separate screens is either lacking or is tacked on as an afterthought. In Ember, the router—the component that manages urls and transitions between them—is the central piece that coordinates work between building blocks. Consequently, it is also the key to understanding the innerworkings of Ember applications.
    Here are the routes for our application:

    App.Router.map(function() {
      this.resource('artists', function() {
        this.route('songs', { path: ':slug' });
      });
    });
    

    We define a resource route, artists, and a songs route nested inside it. That definition will give us the following routes:
    Routes
    I used the great Ember Inspector plugin (it exists both for Chrome and Firefox) to show you the generated routes in an easily readable way. Here are the basic rules for Ember routes, which you can verify for our particular case with the help of the above table:

    1. There is an implicit application route.This gets activated for all requests (transitions).
    2. There is an implicit index route.This gets entered when the user navigates to the root of the application.
    3. Each resource route creates a route with the same name and implicitly creates an index route below it.This index route gets activated when the user navigates to the route. In our case, artists.index gets triggered when the user navigates to /artists.
    4. A simple (non-resource), nested route will have its parent route name as its prefix.The route we defined as this.route('songs', ...) will have artists.songs as its name. It gets triggered when the user navigates to /artists/pearl-jam or /artists/radiohead.
    5. If the path is not given, it is assumed to be equal to the route name.
    6. If the path contains a :, it is considered a dynamic segment.The name assigned to it (in our case, slug) will match the value in the appropriate segment of the url. Theslug segment above will have the value pearl-jam, radiohead or any other value that was extracted from the URL.

    Display the list of artists

    As a first step, we’ll build the screen which displays the list of artists on the left. This screen should be shown to the users when they navigate to /artists/:
    Artists
    To understand how that screen is rendered, it’s time to introduce another overarching Ember design principle:convention over configuration. In the above section, we saw that /artists activates the artists route. By convention, the name of that route object is ArtistsRoute. It’s this route object’s responsibility to fetch data for the app to render. That happens in the route’s model hook:

    App.ArtistsRoute = Ember.Route.extend({
      model: function() {
        var artistObjects = [];
        Ember.$.getJSON('https://localhost:9393/artists', function(artists) {
          artists.forEach(function(data) {
            artistObjects.pushObject(App.Artist.createRecord(data));
          });
        });
        return artistObjects;
      }
    });
    

    In this snippet, the data is fetched via an XHR call from the back-end and—after conversion to a model object—pushed to an array which we can subsequently display. However, the responsbilities of the route do not extend to providing display logic, which is handled by the controller. Let’s take a look.
    Hmmm—in fact, we do not need to define the controller at this point! Ember is smart enough to generate the controller when needed and set the controller’s M.odel attribute to the return value of the model hook itself, namely, the list of artists. (Again, this is a result of the ‘convention over configuration’ paradigm.) We can step one layer down and create a template to display the list:

    <script type="text/x-handlebars" data-template-name="artists">
      <div class="col-md-4">
        <div class="list-group">
          {{#each model}}
            {{#link-to "artists.songs" this class="list-group-item artist-link"}}
              {{name}}
              <span class="pointer glyphicon glyphicon-chevron-right"></span>
            {{/link-to}}
          {{/each}}
        </div>
      </div>
      <div class="col-md-8">
        <div class="list-group">
          {{outlet}}
        </div>
      </div>
    </script>
    

    If this looks familiar, it’s because Ember.js uses Handlebars templates, which have a very simple syntax and helpers but do not allow for non-trivial logic (e.g., ORing or ANDing terms in a conditional).
    In the above template, we iterate through the model (set up earlier by the route to an array that contains all artists) and for each item in it, we render a link that takes us to the artists.songs route for that artist. The link contains the artist name. The #each helper in Handlebars changes the scope inside it to the current item, so {{name}} will always refer to the name of the artist that is currently under iteration.

    Nested routes for nested views

    Another point of interest in the above snippet: {{outlet}}, which specifies slots in the template where content can be rendered. When nesting routes, the template for the outer, resource route is rendered first, followed by the inner route, which renders its template content into the {{outlet}} defined by the outer route. This is exactly what happens here.
    By convention, all routes render their content into the template of the same name. Above, the data-template-name attribute of the above template is artists which means that it will get rendered for the outer route, artists. It specifies an outlet for the content of the right panel, into which the inner route, artists.index renders its content:

    <script type="text/x-handlebars" data-template-name="artists/index">
      <div class="list-group-item empty-list">
        <div class="empty-message">
          Select an artist.
        </div>
      </div>
    </script>
    

    In summary, one route (artists) renders its content in the left sidebar, its model being the list of artists. Another route, artists.index renders its own content into the slot provided by the artists template. It could fetch some data to serve as its model but in this case all we want to display is static text, so we don’t need to.

    Create an artist

    Part 1: Data binding

    Next, we want to be able to create artists, not just look at a boring list.
    When I showed that artists template that renders the list of artists, I cheated a bit. I cut out the top part to focus on what’s important. Now, I’ll add that back:

    <script type="text/x-handlebars" data-template-name="artists">
      <div class="col-md-4">
        <div class="list-group">
          <div class="list-group-item">
            {{input type="text" class="new-artist" placeholder="New Artist" value=newName}}
            <button class="btn btn-primary btn-sm new-artist-button" {{action "createArtist"}}
              {{bind-attr disabled=disabled}}>Add</button>
          </div>
        < this is where the list of artists is rendered >
      ...
    </script>
    

    We use an Ember helper, input, with type text to render a simple text input. In it, we bind the value of the text input to the newName property of the controller that backs up this template, ArtistsController. By consequence, when the value property of the input changes (in other words, when the user types text into it) the newName property on the controller will be kept in sync.
    We also make it known that the createArtist action should be fired when the button is clicked. Finally, we bind the disabled property of the button to the disabled property of the controller. So what does the controller look like?

    App.ArtistsController = Ember.ArrayController.extend({
      newName: '',
      disabled: function() {
        return Ember.isEmpty(this.get('newName'));
      }.property('newName')
    });
    

    newName is set to empty at the start which means that the text input is going to be blank. (Remember what I told about bindings? Try to change newName and see it get reflected as the text in the input field.)
    disabled is implemented such that when there is no text in the input box, it is going to return true and thus the button will be disabled. The .property call at the end makes this a “computed property”, another scrumptious slice of the Ember cake.
    Computed properties are properties that depend on other properties, which can themselves be “normal” or computed. Ember caches the value of these until one of the dependent properties change. It then recalculates the value of the computed property and caches it again.
    Here’s a visual representation of the above process. To summarize: when the user inputs an artist’s name, thenewName property updates, followed by the disabled property and, finally, the artist’s name is added to the list.

    Detour: A single source of truth

    Think about that for a moment. With the help of bindings and computed properties, we can establish (model) data as the single source of truth. Above, a change in the name of the new artist triggers a change in the controller property, which in turn triggers a change in the disabled property. As the user starts to type the name of the new artist, the button becomes enabled, as if by magic.
    The bigger the system, the more leverage we gain from the ‘single source of truth’ principle. It keeps our code clean and robust, and our property definitions, more declarative.
    Some other frameworks also put emphasis on having model data be the single source of truth but either do not go as far as Ember or fail to do such a thorough a job. Angular, for example, has two-way bindings—but does not have computed properties. It can “emulate” computed properties through simple functions; the problem here is that it has no way of knowing when to refresh a “computed property” and thus resorts to dirty checking and, in turn, leads to a performance loss, especially notable in bigger applications.
    Should you wish to learn more about the topic, I recommend you read eviltrout’s blog post for a shorter version or this Quora question for a lengthier discussion in which core developers from both sides weigh in.

    Part 2: Action handlers

    Let’s go back to see how the createArtist action is created after it’s fired (following the press of the button):

    App.ArtistsRoute = Ember.Route.extend({
      ...
      actions: {
        createArtist: function() {
          var name = this.get('controller').get('newName');
          Ember.$.ajax('https://localhost:9393/artists', {
            type: 'POST',
            dataType: 'json',
            data: { name: name },
            context: this,
            success: function(data) {
              var artist = App.Artist.createRecord(data);
              this.modelFor('artists').pushObject(artist);
              this.get('controller').set('newName', '');
              this.transitionTo('artists.songs', artist);
            },
            error: function() {
              alert('Failed to save artist');
            }
          });
        }
      }
    });
    

    Action handlers need to be wrapped in an actions object and can be defined on the route, controller or view. I chose to define it on the route here because the result of the action is not confined to the controller but rather, “global”.
    There is nothing fancy going on here. After the back-end informed us that the saving operation completed successfully, we do three things, in order:

    1. Add the new artist to the model of the template (all artists) so that it gets re-rendered and the new artist appears as the last item of the list.
    2. Clear the input field via the newName binding, saving us from having to manipulate the DOM directly.
    3. Transition to a new route (artists.songs), passing in the freshly created artist as the model for that route. transitionTo is the way to move between routes internally. (The link-to helper serves to do that via user action.)

    Display songs for an artist

    We can display the songs for an artist either by clicking on the artist’s name. We also pass in the artist that is going to become the model of the new route. If the model object is thusly passed in, the model hook of the route will not be called since there is no need to resolve the model.
    The active route here is artists.songs and thus the controller and template are going to be ArtistsSongsController and artists/songs, respectively. We already saw how the template gets rendered into the outlet provided by the artists template so we can focus on just the template at hand:

    <script type="text/x-handlebars" data-template-name="artists/songs">
      (...)
      {{#each songs}}
        <div class="list-group-item">
          {{title}}
          {{view App.StarRating maxRating=5}}
        </div>
      {{/each}}
    </script>
    

    Note that I stripped out the code to create a new song as it would be exactly the same as that for creating a new artist.
    The songs property is set up in all artist objects from the data returned by the server. The exact mechanism by which it is done holds little interest to the current discussion. For now, it’s sufficient for us to know that each song has a title and a rating.
    The title is displayed directly in the template and the rating gets represented by stars, via the StarRatingview. Let’s see that now.

    Star rating widget

    A song’s rating falls between 1 and 5 and gets shown to the user through a view, App.StarRating. Views have access to their context (in this case, the song) and their controller. This means they can read and modify its properties. This is in contrast to another Ember building block, components, which are isolated, reusable controls with access to only what has been passed in to them. (We could use a star rating component in this example, too.)
    Let’s see how the view displays the number of stars and sets the song’s rating when the user clicks on one of the stars:

    App.StarRating = Ember.View.extend({
      classNames: ['rating-panel'],
      templateName: 'star-rating',
      rating: Ember.computed.alias('context.rating'),
      fullStars: Ember.computed.alias('rating'),
      numStars:  Ember.computed.alias('maxRating'),
      stars: function() {
        var ratings = [];
        var fullStars = this.starRange(1, this.get('fullStars'), 'full');
        var emptyStars = this.starRange(this.get('fullStars') + 1, this.get('numStars'), 'empty');
        Array.prototype.push.apply(ratings, fullStars);
        Array.prototype.push.apply(ratings, emptyStars);
        return ratings;
      }.property('fullStars', 'numStars'),
      starRange: function(start, end, type) {
        var starsData = [];
        for (i = start; i <= end; i++) {
          starsData.push({ rating: i, full: type === 'full' });
        };
        return starsData;
      },
      (...)
    });
    

    rating, fullStars and numStars are computed properties which we discussed previously with the disabledproperty of the ArtistsController. Above, I used a so-called computed property macro, about a dozen of which are defined in Ember. They make typical computed properties more succinct and less error-prone (to write). I set rating to be the rating of the context (and thus the song), while I defined both the fullStars and numStars properties so that they read better in the context of the star rating widget.
    The stars method is the main attraction. It returns an array of data for the stars in which each item contains arating property (from 1 to 5) and a flag (full) to indicate whether the star is full. This makes it exceedingly simple to walk through them in the template:

    <script type="text/x-handlebars" data-template-name="star-rating">
      {{#each view.stars}}
        <span {{bind-attr data-rating=rating}}
          {{bind-attr class=":star-rating :glyphicon full:glyphicon-star:glyphicon-star-empty"}}
          {{action "setRating" target=view}}>
        </span>
      {{/each}}
    </script>
    

    This snippet contains several points of note:

    1. First, the each helper designates that it uses a view property (as opposed to a property on the controller) by prefixing the property name with view.
    2. Second, the class attribute of the span tag has mixed dynamic and static classes assigned. Anything prefixed by a : becomes a static class, while the full:glyphicon-star:glyphicon-star-empty notation is like a ternary operator in JavaScript: if the full property is truthy, the first class should be assigned; if not, the second.
    3. Finally, when the tag is clicked, the setRating action should be fired—but Ember will look it up on the view, not the route or controller, as in the case of creating a new artist.

    The action is thus defined on the view:

    App.StarRating = Ember.View.extend({
      (...)
      actions: {
        setRating: function() {
          var newRating = $(event.target).data('rating');
          this.set('rating', newRating);
        }
      }
    });
    

    We get the rating from the rating data attribute we assigned in the template and then set that as the ratingfor the song. Note that the new rating is not persisted on the back-end. It would not be difficult to implement this functionality based on how we created an artist and is left as an exercise for the motivated reader.

    Wrapping it all up

    We have tasted several ingredients of the aforementioned Ember cake:

    • We have seen how routes are the crux of Ember applications and how they serve as the basis of naming conventions.
    • We have seen how two-way data bindings and computed properties make our model data the single source of truth and allow us to avoid direct DOM manipulation.
    • And we have seen how to fire and handle actions in several ways and build a custom view to create a control that is not part of our HTML.

    Beautiful, isn’t it?

  • 6 Essential Drupal Interview Questions

    6 Essential Drupal Interview Questions

    The five layers, starting from the bottom layer, are as follows:

    1. Data (nodes, etc.). Before anything can be displayed on the site, it must be input as data.
    2. Modules. Modules are functional plugins that are either part of the Drupal core or are contributed modules that build on Drupal’s core functionality.
    3. Blocks and menus. Blocks can be used to present anything, so just about any piece of content on a Drupal site (other than main content, breadcrumbs, and primary/secondary menus) is usually a block. Blocks are an extensible core feature of Drupal with a simple API provided by the block module. Blocks are similar to “widgets” in content management systems, but are highly generalized. Menus are a collection of links (menu items) used to navigate a website. The Menu module provides an interface to control and customize the menu system that comes with Drupal. By default, new menu items are placed inside a built-in menu labeled Navigation, but administrators can also create custom menus.
    4. User permissions. User permissions are defined for various roles and users are assigned to these roles in order to grant them the defined permissions.
    5. Themes and templates. The top conceptual layer of the drupal architecture is the theme. This consists primarily of XHTML and CSS, with some PHP variables intermixed, so Drupal-generated content can go in the appropriate spots. Also included with each theme is a set of functions that can be used to override standard functions in the modules in order to provide complete control over how the modules generate their markup at output time. A theme may contain one or more templates, depending on the complexity of the site and the way it has been designed.
    Drupal comes with a built in taxonomy system that allows for categorization of the nodes on a site.
    The taxonomy system allows for arbitrary definition of terms, as well as arbitrary organization of those terms into vocabularies. There is no limit to the number of vocabularies that can be created, nor is there any limit to the number of terms that can be included in a vocabulary.
    A vocabulary can also have free tagging which means that, instead of entering specific terms ahead of time, users may enter tags freely at the time the content is created and those tags automatically become terms in that vocabulary.
    Drupal’s taxonomy system is one if its most powerful and flexible features.
    The Field API allows custom data fields to be attached to Drupal entities and takes care of storing, loading, editing, and rendering field data. Any entity type (node, user, etc.) can use the Field API to make itself “fieldable” and thus allow fields to be attached to it. Other modules can provide a user interface for managing custom fields via a web browser as well as a wide and flexible variety of data type, form element, and display format capabilities.
    The Field API defines two primary data structures, Field and Instance, and the concept of a Bundle. A Field defines a particular type of data that can be attached to entities. A Field Instance is a Field attached to a single Bundle. A Bundle is a set of fields that are treated as a group by the Field Attach API and is related to a single fieldable entity type.
    For example, suppose a site administrator wants Article nodes to have a subtitle and photo. Using the Field API or Field UI module, the administrator creates a field named ‘subtitle’ of type ‘text’ and a field named ‘photo’ of type ‘image’. The administrator (again, via a UI) creates two Field Instances, one attaching the field ‘subtitle’ to the ‘node’ bundle ‘article’ and one attaching the field ‘photo’ to the ‘node’ bundle ‘article’. When the node system uses the Field Attach API to load all fields for an Article node, it passes the node’s entity type (which is ‘node’) and content type (which is ‘article’) as the node’s bundle. field_attach_load() then loads the ‘subtitle’ and ‘photo’ fields because they are both attached to the ‘node’ bundle ‘article’.
    Field definitions are represented as an array of key/value pairs.
    Note that the above answer has been excerpted from the Drupal API Documentation, where more information can be found.
    All content on a Drupal website is stored and treated as “nodes”. A node is any piece of individual content (e.g., a page, article, forum topic, blog entry, etc.). Note, though, that omments are not stored as nodes but are always connected to a node.
    The ability to create different “content types” is a way Drupal allows you to have different kinds of nodes for different purposes. For example, an “article” is one content type, a “book page” is another, and a “blog entry” yet another. You can also create new content types of your own.
    Treating all content as nodes provides a great deal of flexibility that facilitates and simplifies creating new types of content. It also makes it easy to apply new features or changes to all content of a particular type.
    Using the Views module, you can fetch content from the database of your site and present it to the user as lists, posts, galleries, tables, maps, graphs, menu items, blocks, reports, forum posts etc. Different content types including nodes, users, and other bundles can be displayed.
    Views UI, a submodule within Views, provides a graphical interface underneath which lies a powerful SQL query builder that can access virtually any information in your database and display it in any format.
    Different displays can present the query results as pages with fixed URLs on your site (or URLs accepting arguments), blocks, feeds, or panel panes.
    You can also use Views to present related content or implement contextual filters. For example, you can display a list of users along with links to the content they have created and/or you can display customized content to a user according to their user ID.
    More information is available in the Views documentation on the Drupal site.
    Rails is a general purpose web application framework for Ruby. It’s designed to help programmers be more productive in building web sites of all types, not just CMSs. And note that it’s for “programmers”. Unless you intend to write server-side code, you can’t hope to get much done with just Rails alone (but if you do intend to write code, both Ruby and Rails are known to be very productive).
    Drupal is a Content Management System, of which there are hundreds. It happens to be written in PHP, but it’s modular design and large collection of available modules and themes make it possible to design and implement a large variety of web sites without writing a line of code. Most importantly, though, it is fundamntally a CMS. The further your site’s needs are from the CMS sweet-spot, the less likely it is that Drupal will be your best choice.

    [pt_text]
    Source: https://www.toptal.com/
    [/pt_text][pt_alertblock alert_type=”alert-info” title=”Want to improve or add questions?” css_animation=”bounceIn”]
    If you feel to add more question feel free to add in comment section below we will update it in our blog.
    [/pt_alertblock][pt_testimonials_balloon name=”About this post” quote=”This is a shared post. Originally posted on “https://www.toptal.com/“. All rights reserved to their editors. I just shared this post on Original Author’s demand to share this post on my blog.” minheight=”100″ css_animation=”fadeIn”]