Blog

  • The Most Common Mistakes CakePHP Developers Make : A Tutorial for Beginners

    CakePHP is an amazing PHP framework, but it has a steep learning curve! It requires a good amount of research and training to become an expert.
    I have been fortunate to use CakePHP for over 7 years now, and in that time I’ve had the honor of working with many members of the CakePHP community.
    In this CakePHP tutorial I’d like to describe few bad practices which I have seen over the years, and propose the correct approach to avoid these mistakes. This isn’t to say my code is perfect, but as a programmer we are always learning, so it is important to follow the best practices and adjust as you learn!
    Content of this article is inspired by a post from CakeCoded. If you would like to learn more about CakePHP please visit our learning section here.
    This beginner CakePHP tutorial will help you avoid frying your CakePHP code with errors and mistakes!

    Common Mistake #1: Not Following CakePHP Coding Conventions

    CakePHP coding conventions can be viewed here. I will highlight a few things which I often notice when viewing other programmers’ code.
    Control structures. So often you see programmers get this wrong, and in some cases bring practices from other coding languages. CakePHP expects the following syntax:

    if ((expr_1) || (expr_2)) {
        // action_1;
    } elseif (!(expr_3) && (expr_4)) {
        // action_2;
    } else {
        // default_action;
    }
    

    There should be 1 (one) space before the first parenthesis and 1 (one) space between the last parenthesis and the opening bracket. So this means that the following is incorrect:

    if($this->request->data){
    }
    

    Note the spacing between the if and (, and between ) and {
    Always use curly brackets in control structures, even if they are not needed. They increase the readability of the code, and they give you fewer logical errors.
    So, for example, the following is incorrect:

    if ($foo)
        $bar = true
    

    This should be formatted like this:

    if ($foo) {
        $bar = true
    }
    

    Finally, watch where you place the brackets. Opening brackets shouldn’t start a new line. And make sure all your brackets line up so that each new bracket is in line with the closing bracket.
    Here are some incorrect examples:

    if ($foo)
    {
        $bar = true;
    }
    

    This is incorrect, the opening bracket should be in the first line:

    if ($foo) {
        $bar = true;
    if ($action) {
        $to = false;
    }
    }
    

    The indentation needs to line up correctly.
    I often hear programmers say, “But I am too busy to make the code neat….” My response is, “Trust me, neat code will stand the test of time”. Writing CakePHP code which isn’t readable will be a nightmare to come back to if you need to make a change in a few months.

    Common Mistake #2: Improper Use of Containable Behaviors and Recursive Levels in ORM

    I was fortunate recently to have an informal discussion with a database developer from Facebook. We started talking about CakePHP and he said to me, “Oh, that uses ORM doesn’t it? That can be scary.” I asked him what he meant, and he commented that with Object-relational mapping (ORM) it is easy for SQL queries to become unnecessarily large.
    He is right in a way. Part of CakePHP’s magic is in its use of ORM and the way that it groups different database table relations together. By default, CakePHP automatically selects any related ‘Belongs To’, ‘Has One’ and ‘Has Many’ data, and this can lead to very large SQL queries. These queries may not be a concern when you are initially developing an application, but after six months of collecting live data, you may find the application becomes very slow, and in some cases crashes if the queries aren’t optimized.
    I look out for two things when auditing an existing website. Firstly, has the default recursive level been changed? By default, CakePHP sets the recursive level to 1, which in my opinion is too high. I always set it to -1 and then use the containable behavior to get any related models.
    That leads to the second thing I look for – has the Containable behavior been used? I often have new clients come to me and say that CakePHP is slow. The reason is almost always because Containable hasn’t been used! A good CakePHP programmer will optimize their SQL queries regardless of how much “auto-magic” is done behind the scenes.
    The containable behavior wasn’t added until CakePHP 1.2, but boy has it made a difference?! Be sure to use containable as much as possible, as it is such an effective way to optimize your SQL. For more information on how to implement and use the Containable behavior, click here.

    Common Mistake #3: Keeping Business Logic in Controllers Instead of Models

    Good CakePHP code will have the logic in the model files. This takes a bit to get used to, but once mastered there is no looking back! A controller file should be used for what it is intended for in the MVC pattern – controlling! So use your controller file to handle user actions, while letting the business logic go in the model file.
    A good example of this would be a simple CRUD – an everyday action! Let’s take the add posts function from a blog tutorial as an example. The default add function is as follows:

    public function add() {
        if ($this->request->is('post')) {
            $this->Post->create();
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash(__('Your post has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add your post.'));
        }
    }
    

    This controller action is fine for a simple add, but what would happen if you wanted to do things such as send an email to the admin when a post was added, or update another model association when a post was added. This is additional logic, but this logic shouldn’t go into our controller file.
    Instead we would write a function for this in our Post.php model. Perhaps something like this:

    public function addPost($data = array(), $emailAdmin = true) {
        $this->create();
        $this->save($data);
        // update any other tables
        // send the email to the admin user
        if ($emailAdmin) {
        }
        // if all is successful
        return true;
    }
    

    This would then result in a small change to the controller action as follows:

    public function add() {
        if ($this->request->is('post')) {
            if ($this->Post->addPost($this->request->data)) {
                $this->Session->setFlash(__('Your post has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to add your post.'));
        }
    }
    

    As you can see, the new action is actually one less line, because the $this->Post->create() has been moved to the model file.
    This is a perfect, everyday example of where moving logic to the model file is a good idea – and it certainly makes for a much cleaner code base!

    Common Mistake #4: Adding Too Much Complexity to the Code, Instead of Returning Often and Early

    This is always a bit of an ongoing debate, but returning often, and returning early certainly does make for much cleaner looking code. This applies to the model methods more than anything else.
    But what exactly do I mean? Well, let’s take a look at the method we added in the CakePHP tutorial above:

    public function addPost($data = array(), $emailAdmin = true) {
        $this->create();
        $this->save($data);
        // update any other tables
        // send the email to the admin user
        if ($emailAdmin) {
        }
        // if all is successful
        return true;
    }
    

    To return often, and return early means that as we run through our function, we check to make sure the everything is OK on a regular basis. If it isn’t, then we return false, or return a CakePHP error.
    It might be easiest to show this with an example. There are two ways the above function could be written:

    public function addPost($data = array(), $emailAdmin = true) {
        if ($data) {
            $this->create();
            $result = $this->save($data);
            if ($result) {
                // update any other tables
                // send the email to the admin user
                if ($emailAdmin) {
                    // send the admin email
                }
            } else {
                // problem saving the data
                return false;
            }
            // if all is successful
            return true;
        } else {
            // no data submitted
            return false;
        }
    }
    

    See how the code quickly becomes unreadable? There are ifs and elses all over the place, and the function quickly becomes one big indentation. Don’t get me wrong, I love clean indentation, but watch how the function looks if it written with the return often, return early principle.

    public function addPost($data = array(), $emailAdmin = true) {
        if (!$data) {
            // no data submitted
            return false;
        }
        $this->create();
        $result = $this->save($data);
        if (!$result) {
            // problem saving the data
            return false;
        }
        // update any other tables
        // send the email to the admin user
        if ($emailAdmin) {
            // send the admin email
        }
        // if all is successful
        return true;
    }
    

    Straight away, in this small example, you can see the code only has a single indentation and is much more readable. The logic actually makes more sense – let the logic run through line by line, and if there is any issue along the way, return the error and don’t proceed to the next line.
    This allows a CakePHP programmer to write the same way that we read – reading code from left to right, top to bottom, rather than in different blocks, which can quickly get confusing!

    Common Mistake #5: Not Using the DRY Principle

    DRY stands for Don’t Repeat Yourself, and it is a philosophy which should be followed when coding in CakePHP. With object-oriented code, there is no excuse for repeating the same block of code twice!
    Here are few CakePHP tips to ensure you don’t repeat yourself:

    • As mentioned above, aim to put logic in model files so you can share the logic.
    • In your view files, if you are repeating views, create the view code as an Element, or even a custom helper.
    • Set up some configuration settings – the app/Config/bootstrap.php file is a great place for this. This helps make sure you aren’t hard coding things like the application name and the main email address. The last thing you want to do is go through hundreds of files just because the client has asked to update an email address in an application.
    • Always ask yourself, “If I am repeating code, is there a better way to write this code, and am I putting this code in the right place?” Chances are, if you need to repeat code, it could be written better.

    Common Mistake #6: Not Commenting the Code

    The last point I will make is in regards to comments. Firstly, doc blocking. A doc block is when you document a method or an action. It takes only a minute to record a little about what a function is doing, but it makes such a difference in terms of readability of code.
    CakePHP Doc Blocks need to go against the left margin of the page. So a simple example using the code from above.

    /**
     * Adds & saves a post as well as emails the admin to let them know the post has been added.
     * Also performs some saving to another table
     *
     * @param   array $data The post data
     * @param   bool $emailAdmin If set to true, will email the website admin
     * @return  bool Returns true if successful
     */
    public function addPost($data = array(), $emailAdmin = true) {
    

    As you will see, it doesn’t take long to write a doc block, but it makes a huge difference in terms of longevity of the code. Ultimately, it means the code can live on past you as the developer.
    Likewise with in-line comments. Don’t be scared to explain what your code is doing and why! It makes it a lot easier in the long run to understand your code, especially if another developer is looking at it!

    Wrap-up

    CakePHP is an extensive, full-featured framework. Given it follows convention over configuration, CakePHP is more strict than other PHP based frameworks, in the sense that a user is “forced” to follow a certain way of laying out the code. This can be controversial, but in my experience it leads to a code base which is more consistent, readable and understandable – rather than letting a developer “choose” how the code should be written, a development team will write consistent code by following Cake’s conventions.
    By following this CakePHP tutorial and ensuring your code is well written, applications can stand the test of time. Code should always be written for tomorrow – so that if another developer is looking at a particular code block years later, he will understand the code, and stick to the expected standards. CakePHP is no different and hopefully this guide will help correct some bad habits.

  • How to Find Great Software Developers (or be Found)

    How to Find Great Software Developers (or be Found)

    Whether you’re a software developer who wants to ace an interview or a technical recruiter looking for ways to locate and screen the best technical talent for your project, Toptal has created a comprehensive suite of hiring resources designed to make the interview and recruitment process efficient and successful.
    Software Developers Resources
    One of the most recent resources is the The Software Engineer’s Online Handbook which contains great tips and resources for engineers of all experience levels will find great tools for collaboration, open source projects, and free tutorials. Stay a step ahead with emerging industry trends and hiring forecasts, as well as the latest tools and technologies vetted by the elite Toptal team.

     

  • Data Encoding: A Guide to UTF-8 for PHP and MySQL

    As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8.

    A Quick UTF-8 Primer

    Unicode is a widely-used computing industry standard that defines a comprehensive mapping of unique numeric code values to the characters in most of today’s written character sets to aid with system interoperability and data interchange.
    UTF-8 is a variable-width encoding that can represent every character in the Unicode character set. It was designed for backward compatibility with ASCII and to avoid the complications of endianness and byte order marks in UTF-16 and UTF-32. UTF-8 has become the dominant character encoding for the World Wide Web, accounting for more than half of all Web pages.
    UTF-8 encodes each character using one to four bytes. The first 128 characters of Unicode correspond one-to-one with ASCII, making valid ASCII text also valid UTF-8-encoded text. It is for this reason that systems that are limited to use of the English character set are insulated from the complexities that can otherwise arise with UTF-8.
    For example, the Unicode hexidecimal code for the letter A is U+0041, which in UTF-8 is simply encoded with the single byte 41. In comparison, the Unicode hexidecimal code for the character  is U+233B4, which in UTF-8 is encoded with the four bytes F0 A3 8E B4.

    On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not.
    This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and so on. Soon, we ended up with a list of 600,000 artist bios with double- or triple-encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.
    Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pulling experience. This post provides a concise cookbook for addressing these issues when working with PHP and MySQL in particular, based on practical experience and lessons learned (and with thanks, in part, to information discovered here and here along the way).
    Data encoding with UTF-8 unicode for PHP and MySQL makes complex languages simple.
    Specifically, we’ll cover the following in this post:

    • Mods you’ll need to make to your php.ini file and PHP code.
    • Mods you’ll need to make to your my.ini file and other MySQL-related issues to be aware of (including config mods needed if you’re using Sphinx)
    • How to migrate data from a MySQL database previously encoded in latin1 to instead use a UTF-8 encoding

    PHP & UTF-8 Encoding – modifications to your php.ini file:

    The first thing you need to do is to modify your php.ini file to use UTF-8 as the default character set:

    	default_charset = "utf-8";
    

    (Note: You can subsequently use phpinfo() to verify that this has been set properly.)
    OK cool, so now PHP and UTF-8 should work just fine together. Right?
    Well, not exactly. In fact, not even close.
    While this change will ensure that PHP always outputs UTF-8 as the character encoding (in browser response Content-type headers), you still need to make a number of modifications to your PHP code to make sure that it properly processes and generates UTF-8 characters.

    PHP & UTF-8 Encoding – modifications to your code:

    To be sure that your PHP code plays well in the UTF-8 data encoding sandbox, here are the things you need to do:

    • Set UTF-8 as the character set for all headers output by your PHP codeIn every PHP output header, specify UTF-8 as the encoding:
        header('Content-Type: text/html; charset=utf-8');
      
    • Specify UTF-8 as the encoding type for XML
        <?xml version="1.0" encoding="UTF-8"?>
      
    • Strip out unsupported characters from XMLSince not all UTF-8 characters are accepted in an XML document, you’ll need to strip any such characters out from any XML that you generate. A useful function for doing this (which I found here) is the following:
        function utf8_for_xml($string)
        {
          return preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u',
                              ' ', $string);
        }
      

      Here’s how you can use this function in your code:

        $safeString = utf8_for_xml($yourUnsafeString);
      
    • Specify UTF-8 as the character set for all HTML contentFor HTML content, specify UTF-8 as the encoding:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      

      In HTML forms, specify UTF-8 as the encoding:

        <form accept-charset="utf-8">
      
    • Specify UTF-8 as the encoding in all calls to htmlspecialcharse.g.:
        htmlspecialchars($str, ENT_NOQUOTES, "UTF-8")
      

      Note: As of PHP 5.6.0, default_charset value is used as the default. From PHP 5.4.0, UTF-8 was the default, but prior to PHP 5.4.0, ISO-8859-1 was used as the default. It’s therefore a good idea to always explicitly specify UTF-8 to be safe, even though this argument is technically optional.
      Also note that, for UTF-8, htmlspecialchars and htmlentities can be used interchangeably.

    • Set UTF-8 as the default character set for all MySQL connectionsSpecify UTF-8 as the default character set to use when exchanging data with the MySQL database using mysql_set_charset:
        $link = mysql_connect('localhost', 'user', 'password');
        mysql_set_charset('utf8', $link);
      

      Note that, as of PHP 5.5.0, mysql_set_charset is deprecated, and mysqli::set_charset should be used instead:

        $mysqli = new mysqli("localhost", "my_user", "my_password", "test");
        /* check connection */
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
        /* change character set to utf8 */
        if (!$mysqli->set_charset("utf8")) {
            printf("Error loading character set utf8: %s\n", $mysqli->error);
        } else {
            printf("Current character set: %s\n", $mysqli->character_set_name());
        }
        $mysqli->close();
      
    • Always use UTF-8 compatible versions of string manipulation functionsThere are several PHP functions that will fail, or at least not behave as expected, if the character representation needs more than 1 byte (as UTF-8 does). An example is the strlen function that will return the number of bytes rather than the number of characters.
      Two options are available for dealing with this:

      • The iconv functions that are available by default with PHP provide multibyte compatible versions of many of these functions (e.g., iconv_strlen, etc.). Remember, though, that the strings you provide to these functions must themselves be properly encoded.
      • There is also the mbstring extension to PHP (information on enabling and configuring it is available here). This extension provides a comprehensive set of functions that properly account for multibyte encoding.

    MySQL & UTF-8 Encoding – modifications to your my.ini file:

    On the MySQL/UTF-8 side of things, modifications to the my.ini file are required as follows:

    • Set the following config parameters after each corresponding tag:
        [client]
        default-character-set=UTF-8
        [mysql]
        default-character-set=UTF-8
        [mysqld]
        character-set-client-handshake = false #force encoding to uft8
        character-set-server=UTF-8
        collation-server=UTF-8_general_ci
        [mysqld_safe]
        default-character-set=UTF-8
      
    • After making the above changes to your my.ini file, restart your MySQL daemon.
    • To verify that everything has properly been set to use the UTF-8 encoding, execute the following query:
        mysql> show variables like 'char%';
      

      The output should look something like:

            | character_set_client        | UTF-8
            | character_set_connection    | UTF-8
            | character_set_database      | UTF-8
            | character_set_filesystem    | binary
            | character_set_results       | UTF-8
            | character_set_server        | UTF-8
            | character_set_system        | UTF-8
            | character_sets_dir          | /usr/share/mysql/charsets/
      

      If you instead see latin1 listed for any of these, double-check your configuration and make sure you’ve properly restarted your mysql daemon.

    MySQL & UTF-8 Encoding – other things to consider:

    • MySQL UTF-8 is actually a partial implementation of the full UTF-8 character set. Specifically, MySQL UTF-8 data encoding uses a maximum of 3 bytes, whereas 4 bytes are required for encoding the full UTF-8 character set. This is fine for all language characters, but if you need to support astral symbols (whose code points range from U+010000 to U+10FFFF), those require a four byte encoding which is not supported in MySQL UTF-8.  In MySQL 5.5.3, this was addressed with the addition of support for the utf8mb4 character set which uses a maximum of four bytes per character and thereby supports the full UTF-8 character set. So if you’re using MySQL 5.5.3 or later, use utf8mb4 instead of UTF-8 as your database/table/row character set. More info is available here.
    • If the connecting client has no way to specify the encoding for its communication with MySQL, after the connection is established you may have to run the following command/query:
        set names UTF-8;
      
    • When determining the size of varchar fields when modeling the database, don’t forget that UTF-8 characters may require as many as 4 bytes per character.

    MySQL & UTF-8 Encoding – if you use Sphinx:

    • In your Sphinx configuration file (i.e., sphinx.conf):
      • Set your index definition to have:
        charset_type = utf-8
        
      • Add the following to your source definition:
        sql_query_pre = SET CHARACTER_SET_RESULTS=UTF-8
        sql_query_pre = SET NAMES UTF-8
        
    • Restart the engine and remake all indices.
    • If you want to configure sphinx so that letters like C c Ć ć Ĉ ĉ Ċ ċ Č č are all treated as equivalent for search purposes, you will need to configure a charset_table (a.k.a. character folding) which is essentially an equivalency mapping between characters. More information is available here.

    MySQL – Migrating a database data that is already encoded in latin1 to UTF-8

    If you have an existing MySQL database that is already encoded in latin1, here’s how to convert the latin1 to UTF-8:

    1. Make sure you’ve made all the modifications to the configuration settings in your my.ini file, as described above.
    2. Execute the following command:
       ALTER SCHEMA `your-db-name` DEFAULT CHARACTER SET UTF-8;
      
    3. Via command line, verify that everything is properly set to UTF-8
       mysql> show variables like 'char%';
      
    4. Create a dump file with latin1 encoding for the table you want to convert:
       mysqldump -u USERNAME -pDB_PASSWORD --opt --skip-set-charset --default-character-set=latin1
                 --skip-extended-insert DATABASENAME --tables TABLENAME >
                 DUMP_FILE_TABLE.sql
      

      e.g:

       mysqldump -u root --opt --skip-set-charset  --default-character-set=latin1
                 --skip-extended-insert artists-database --tables tbl_artist >
                 tbl_artist.sql
      
    5. Do a global search and replace of the charset in the dumpfile from latin1 to UTF-8:e.g., using Perl:
       perl -i -pe 's/DEFAULT CHARSET=latin1/DEFAULT CHARSET=UTF-8/' DUMP_FILE_TABLE.sql
      

      Note to Windows users: This charset string replacement (from latin1 to UTF-8) can also be done using find-and-replace in WordPad (or some other text editor, such as vim). Be sure to save the file just as it is though (don’t save it as unicode txt file!).

    6. From this point, we will start messing with the database data, so it would probably be prudent to backup the database if you haven’t already done so. Then, restore the dump into the database:
       mysql> source "DUMP_FILE_TABLE.sql";
      
    7. Search for any records that may not have converted properly and correct them. Since non-ASCII characters are multi-byte by design, we can find them by comparing the byte length to the character length (i.e., to identify rows that may hold double-encoded UTF-8 characters that need to be fixed).
      • See if there are any records with multi-byte characters (if this query returns zero, then there don’t appear to be any records with multi-byte characters in your table and you can proceed to Step 8).
          mysql> select count(*) from MY_TABLE where LENGTH(MY_FIELD) != CHAR_LENGTH(MY_FIELD);
        
      • Copy rows with multi-byte characters into a temporary table:
          create table temptable (
              select * from MY_TABLE where
              LENGTH(MY_FIELD) != CHAR_LENGTH(MY_FIELD));
        
      • Convert double-encoded UTF-8 characters to proper UTF-8 charactersThis is actually a bit tricky. A double encoded string is one that was properly encoded as UTF-8. However, MySQL then did us the erroneous favor of converting it (from what it thought was latin1) to UTF-8 again, when we set the column to UTF-8 encoding. Resolving this therefore requires a two step process through which we “trick” MySQL in order to preclude it from doing us this “favor”.
        First, we set the encoding type for the column back to latin1, thereby removing the double encoding:
        e.g.:

          alter table temptable modify temptable.ArtistName varchar(128) character set latin1;
        

        Note: Be sure to use the correct field type for your table. In the example above, for our table, the correct field type for ‘ArtistName’ was varchar(128), but the field in your table could be text or any other type. Be sure to specify it properly!
        The problem is that now, if we set the column encoding back to UTF-8, MySQL will run the latin1 to UTF-8 data encoding for us again and we’ll be back to where we started. To avoid this, we change the column type to blob and THEN we set it to UTF-8. This exploits the fact that MySQL will not attempt to encode a blob. We are thereby able to “fool” the MySQL charset conversion to avoid the double encoding issue.
        e.g.:

          alter table temptable modify temptable.ArtistName blob;
          alter table temptable modify temptable.ArtistName varchar(128) character set UTF-8;
        

        (Again, as noted above, be sure to use the proper field type for your table.)

      • Remove rows with only single-byte characters from the temporary table:
          delete from MY_TABLE where LENGTH(MY_FIELD) = CHAR_LENGTH(MY_FIELD);
        
      • Re-insert fixed rows back into the original table (before doing this, you may want to run some selects on the temptable to verify that it appears to be properly corrected, just as a sanity check).
          replace into MY_TABLE (select * from temptable);
        
    8. Verify the remaining data and, if necessary, repeat the process in step 7 (this could be necessary, for example, if the data was triple encoded). Further errors, if any, may be easiest to resolve manually.

    Source code and resource files

    One other thing to remember and verify is that your source code files, resources files, and so on, are all being saved properly with UTF-8 data encoding. Otherwise, any “special” characters in these files may not be handled correctly.
    In Netbeans, for example, you can right-click on your project, choose properties and then in “Sources” you will find the data encoding option (it usually defaults to UTF-8, but it’s worth checking).
    Or in Windows Notepad, use the “Save As…” option in the File menu, and select the UTF-8 encoding option at the bottom of the dialog. (Note that the “Unicode” option that Notepad provides is actually UTF-16, so that’s not what you want.)

    Wrap-up

    Although it can be somewhat tedious, taking the time to go through these steps to systematically address your MySQL and PHP UTF-8 data encoding issues can ultimately save you a great deal of time and grief. In the long run, this type of methodical approach is far superior to the all-too-common tendency to just keep patching the system.
    This guide hopefully emphasizes the importance of taking the charset definition into consideration when setting up a project environment in the first place and working in a software project environment that properly accounts for character encoding in its manipulation of text and strings.

  • Building REST API for Legacy PHP Projects

    Building or architecting a REST API is not an easy task, especially when you have to do it for legacy PHP projects. There are a lot of 3rd party libraries nowadays that make it easy to implement a REST API, but integrating them into existing legacy codebases can be rather daunting. And, you don’t always have the luxury to work with modern frameworks, such as Laravel and Symfony. With legacy PHP projects, you can often find yourself somewhere in the middle of deprecated in-house frameworks, running on top of old versions of PHP.
    Building REST API for Legacy PHP Projects

    Building REST API for Legacy PHP Projects

    In this article, we will take a look at some common challenges of trying to implement REST APIs from scratch, a few ways to work around those issues and an overall strategy for building custom PHP based API servers for legacy projects.
    Although the article is based on PHP 5.3 and above, the core concepts are valid for all versions of PHP beyond version 5.0, and can even be applied to non-PHP projects. Here, we will not cover what a REST API is in general, so if you’re not familiar with it be sure to read about it first.
    To make it easy for you to follow along, here is a list of some terms used throughout this article and and their meanings:

    • API server: main REST application serving the API, in this case, written in PHP.
    • API endpoint: a backend “method” which the client communicates with to perform an action and produce results.
    • API endpoint URL: URL through which the backend system is accessible to the world.
    • API token: a unique identifier passed via HTTP headers or cookies from which the user can be identified.
    • App: client application which will communicate with the REST application via API endpoints. In this article we will assume that it is web based (either desktop or mobile), and so it is written in JavaScript.

    Initial Steps

    Path Patterns

    One of the very first things that we need to decide is at what URL path the API endpoints will be available. There are 2 popular ways:

    • Create a new subdomain, such as api.example.com.
    • Create a path, such as example.com/api.

    At a glance, it may seem that the first variant is more popular and attractive. In reality, however, if you’re building a project-specific API, it could be more appropriate to choose the second variant.
    One of the most important reasons behind taking the second approach is that this allows cookies to be used as a means to transfer credentials. Browser based clients will automatically send appropriate cookies within XHR requests, eliminating the need of an additional authorization header.
    Another important reason is that you don’t need to do anything regarding subdomain configuration or management problems where custom headers may be stripped by some proxy servers. This can be a tedious ordeal in legacy projects.
    Using cookies can be considered an “unRESTful” practice as REST requests should be stateless. In this case we can make a compromise and pass the token value in a cookie instead of passing it via a custom header. Effectively we are using cookies as just a way to pass the token value instead of the session_id directly. This approach could be considered stateless, but we can leave it up to your preferences.
    API endpoint URLs can also be versioned. Additionally, they can include the expected response format as an extension in the path name. Although these are not critical, especially during the early stages of API development, in the long run these details can certainly pay off. Especially when you need to implement new features. By checking which version the client is expecting and providing the needed format for backwards compatibility can be the best solution.
    The API endpoint URL structure could look as follows:

    example.com/api/${version_code}/${actual_request_path}.${format}
    

    And, a real example:

    example.com/api/v1.0/records.json
    

    Routing

    After choosing a base URL for the API endpoints, the next thing we need to do is to think about our routing system. It could be integrated into an existing framework, but if that is too cumbersome, a potential workaround is to create a folder named “api” in the document root. That way the API can have completely separate logic. You can extend this approach by placing the API logic into its own files, such as this:

    You can think of “www/api/Apis/Users.php” as a separate “controller” for a particular API endpoint. It would be great to reuse implementations from the existing codebase, for example reuse models that are already implemented in the project to communicate with the database.
    Finally, make sure to point all incoming requests from “/api/*” to “/api/index.php”. This can be done by changing your web server configuration.

    API Class

    Version and Format

    You should always clearly define what versions and formats your API endpoints accept and what are the default ones. This will allow you to build new features in the future while maintaining old functionalities. API version can basically be a string but you can use numeric values for better understanding and comparability. It is good to have spare digits for minor versions because it would clearly indicate that only few things are different:

    • v1.0 would mean first version.
    • v1.1 first version with some minor changes.
    • v2.0 would be a completely new version.

    Format can be anything your client needs including but not limited to JSON, XML, and even CSV. By providing it via URL as a file extension, the API endpoint url ensures readability and it becomes a no-brainer for the API consumer to know what format they can expect:

    • “/api/v1.0/records.json” would return JSON array of records
    • “/api/v1.0/records.xml” would return XML file of records

    It’s worth pointing out that you will also need to send proper a Content-Type header in the response for each of these formats.
    Upon receiving an incoming request, one of the first things you should do is check whether the API server supports the requested version and format. In your main method, which handles the incoming request, parse $_SERVER[‘PATH_INFO’] or $_SERVER[‘REQUEST_URI’] to determine if the requested format and version are supported. Then, either continue or return a 4xx response (e.g. 406 “Not Acceptable”). The most critical part in here is to always return something that the client expects. An alternative to this would be to check request header “Accept” instead of the URL path extension.

    Allowed Routes

    You could forward everything transparently to your API controllers but it might be better to use a whitelisted set of allowed routes. This would reduce flexibility a bit but will provide very clear insight of what the API endpoint URLs look like the next time you return to the code.

    private $public_routes = array(
    	'system' => array(
    		'regex' => 'system',
    	),
    	'records' => array(
    		'regex' => 'records(?:/?([0-9]+)?)',
    	),
    );
    

    You could also move these to separate files to make things cleaner. The configuration above will be used to enable requests to these URLs:

    /api/v1.0/system.json
    /api/v1.0/records.json
    /api/v1.0/records/7.json
    

    Handling PUT Data

    PHP automatically handles incoming POST data and places it under $_POST superglobal. However, that is not the case with PUT requests. All the data is “buried” into php://input. Do not forget to parse it into a separate structure or array before invoking the actual API method. A simple parse_str could be enough, but if the client is sending multipart request additional parsing may be needed to handle form boundaries. Typical use case of multipart requests include file uploads. Detecting and handling multipart requests can be done as follows:

    self::$input = file_get_contents('php://input');
    // For PUT/DELETE there is input data instead of request variables
    if (!empty(self::$input)) {
    	preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);
    	if (isset($matches[1]) && strpos(self::$input, $matches[1]) !== false) {
    		$this->parse_raw_request(self::$input, self::$input_data);
    	} else {
    		parse_str(self::$input, self::$input_data);
    	}
    }
    

    Here, parse_raw_request could be implemented as:

    /**
     * Helper method to parse raw requests
     */
    private function parse_raw_request($input, &$a_data)
    {
    	// grab multipart boundary from content type header
    	preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);
    	$boundary = $matches[1];
    	// split content by boundary and get rid of last -- element
    	$a_blocks = preg_split("/-+$boundary/", $input);
    	array_pop($a_blocks);
    	// loop data blocks
    	foreach ($a_blocks as $id => $block) {
    		if (empty($block)) {
    			continue;
    		}
    		// parse uploaded files
    		if (strpos($block, 'application/octet-stream') !== false) {
    			// match "name", then everything after "stream" (optional) except for prepending newlines
    			preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches);
    			// parse all other fields
    		} else {
    			// match "name" and optional value in between newline sequences
    			preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
    		}
    		$a_data[$matches[1]] = $matches[2];
    	}
    }
    

    With this, we can have the necessary request payload at Api::$input as raw input and Api::$input_data as an associative array.

    Faking PUT/DELETE

    Sometimes you can see yourself in a situation where the server does not support anything besides standard GET/POST HTTP methods. A common solution to this problem is to “fake” PUT/DELETE or any other custom request method. For that you can use a “magic” parameter, such as “_method”. If you see it in your $_REQUEST array, simply assume that the request is of specified type. Modern frameworks like Laravel have such functionality built into them. It provides great compatibility in case your server or client has limitations (for example a person is using his job’s Wi-Fi network behind corporate proxy that does not allow PUT requests.)

    Forwarding to Specific API

    If you don’t have the luxury of reusing existing project autoloaders, you can create your own with the help of spl_autoload_register function. Define it in your “api/index.php” page and call your API class located in “api/Api.php”. The API class acts as a middleware and calls the actual method. For example, a request to “/api/v1.0/records/7.json” should end up invoking “Apis/Records.php” GET method with parameter 7. This would ensure separation of concerns and provide a way to keep the logic cleaner. Of course, if it is possible to integrate this deeper into the framework you are using and reuse its specific controllers or routes you should consider that possibility too.
    Example “api/index.php” with primitive autoloader:

    <?php
    // Let's define very primitive autoloader
    spl_autoload_register(function($classname){
        $classname = str_replace('Api_', 'Apis/', $classname);
        if (file_exists(__DIR__.'/'.$classname.'.php')) {
            require __DIR__.'/'.$classname.'.php';
        }
    });
    // Our main method to handle request
    Api::serve();
    

    This will load our Api class and start serving it independently of the main project.

    OPTIONS Requests

    When a client uses custom header to forward its unique token, the browser first needs to check whenever the server supports that header. That’s where OPTIONS request come in. Its purpose is to ensure that everything is alright and safe for both the client and API server. So OPTIONS request could be firing every time a client tries to do anything. However, when a client is using cookies for credentials it saves the browser from having to send this additional OPTIONS request.

    If a client is requesting for POST /users/8.json with cookies, its request will be pretty standard:

    • App performs a POST request to /users/8.json.
    • The browser carries out the request and receives a response.

    But with custom authorization or token header:

    • App performs a POST request to /users/8.json.
    • The browser stops processing the request and initiates an OPTIONS request instead.
    • OPTIONS request is sent to /users/8.json.
    • The browser receives response with a list of all available methods and headers, as defined by the API.
    • Browser continues with the original POST request only if the custom header is present in the list of available headers.

    However, keep in mind that even when using cookies, with PUT/DELETE you might still receive that additional OPTIONS request. So be prepared to respond to it.

    Records API

    Basic Structure

    Our example Records API is pretty straightforward. It will contain all the request methods and return output back to the same main API class. For example:

    <?php
    class Api_Records
    {
    	public function __construct()
    	{
    		// In here you could initialize some shared logic between this API and rest of the project
    	}
    	/**
    	 * Get individual record or records list
    	 */
    	public function get($id = null)
    	{
    		if ($id) {
    			return $this->getRecord(intval($id));
    		} else {
    			return $this->getRecords();
    		}
    	}
    	/**
    	 * Update record
    	 */
    	public function put($record_id = null)
    	{
    		// In real world there would be call to model with validation and probably token checking
    		// Use Api::$input_data to update
    		return Api::responseOk('OK', array());
    	}
    	// ...
    

    So defining each HTTP method will allow us to build API in REST style more easily.

    Formatting Output

    Naively responding with everything received from the database back to the client can have catastrophic consequences. In order to avoid any accidental exposure of data, create specific format method which would return only whitelisted keys.
    Another benefit of whitelisted keys is that you can write documentation based on these and do all type-checkings ensuring, for example, that user_id will always be an integer, flag is_banned will always be boolean true or false, and date times will have one standard response format.

    Outputting Results

    Headers

    Separate methods for headers output will ensure that everything sent to the browser is correct. This method can use the benefits of making the API accessible via same domain while still maintaining possibility to receive custom authorization header. The choice between the same or 3rd party domain can happen with the help of HTTP_ORIGIN and HTTP_REFERER server headers. If the app is detecting that client is using x-authorization (or any other custom header) it should allow access from all origins, allow the custom header. So it could look like this:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Expose-Headers: x-authorization');
    header('Access-Control-Allow-Headers: origin, content-type, accept, x-authorization');
    header('X-Authorization: '.YOUR_TOKEN_HERE);
    

    However if the client is using cookie-based credentials, headers could be a bit different, allowing only requested host and cookie related headers for credentials:

    header('Access-Control-Allow-Origin: '.$origin);
    header('Access-Control-Expose-Headers: set-cookie, cookie');
    header('Access-Control-Allow-Headers: origin, content-type, accept, set-cookie, cookie');
    // Allow cookie credentials because we're on the same domain
    header('Access-Control-Allow-Credentials: true');
    if (strtolower($_SERVER['REQUEST_METHOD']) != 'options') {
    	setcookie(TOKEN_COOKIE_NAME, YOUR_TOKEN_HERE, time()+86400*30, '/', '.'.$_SERVER['HTTP_HOST']);
    }
    

    Keep in mind that OPTIONS request does not support cookies so app will not send them with it. And, finally this allows all our wanted HTTP methods to have expiration of access control:

    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
    header('Access-Control-Max-Age: 86400');
    

    Body

    The body itself should contain the response in a format requested by your client with a 2xx HTTP status upon success, 4xx status upon failure due to client and 5xx status upon failure due to server. Structure of the response can vary, although specifying “status” and “response” fields could be beneficial too. For example, if the client is trying to register a new user and the username is already taken it you could send a response with HTTP status 200 but a JSON in the body that looks something like:

    {“status”: “ERROR”, “response”: ”username already taken”}
    

    … instead of HTTP 4xx error directly.

    Conclusion

    No two projects are exactly the same. The strategy outlined in this article may or may not be be a good fit for your case, but the core concepts should be similar nonetheless. It’s worth noting that not every page can have the latest trending or up-to-date framework behind it, and sometimes the anger regarding “why my REST Symfony bundle doesn’t work here” can be turned into a motivation for building something useful, something that works. The end result may not be as shiny, as it will always be some custom and project-specific implementation, but at the end of the day the solution will be something that really works; and in a scenario like this that should be the goal of every API developer.
    Example implementations of the concepts discussed here has been uploaded to a GitHub repository for convenience. You may not want to use these sample codes directly in production as they are, but this could easily work as a starting point for your next legacy PHP API integration project.
    Had to implement a REST API server for some legacy project recently? Share your experience with us in the comment section below.

  • Before Debugging PHP That’s Not Working, Consult This List of the 10 Most Common Mistakes That PHP Developers Make

    PHP makes it relatively easy to build a web-based system, which is much of the reason for its popularity. But its ease of use notwithstanding, PHP has evolved into quite a sophisticated language with many frameworks, nuances, and subtleties that can bite developers, leading to hours of hair-pulling debugging. This article highlights ten of the more common mistakes that PHP developers need to beware of.
    This PHP logo broke thanks to one of the 10 most common PHP mistakes

    Common Mistake #1: Leaving dangling array references after foreach loops

    Not sure how to use foreach loops in PHP? Using references in foreach loops can be useful if you want to operate on each element in the array that you are iterating over. For example:

    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    // $arr is now array(2, 4, 6, 8)
    

    The problem is that, if you’re not careful, this can also have some undesirable side effects and consequences. Specifically, in the above example, after the code is executed, $value will remain in scope and will hold a reference to the last element in the array. Subsequent operations involving $value could therefore unintentionally end up modifying the last element in the array.
    The main thing to remember is that foreach does not create a scope. Thus, $value in the above example is a reference within the top scope of the script. On each iteration foreach sets the reference to point to the next element of $array. After the loop completes, therefore, $value still points to the last element of $array and remains in scope.
    Here’s an example of the kind of evasive and confusing bugs that this can lead to:

    $array = [1, 2, 3];
    echo implode(',', $array), "\n";
    foreach ($array as &$value) {}    // by reference
    echo implode(',', $array), "\n";
    foreach ($array as $value) {}     // by value (i.e., copy)
    echo implode(',', $array), "\n";
    

    The above code will output the following:

    1,2,3
    1,2,3
    1,2,2
    

    No, that’s not a typo. The last value on the last line is indeed a 2, not a 3.
    Why?
    After going through the first foreach loop, $array remains unchanged but, as explained above, $value is left as a dangling reference to the last element in $array (since that foreach loop accessed $value by reference).
    As a result, when we go through the second foreach loop, “weird stuff” appears to happen. Specifically, since $value is now being accessed by value (i.e., by copy), foreach copies each sequential $arrayelement into $value in each step of the loop. As a result, here’s what happens during each step of the second foreach loop:

    • Pass 1: Copies $array[0] (i.e., “1”) into $value (which is a reference to $array[2]), so $array[2] now equals 1. So $array now contains [1, 2, 1].
    • Pass 2: Copies $array[1] (i.e., “2”) into $value (which is a reference to $array[2]), so $array[2] now equals 2. So $array now contains [1, 2, 2].
    • Pass 3: Copies $array[2] (which now equals “2”) into $value (which is a reference to $array[2]), so $array[2] still equals 2. So $array now contains [1, 2, 2].

    To still get the benefit of using references in foreach loops without running the risk of these kinds of problems, call unset() on the variable, immediately after the foreach loop, to remove the reference; e.g.:

    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    unset($value);   // $value no longer references $arr[3]
    

    Common Mistake #2: Misunderstanding isset() behavior

    Despite its name, isset() not only returns false if an item does not exist, but also returns false for nullvalues.
    This behavior is more problematic than it might appear at first and is a common source of problems.
    Consider the following:

    $data = fetchRecordFromStorage($storage, $identifier);
    if (!isset($data['keyShouldBeSet']) {
        // do something here if 'keyShouldBeSet' is not set
    }
    

    The author of this code presumably wanted to check if keyShouldBeSet was set in $data. But, as discussed, isset($data['keyShouldBeSet']) will also return false if $data['keyShouldBeSet'] was set, but was set to null. So the above logic is flawed.
    Here’s another example:

    if ($_POST['active']) {
        $postData = extractSomething($_POST);
    }
    // ...
    if (!isset($postData)) {
        echo 'post not active';
    }
    

    The above code assumes that if $_POST['active'] returns true, then postData will necessarily be set, and therefore isset($postData) will return true. So conversely, the above code assumes that the only way that isset($postData) will return false is if $_POST['active'] returned false as well.
    Not.
    As explained, isset($postData) will also return false if $postData was set to null. It therefore is possible for isset($postData) to return false even if $_POST['active'] returned true. So again, the above logic is flawed.
    And by the way, as a side point, if the intent in the above code really was to again check if $_POST['active']returned true, relying on isset() for this was a poor coding decision in any case. Instead, it would have been better to just recheck $_POST['active']; i.e.:

    if ($_POST['active']) {
        $postData = extractSomething($_POST);
    }
    // ...
    if ($_POST['active']) {
        echo 'post not active';
    }
    

    For cases, though, where it is important to check if a variable was really set (i.e., to distinguish between a variable that wasn’t set and a variable that was set to null), the array_key_exists() method is a much more robust solution.
    For example, we could rewrite the first of the above two examples as follows:

    $data = fetchRecordFromStorage($storage, $identifier);
    if (! array_key_exists('keyShouldBeSet', $data)) {
        // do this if 'keyShouldBeSet' isn't set
    }
    

    Moreover, by combining array_key_exists() with get_defined_vars(), we can reliably check whether a variable within the current scope has been set or not:

    if (array_key_exists('varShouldBeSet', get_defined_vars())) {
        // variable $varShouldBeSet exists in current scope
    }
    

    Common Mistake #3: Confusion about returning by reference vs. by value

    Consider this code snippet:

    class Config
    {
        private $values = [];
        public function getValues() {
            return $this->values;
        }
    }
    $config = new Config();
    $config->getValues()['test'] = 'test';
    echo $config->getValues()['test'];
    

    If you run the above code, you’ll get the following:

    PHP Notice:  Undefined index: test in /path/to/my/script.php on line 21
    

    What’s wrong?
    The issue is that the above code confuses returning arrays by reference with returning arrays by value. Unless you explicitly tell PHP to return an array by reference (i.e., by using&), PHP will by default return the the array “by value”. This means that a copy of the array will be returned and therefore the called function and the caller will not be accessing the same instance of the array.
    So the above call to getValues() returns a copy of the $values array rather than a reference to it. With that in mind, let’s revisit the two key lines from the above the example:

    // getValues() returns a COPY of the $values array, so this adds a 'test' element
    // to a COPY of the $values array, but not to the $values array itself.
    $config->getValues()['test'] = 'test';
    // getValues() again returns ANOTHER COPY of the $values array, and THIS copy doesn't
    // contain a 'test' element (which is why we get the "undefined index" message).
    echo $config->getValues()['test'];
    

    One possible fix would be to save the first copy of the $values array returned by getValues() and then operate on that copy subsequently; e.g.:

    $vals = $config->getValues();
    $vals['test'] = 'test';
    echo $vals['test'];
    

    That code will work fine (i.e., it will output test without generating any “undefined index” message), but depending on what you’re trying to accomplish, this approach may or may not be adequate. In particular, the above code will not modify the original $values array. So if you do want your modifications (such as adding a ‘test’ element) to affect the original array, you would instead need to modify the getValues() function to return a reference to the $values array itself. This is done by adding a & before the function name, thereby indicating that it should return a reference; i.e.:

    class Config
    {
        private $values = [];
        // return a REFERENCE to the actual $values array
        public function &getValues() {
            return $this->values;
        }
    }
    $config = new Config();
    $config->getValues()['test'] = 'test';
    echo $config->getValues()['test'];
    

    The output of this will be test, as expected.
    But to make things more confusing, consider instead the following code snippet:

    class Config
    {
        private $values;
        // using ArrayObject rather than array
        public function __construct() {
            $this->values = new ArrayObject();
        }
        public function getValues() {
            return $this->values;
        }
    }
    $config = new Config();
    $config->getValues()['test'] = 'test';
    echo $config->getValues()['test'];
    

    If you guessed that this would result in the same “undefined index” error as our earlier array example, you were wrong. In fact, this code will work just fine. The reason is that, unlike arrays, PHP always passes objects by reference. (ArrayObject is an SPL object, which fully mimics arrays usage, but works as an object.)
    As these examples demonstrate, it is not always entirely obvious in PHP whether you are dealing with a copy or a reference. It is therefore essential to understand these default behaviors (i.e., variables and arrays are passed by value; objects are passed by reference) and also to carefully check the API documentation for the function you are calling to see if it is returning a value, a copy of an array, a reference to an array, or a reference to an object.
    All that said, it is important to note that the practice of returning a reference to an array or an ArrayObject is generally something that should be avoided, as it provides the caller with the ability to modify the instance’s private data. This “flies in the face” of encapsulation. Instead, it’s better to use old style “getters” and “setters”, e.g.:

    class Config
    {
        private $values = [];
        public function setValue($key, $value) {
            $this->values[$key] = $value;
        }
        public function getValue($key) {
            return $this->values[$key];
        }
    }
    $config = new Config();
    $config->setValue('testKey', 'testValue');
    echo $config->getValue('testKey');    // echos 'testValue'
    

    This approach gives the caller the ability to set or get any value in the array without providing public access to the otherwise-private $values array itself.

    Common Mistake #4: Performing queries in a loop

    It’s not uncommon to come across something like this if your PHP is not working:

    $models = [];
    foreach ($inputValues as $inputValue) {
        $models[] = $valueRepository->findByValue($inputValue);
    }
    

    While there may be absolutely nothing wrong here, but if you follow the logic in the code, you may find that the innocent looking call above to $valueRepository->findByValue() ultimately results in a query of some sort, such as:

    $result = $connection->query("SELECT `x`,`y` FROM `values` WHERE `value`=" . $inputValue);
    

    As a result, each iteration of the above loop would result in a separate query to the database. So if, for example, you supplied an array of 1,000 values to the loop, it would generate 1,000 separate queries to the resource! If such a script is called in multiple threads, it could potentially bring the system to a grinding halt.
    It’s therefore crucial to recognize when queries are being made by your code and, whenever possible, gather the values and then run one query to fetch all the results.
    One example of a fairly common place to encounter querying being done inefficiently (i.e., in a loop) is when a form is posted with a list of values (IDs, for example). Then, to retrieve the full record data for each of the IDs, the code will loop through the array and do a separate SQL query for each ID. This will often look something like this:

    $data = [];
    foreach ($ids as $id) {
        $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` = " . $id);
        $data[] = $result->fetch_row();
    }
    

    But the same thing can be accomplished much more efficiently in a single SQL query as follows:

    $data = [];
    if (count($ids)) {
        $result = $connection->query("SELECT `x`, `y` FROM `values` WHERE `id` IN (" . implode(',', $ids));
        while ($row = $result->fetch_row()) {
            $data[] = $row;
        }
    }
    

    It’s therefore crucial to recognize when queries are being made, either directly or indirectly, by your code. Whenever possible, gather the values and then run one query to fetch all the results. Yet caution must be exercised there as well, which leads us to our next common PHP mistake…

    Common Mistake #5: Memory usage headfakes and inefficiencies

    While fetching many records at once is definitely more efficient than running a single query for each row to fetch, such an approach can potentially lead to an “out of memory” condition in libmysqlclient when using PHP’s mysql extension.
    To demonstrate, let’s take a look at a test box with limited resources (512MB RAM), MySQL, and php-cli.
    We’ll bootstrap a database table like this:

    // connect to mysql
    $connection = new mysqli('localhost', 'username', 'password', 'database');
    // create table of 400 columns
    $query = 'CREATE TABLE `test`(`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT';
    for ($col = 0; $col < 400; $col++) {
        $query .= ", `col$col` CHAR(10) NOT NULL";
    }
    $query .= ');';
    $connection->query($query);
    // write 2 million rows
    for ($row = 0; $row < 2000000; $row++) {
        $query = "INSERT INTO `test` VALUES ($row";
        for ($col = 0; $col < 400; $col++) {
            $query .= ', ' . mt_rand(1000000000, 9999999999);
        }
        $query .= ')';
        $connection->query($query);
    }
    

    OK, now let’s check resources usage:

    // connect to mysql
    $connection = new mysqli('localhost', 'username', 'password', 'database');
    echo "Before: " . memory_get_peak_usage() . "\n";
    $res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 1');
    echo "Limit 1: " . memory_get_peak_usage() . "\n";
    $res = $connection->query('SELECT `x`,`y` FROM `test` LIMIT 10000');
    echo "Limit 10000: " . memory_get_peak_usage() . "\n";
    

    Output:

    Before: 224704
    Limit 1: 224704
    Limit 10000: 224704
    

    Cool. Looks like the query is safely managed internally in terms of resources.
    Just to be sure, though, let’s boost the limit one more time and set it to 100,000. Uh-oh. When we do that, we get:

    PHP Warning:  mysqli::query(): (HY000/2013):
                  Lost connection to MySQL server during query in /root/test.php on line 11
    

    What happened?
    The issue here is the way PHP’s mysql module works. It’s really just a proxy for libmysqlclient, which does the dirty work. When a portion of data is selected, it goes directly into memory.  Since this memory is not managed by PHP’s manager, memory_get_peak_usage() won’t show any increase in resources utilization as we up the limit in our query. This leads to problems like the one demonstrated above where we’re tricked into complacency thinking that our memory management is fine. But in reality, our memory management is seriously flawed and we can experience problems like the one shown above.
    You can at least avoid the above headfake (although it won’t itself improve your memory utilization) by instead using the mysqlnd module.  mysqlnd is compiled as a native PHP extension and it does use PHP’s memory manager.
    Therefore, if we run the above test using mysqlnd rather than mysql, we get a much more realistic picture of our memory utilization:

    Before: 232048
    Limit 1: 324952
    Limit 10000: 32572912
    

    And it’s even worse than that, by the way. According to PHP documentation, mysql uses twice as many resources as mysqlnd to store data, so the original script using mysql really used even more memory than shown here (roughly twice as much).
    To avoid such problems, consider limiting the size of your queries and using a loop with small number of iterations; e.g.:

    $totalNumberToFetch = 10000;
    $portionSize = 100;
    for ($i = 0; $i <= ceil($totalNumberToFetch / $portionSize); $i++) {
        $limitFrom = $portionSize * $i;
        $res = $connection->query(
                             "SELECT `x`,`y` FROM `test` LIMIT $limitFrom, $portionSize");
    }
    

    When we consider both this PHP mistake and mistake #4 above, we realize that there is a healthy balance that your code ideally needs to achieve between, on the one hand, having your queries being too granular and repetitive, vs. having each of your individual queries be too large. As is true with most things in life, balance is needed; either extreme is not good and can cause problems with PHP not working properly.

    Common Mistake #6: Ignoring Unicode/UTF-8 issues

    In some sense, this is really more of an issue in PHP itself than something you would run into while debugging PHP, but it has never been adequately addressed. PHP 6’s core was to be made Unicode-aware, but that was put on hold when development of PHP 6 was suspended back in 2010.
    But that by no means absolves the developer from properly handing UTF-8 and avoiding the erroneous assumption that all strings will necessarily be “plain old ASCII”. Code that fails to properly handle non-ASCII strings is notorious for introducing gnarly heisenbugs into your code. Even simple strlen($_POST['name'])calls could cause problems if someone with a last name like “Schrödinger” tried to sign up into your system.
    Here’s a small checklist to avoid such problems in your code:

    • If you don’t know much about Unicode and UTF-8, you should at least learn the basics. There’s a great primer here.
    • Be sure to always use the mb_* functions instead of the old string functions (make sure the “multibyte” extension is included in your PHP build).
    • Make sure your database and tables are set to use Unicode (many builds of MySQL still use latin1 by default).
    • Remember that json_encode() converts non-ASCII symbols (e.g., “Schrödinger” becomes “Schr\u00f6dinger”) but serialize() does not.
    • Make sure your PHP code files are also UTF-8 encoded to avoid collisions when concatenating strings with hardcoded or configured string constants.

    A particularly valuable resource in this regard is the UTF-8 Primer for PHP and MySQL post by Francisco Claria on this blog.

    Common Mistake #7: Assuming $_POST will always contain your POST data

    Despite its name, the $_POST array won’t always contain your POST data and can be easily found empty. To understand this, let’s take a look at an example. Assume we make a server request with a jQuery.ajax() call as follows:

    // js
    $.ajax({
        url: 'https://my.site/some/path',
        method: 'post',
        data: JSON.stringify({a: 'a', b: 'b'}),
        contentType: 'application/json'
    });
    

    (Incidentally, note the contentType: 'application/json' here. We send data as JSON, which is quite popular for APIs. It’s the default, for example, for posting in the AngularJS $http service.)
    On the server side of our example, we simply dump the $_POST array:

    // php
    var_dump($_POST);
    

    Surprisingly, the result will be:

    array(0) { }
    

    Why? What happened to our JSON string {a: 'a', b: 'b'}?
    The answer is that PHP only parses a POST payload automatically when it has a content type of application/x-www-form-urlencoded or multipart/form-data. The reasons for this are historical — these two content types were essentially the only ones used years ago when PHP’s $_POST was implemented. So with any other content type (even those that are quite popular today, like application/json), PHP doesn’t automatically load the POST payload.
    Since $_POST is a superglobal, if we override it once (preferably early in our script), the modified value (i.e., including the POST payload) will then be referenceable throughout our code. This is important since $_POSTis commonly used by PHP frameworks and almost all custom scripts to extract and transform request data.
    So, for example, when processing a POST payload with a content type of application/json, we need to manually parse the request contents (i.e., decode the JSON data) and override the $_POST variable, as follows:

    // php
    $_POST = json_decode(file_get_contents('php://input'), true);
    

    Then when we dump the $_POST array, we see that it correctly includes the POST payload; e.g.:

    array(2) { ["a"]=> string(1) "a" ["b"]=> string(1) "b" }
    

    Common Mistake #8: Thinking that PHP supports a character data type

    Look at this sample piece of code and try guessing what it will print:

    for ($c = 'a'; $c <= 'z'; $c++) {
        echo $c . "\n";
    }
    

    If you answered ‘a’ through ‘z’, you may be surprised to know that you were wrong.
    Yes, it will print ‘a’ through ‘z’, but then it will also print ‘aa’ through ‘yz’. Let’s see why.
    In PHP there’s no char datatype; only string is available. With that in mind, incrementing the string z in PHP yields aa:

    php> $c = 'z'; echo ++$c . "\n";
    aa
    

    Yet to further confuse matters, aa is lexicographically less than z:

    php> var_export((boolean)('aa' < 'z')) . "\n";
    true
    

    That’s why the sample code presented above prints the letters a through z, but then also prints aathrough yz. It stops when it reachs za, which is the first value it encounters that it “greater than” z:

    php> var_export((boolean)('za' < 'z')) . "\n";
    false
    

    That being the case, here’s one way to properly loop through the values ‘a’ through ‘z’ in PHP:

    for ($i = ord('a'); $i <= ord('z'); $i++) {
        echo chr($i) . "\n";
    }
    

    Or alternatively:

    $letters = range('a', 'z');
    for ($i = 0; $i < count($letters); $i++) {
        echo $letters[$i] . "\n";
    }
    

    Common Mistake #9: Ignoring coding standards

    Although ignoring coding standards doesn’t directly lead to needing to debug PHP code, it is still probably one of the most important things to discuss here.
    Ignoring coding standards can cause a whole slew of problems on a project. At best, it results in code that is inconsistent (since every developer is “doing their own thing”). But at worst, it produces PHP code that does not work or can be difficult (sometimes almost impossible) to navigate, making it extremely difficult to debug, enhance, maintain. And that means reduced productivity for your team, including lots of wasted (or at least unnecessary) effort.
    Fortunately for PHP developers, there is the PHP Standards Recommendation (PSR), comprised of the following five standards:

    • PSR-0: Autoloading Standard
    • PSR-1: Basic Coding Standard
    • PSR-2: Coding Style Guide
    • PSR-3: Logger Interface
    • PSR-4: Autoloader

    PSR was originally created based on inputs from maintainers of the most recognized platforms on the market. Zend, Drupal, Symfony, Joomla and others contributed to these standards, and are now following them. Even PEAR, which attempted to be a standard for years before that, participates in PSR now.
    In some sense, it almost doesn’t matter what your coding standard is, as long as you agree on a standard and stick to it, but following the PSR is generally a good idea unless you have some compelling reason on your project to do otherwise. More and more teams and projects are conforming with the PSR. Tt’s definitely recognized at this point as “the” standard by the majority of PHP developers, so using it will help ensure that new developers are familiar and comfortable with your coding standard when they join your team.

    Common Mistake #10: Misusing empty()

    Some PHP developers like using empty() for boolean checks for just about everything. There are case, though, where this can lead to confusion.
    First, let’s come back to arrays and ArrayObject instances (which mimic arrays). Given their similarity, it’s easy to assume that arrays and ArrayObject instances will behave identically. This proves, however, to be a dangerous assumption. For example, in PHP 5.0:

    // PHP 5.0 or later:
    $array = [];
    var_dump(empty($array));        // outputs bool(true) 
    $array = new ArrayObject();
    var_dump(empty($array));        // outputs bool(false)
    // why don't these both produce the same output?
    

    And to make matters even worse, the results would have been different prior to PHP 5.0:

    // Prior to PHP 5.0:
    $array = [];
    var_dump(empty($array));        // outputs bool(false) 
    $array = new ArrayObject();
    var_dump(empty($array));        // outputs bool(false)
    

    This approach is unfortunately quite popular. For example, this is the way Zend\Db\TableGateway of Zend Framework 2 returns data when calling current() on TableGateway::select() result as the doc suggests. Developer can easily become victim of this mistake with such data.
    To avoid these issues, the better approach to checking for empty array structures is to use count():

    // Note that this work in ALL versions of PHP (both pre and post 5.0):
    $array = [];
    var_dump(count($array));        // outputs int(0)
    $array = new ArrayObject();
    var_dump(count($array));        // outputs int(0)
    

    And incidentally, since PHP casts 0 to false, count() can also be used within if () conditions to check for empty arrays. It’s also worth noting that, in PHP, count() is constant complexity (O(1) operation) on arrays, which makes it even clearer that it’s the right choice.
    Another example when empty() can be dangerous is when combining it with the magic class function __get(). Let’s define two classes and have a test property in both.
    First let’s define a Regular class that includes test as a normal property:

    class Regular
    {
    	public $test = 'value';
    }
    

    Then let’s define a Magic class that uses the magic __get() operator to access its test property:

    class Magic
    {
    	private $values = ['test' => 'value'];
    	public function __get($key)
    	{
    		if (isset($this->values[$key])) {
    			return $this->values[$key];
    		}
    	}
    }
    

    OK, now let’s see what happens when we attempt to access the test property of each of these classes:

    $regular = new Regular();
    var_dump($regular->test);    // outputs string(4) "value"
    $magic = new Magic();
    var_dump($magic->test);      // outputs string(4) "value"
    

    Fine so far.
    But now let’s see what happens when we call empty() on each of these:

    var_dump(empty($regular->test));    // outputs bool(false)
    var_dump(empty($magic->test));      // outputs bool(true)
    

    Ugh. So if we rely on empty(), we can be misled into believing that the test property of $magic is empty, whereas in reality it is set to 'value'.
    Unfortunately, if a class uses the magic __get() function to retrieve a property’s value, there’s no foolproof way to check if that property value is empty or not. Outside of the class’ scope, you can really only check if a null value will be returned, and that doesn’t necessarily mean that the corresponding key is not set, since it actually could have been set to null.
    In contrast, if we attempt to reference a non-existent property of a Regular class instance, we will get a notice similar to the following:

    Notice: Undefined property: Regular::$nonExistantTest in /path/to/test.php on line 10
    Call Stack:
        0.0012     234704   1. {main}() /path/to/test.php:0
    

    So the main point here is that the empty() method should be used with care as it can lend itself to confusing – or even potentially misleading – results, if one is not careful.

    Wrap-up

    PHP’s ease of use can lull developers into a false sense of comfort, leaving themselves vulnerable to lengthy PHP debugging due to some of the nuances and idiosyncrasies of the language. This can result in PHP not working and problems such as those described herein.
    The PHP language has evolved significantly over the course of its 20 year history. Familiarizing oneself with its subtleties is a worthwhile endeavor, as it will help ensure that the software you produce is more scalable, robust, and maintainable.

  • PHP Best Practices and Tips

    Manage Your Dependencies in PHP with Composer

    What Is a Dependency?

    PHP is a great language to create web projects. One of the things you will see when using PHP is that there is a library for almost anything you need.
    A dependency in your project is a library or package that your code uses for performing tasks. For example, if you need to call a REST API you can use the curl library of PHP, or better yet, use the Guzzle library, that have all the things you need for creating the calls.

    The Problem with Dependency Management

    One common problem of using third party code is keeping it updated while time goes on. Also, there are libraries that depend on other libraries, that depends on other libraries, and so on. That is really a bad situation in a dynamic context as web development is. Not to mention which version of the library you’ll use, as sometimes you need a different version according to the context you’re in, for example, the PHP version your server has.
    And there is another catch. Requiring libraries is a big pain, you have to write all the includes into the file that needs to use a given library. When removing that class, you have to clean all the includes and delete the library. And as we all know, that can almost never happen, and we end up with a big folder of deprecated libraries, and then we need to waste our time (or the time of your team) to clean all that mess.

    Meet Composer, Your New Friend

    Composer is here to solve all those problems for us. When I first started using Composer, I thought it was a package manager, like Yum or Apt. However as they state in their documentation, they are a dependency management and not a package manager, because the packages are not installed globally. Instead, the packages are installed under a vendor folder inside your project.

    How to Manage Dependencies

    I won’t go over every detail. You can find a step by step guide explained in their getting started page, but I’ll explain quickly what you need.
    First you need to install Composer. I recommend to install it globally, and set it up so you have the Composer command available. Once you do that you have to create a composer.json file in the root of your project.
    If you want to add a new library to your project, all you have to do is add it to that file with the version you need, which looks something like this:

    {
        "require": {
            "vendor/package": "1.3.2",
            "vendor/package2": "1.*",
            "vendor/package3": "^2.0.3"
        }
    }
    

    Once you do that, next you have to run in the command line composer install and Composer will install all the needed libraries inside the vendor/ folder of your project. If you run composer update, Composer will check for new versions of the libraries and update them accordingly.
    Also, Composer will install the dependencies of these libraries without any needed extra work from you.
    There are a lot of commands you can use with Composer, run composer --help to list them all.

    Autoload Classes

    If you are already falling in love with Composer for this, you’ll definitely love it for what comes next.
    Composer offers an autoload for your classes. All you have to do is add this line in top of your project require __DIR__ . '/vendor/autoload.php'; and then just call the constructor of your class. For example, if you’re using Guzzle, you just have to call:

    $client = new GuzzleHttp\Client();
    

    and it will work. If you don’t need it anymore, just delete the class and that’s it! Well, I lied, that’s not all but almost. Head to the next section to learn the final step.

    Deleting Libraries

    We talk about the pain that is deleting a library, because you not only have to be aware of that library but also of the dependencies of that library, and being careful enough not to delete a dependency being use by another library.
    In composer this is just as simple as deleting the dependency from the composer.json file, and run composer update. Yes, it is that simple.

    Meet Packagist, the Repository for Your Projects

    As if you already don’t have enough with all this, there is a common repository for finding libraries for your projects that can be used easily with Composer.
    Packagist is the place you go when you need a library. There you can search for libraries, and see what version you want to use, depending on your needs. Also, you can write your own packages, and include them there for others to use.
    Of course, there are other ways to include packages, like directly from Github or other sources. That is out of the scope of this article, but you can find how to do this in the documentation page of Composer.

    Versioning

    When you go to the library website, you can see several available versions. In general, you will have one that is ready for production and one that is in development.
    How the versioning numbers work? Well, they follow the semantic versioning standard, which is basically as follows:
    You have 3 numbers, separated by a dot. So for example, in your composer.json file you can add something like "guzzlehttp/guzzle": "5.3.*" for requiring the Guzzle library. The first number, in this case 5, is called the major version. This number changes when big changes are made in the library. Changing this version will probably change the name of the functions, or the classes, or anything. The second number is the minor version, that is meant to be for functionality changes or additions, but having backwards compatibility with other versions. The third number is the patch number. This number is changed each time a bug is fixed, and doesn’t change the functionality of the package.
    As you can notice, you can include the wildcard * for replacing that number. This means that when you run composer update, Composer will check for the latest number in that category (major, minor or patch) and update to the newer version. It is recommended to keep the last number with a wildcard only, and update the minor version according. However, if you really trust that library and you always want the latest version, you can of course make this a wildcard as well.
    You can also use comparator operators to include a range. For example:  "guzzlehttp/guzzle": ">=5.3,<5.4"is equivalent to "guzzlehttp/guzzle": "5.3.*", and also is equivalent to "guzzlehttp/guzzle": "~5.3" using the tilde (~) operator.
    For more about versioning, go to the documentation of Composer about versioning.

    Save Disk Space

    As a last tip, if you use Git add the vendor folder in your ignore file. Having the Composer file is enough, because once the user downloads the project, it will just have to run a composer install command to fetch all the libraries.

    Summary

    In this article we explained what dependencies are, why they are important for our projects, and the problems we have when we deal with them.
    After that, we explained how Composer address all those issues in a really smart way to keep your project dependencies organized.
    Composer is another tool for your toolbelt that will save you a lot of time and headaches.
    Tips are from Toptal Developers 

  • Integration of Google Translate in any website

    Do you need your website in multilingual but don’t want to repopulate content in multiple language. In that case you can use Google API to make your website multilingual.
    First of all decide the area where you want to add language selector.
    In that place you have to add this DIV section with ID so that Script find that block and append language dropdown.

    <div id="google_translate_element"></div>
    

    now add JS library for translation.

    <script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

    Its up to you where you want to add this library either in head section or in footer. but I recommend you to place it in footer so that you web page load quickly and after that it call 3rd party library.
    now after this library call its function so that it start working. For that we have to use this JS snippt

    <script>
        function googleTranslateElementInit() {
            new google.translate.TranslateElement(
                {pageLanguage: 'en'},
                'google_translate_element'
            );
        }
    </script>

    That’s all.. now you will be able to see drop down on that place where you call that DIV section.
    7VgGB

  • Context Validation in Domain-Driven Design

    Domain-driven design (DDD in short) is not a technology or a methodology. DDD provides a structure of practices and terminology for making design decisions that focus and accelerate software projects dealing with complicated domains. As described by Eric Evans and Martin Fowler, Domain objects are a place to put validation rules and business logic.
    Eric Evans:

    Domain Layer (or Model Layer): Responsible for representing concepts of the business, information about the business situation, and business rules. State that reflects the business situation is controlled and used here, even though the technical details of storing it are delegated to the infrastructure. This layer is the heart of business software.

    Martin Fowler:

    The logic that should be in a domain object is domain logic – validations, calculations, business rules – whatever you like to call it.

    Context Validation in Domain-Driven Design
    Putting all of validation in Domain objects results in huge and complex domain objects to work with. Personally I much prefer the idea of decoupling domain validations into separate validator components that can be reused anytime and that will be based on context and user action.
    As Martin Fowler wrote in a great article:  ContextualValidation.

    One common thing I see people do is to develop validation routines for objects. These routines come in various ways, they may be in the object or external, they may return a boolean or throw an exception to indicate failure. One thing that I think constantly trips people up is when they think of object validity in a context independent way, such as an isValid method implies. […] I think it’s much more useful to think of validation as something that’s bound to a context , typically an action that you want to do. Such as asking if this order valid to be filled, or is this customer valid to check in to the hotel. So rather than have methods like isValid, have methods like isValidForCheckIn.

    Action Validation Proposal

    In this article we will implement a simple interface ItemValidator for which you need to implement a validatemethod with return type ValidationResult. ValidationResult is an object containing the item that has been validated and also the Messages object. The latter contains an accumulation of errors, warnings, and information validation states (messages) dependent upon the execution context.
    Validators are decoupled components that can be easily reused anywhere they are needed. With this approach all dependencies, which are needed for validation checks, can be easily injected. For example, to check in the database if there is a user with given email only UserDomainService is used.
    Validators decoupling will be per context (action). So if UserCreate action and UserUpdate action will have decoupled components or any other action (UserActivate, UserDelete, AdCampaignLaunch, etc.), validation can rapidly grow.
    Each action validator should have a corresponding action model which will have only the allowed action fields. For creating users, the following fields are needed:
    UserCreateModel:

    {
      "firstName": "John",
      "lastName": "Doe",
      "email": "[email protected]",
      "password": "MTIzNDU="
    }
    

    And to update user the following are allowed externalId, firstName and lastName. externalId is used for user identification and only changing of firstName and lastName is allowed.
    UserUpdateModel:

    {
      "externalId": "a55ccd60-9d82-11e5-9f52-0002a5d5c51b",
      "firstName": "John Updated",
      "lastName": "Doe Updated"
    }
    

    Field integrity validations can be shared, firstName maximum length is always 255 characters.
    During validating it is desirable to not only get the first error that occurs, but a list of all issues encountered. For example, the following 3 issues may happen at the same time, and can be reported accordingly during execution:

    • invalid address format [ERROR]
    • email must be unique among users [ERROR]
    • password too short [ERROR]

    To achieve that kind of validation, something like validation state builder is needed, and for that purpose Messages is introduced. Messages is a concept that I heard from my great mentor years ago when he introduced it to support validation and also for various other things that can be done with it, as Messages are not just for validation.
    Note that in the following sections we will be using Scala to illustrate the implementation. Just in case you are not a Scala expert, fear not as it should be easy to follow along nonetheless.

    Messages in Context Validation

    Messages is an object that represents the validation state builder. It provides an easy way to collect errors, warnings, and information messages during validation. Each Messages object has an inner collection of Message objects and also can have a reference to parentMessages object.

    A Message object is an object that can have type, messageText, key (which is optional and is used to support validation of specific inputs which are identified by identifier), and finally childMessages that provies a great way for building composable message trees.
    A message can be of one of the following types:

    • Information
    • Warning
    • Error

    Messages structured like this allows us to build them iteratively and also allows decisions to be made about next actions based on prior messages state. For example, performing validation during user creation:

    @Component
    class UserCreateValidator @Autowired (private val entityDomainService: UserDomainService) extends ItemValidator[UserCreateEntity] {
      Asserts.argumentIsNotNull(entityDomainService)
      private val MAX_ALLOWED_LENGTH = 80
      private val MAX_ALLOWED_CHARACTER_ERROR = s"must be less than or equal to $MAX_ALLOWED_LENGTH character"
      override def validate(item: UserCreateEntity): ValidationResult[UserCreateEntity] = {
        Asserts.argumentIsNotNull(item)
        val validationMessages = Messages.of
        validateFirstName (item, validationMessages)
        validateLastName  (item, validationMessages)
        validateEmail     (item, validationMessages)
        validateUserName  (item, validationMessages)
        validatePassword  (item, validationMessages)
        ValidationResult(
          validatedItem = item,
          messages      = validationMessages
        )
      }
      private def validateFirstName(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.firstName
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.FIRST_NAME_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
      }
      private def validateLastName(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.lastName
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.LAST_NAME_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
      }
      private def validateEmail(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.email
        ValidateUtils.validateEmail(
          fieldValue,
          UserCreateEntity.EMAIL_FORM_ID,
          localMessages
        )
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.EMAIL_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
        if(!localMessages.hasErrors()) {
          val doesExistWithEmail = this.entityDomainService.doesExistByByEmail(fieldValue)
          ValidateUtils.isFalse(
            doesExistWithEmail,
            localMessages,
            UserCreateEntity.EMAIL_FORM_ID.value,
            "User already exists with this email"
          )
        }
      }
      private def validateUserName(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.username
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.USERNAME_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
        if(!localMessages.hasErrors()) {
          val doesExistWithUsername = this.entityDomainService.doesExistByUsername(fieldValue)
          ValidateUtils.isFalse(
            doesExistWithUsername,
            localMessages,
            UserCreateEntity.USERNAME_FORM_ID.value,
            "User already exists with this username"
          )
        }
      }
      private def validatePassword(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.password
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.PASSWORD_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
      }
    }
    

    Looking into this code, you can see use of ValidateUtils. These utility functions are used to populate the Messages object in predefined cases. You can check out the implementation of ValidateUtils on Github code.
    During email validation, first it is checked if email is valid by calling ValidateUtils.validateEmail(…, and it is also checked if email has a valid length by calling ValidateUtils.validateLengthIsLessThanOrEqual(… . Once these two validations are done, checking if the email is already assigned to some User is performed, only if the prior email validation conditions are passing and that is done with  if(!localMessages.hasErrors()) { … . This way expensive database calls can be avoided. This is only part of UserCreateValidator. Complete source code can be found  here.
    Notice that one of the validation parameters stand out: UserCreateEntity.EMAIL_FORM_ID. This parameter connects validation state to a specific input ID.
    In previous examples, next action is decided based upon the fact if Messages object has errors (using hasErrors method). One can easily check if there are any “WARNING” messages and retry if necessary.
    One thing that can be noticed is the way localMessages is used. Local messages are messages that have been created the same as any message, but with parentMessages. With that said, the goal is to have a reference only to current validation state (in this example emailValidation), so localMessages.hasErrors can be called, where it is checked only if emailValidation context hasErrors. Also when a message is added to localMessages, it is also added to parentMessages and so all validation messages exist in higher context of UserCreateValidation.
    Now that we have seen Messages in action, in next chapter we will focus on ItemValidator.

    ItemValidator – Reusable Validation Component

    ItemValidator is a simple trait (interface) that forces developers to implement the method validate, which needs to return ValidationResult.
    ItemValidator:

    trait ItemValidator[T] {
      def validate(item:T) : ValidationResult[T]
    }
    

    ValidationResult:

    case class ValidationResult[T: Writes](
      validatedItem : T,
      messages      : Messages
    ) {
      Asserts.argumentIsNotNull(validatedItem)
      Asserts.argumentIsNotNull(messages)
      def isValid :Boolean = {
        !messages.hasErrors
      }
      def errorsRestResponse = {
        Asserts.argumentIsTrue(!this.isValid)
        ResponseTools.of(
          data      = Some(this.validatedItem),
          messages  = Some(messages)
        )
      }
    }
    

    When ItemValidators such as UserCreateValidator are implemented to be dependency injection components, then ItemValidator objects can be injected and reused in any object that needs UserCreate action validation.
    After validation is executed, it is checked if validation was successful. If it is, then user data is persisted to database, but if not the API response containing validation errors is returned.
    In the next section we will see how we can present validation errors in RESTful API response and also how to communicate with API consumers about execution action states.

    Unified API Response – Simple User Interaction

    After user action has been successfully validated, in our case user creation, validation action results need to be displayed to RESTful API consumer. The best way is to have a unified API response where only context will be switched (in terms of JSON, value of “data”). With unified responses, errors can be presented easily to RESTful API consumers.
    Unified response structure:

    {
        "messages" : {
            "global" : {
                "info": [],
                "warnings": [],
                "errors": []
            },
            "local" : []
        },
    	"data":{}
    }
    

    Unified response is structured to have two tiers of messages, global and local. Local messages are messages that are coupled to specific inputs. Such as “username is too long, at most 80 characters is allowed”_. Global messages are messages that are reflecting the state of whole data on page, such as “user will not be active until approved”. Local and global messages have three levels – error, warning and information. The value of “data” is specific to the context. When creating users the data field will contain user data, but when getting a list of users the data field will be an array of users.

    With this kind of structured response the client UI handler can be created easily, which will be responsible for displaying errors, warnings, and information messages. Global messages will be displayed at the top of the page, because they are related to global API action state, and local messages can be displayed near specified input (field), as they are directly related to the field’s value. Error messages can be presented in red color, warning messages in yellow, and information in blue.
    For example, in an AngularJS based client app we can have two directives responsible for handling local and global response messages, so that only these two handlers can deal with all responses in a consistent manner.
    Directive for the local message will need to be applied to an element parent to the actual element holding all the messages.
    localmessages.direcitive.js :

    (function() {
      'use strict';
      angular
        .module('reactiveClient')
        .directive('localMessagesValidationDirective', localMessagesValidationDirective);
      /** @ngInject */
      function localMessagesValidationDirective(_) {
        return {
          restrict: 'AE',
          transclude: true,
          scope: {
            binder: '='
          },
          template: '<div ng-transclude></div>',
          link: function (scope, element) {
            var messagesWatchCleanUp = scope.$watch('binder', messagesBinderWatchCallback);
            scope.$on('$destroy', function() {
              messagesWatchCleanUp();
            });
            function messagesBinderWatchCallback (messagesResponse) {
              if (messagesResponse != undefined && messagesResponse.messages != undefined) {
                if (messagesResponse.messages.local.length > 0) {
                  element.find('.alert').remove();
                  _.forEach(messagesResponse.messages.local, function (localMsg) {
                    var selector = element.find('[id="' + localMsg.inputId + '"]').parent();
                    _.forEach(localMsg.info, function (msg) {
                      var infoMsg = '<div class="form-control validation-alert alert alert-info alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>';
                      selector.after(infoMsg);
                    });
                    _.forEach(localMsg.warnings, function (msg) {
                      var warningMsg = '<div class="form-control validation-alert alert alert-warning alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>';
                      selector.after(warningMsg);
                    });
                    _.forEach(localMsg.errors, function (msg) {
                      var errorMsg = '<div class="form-control validation-alert  alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>';
                      selector.after(errorMsg);
                    });
                  });
                }
              }
            }
          }
        }
      }
    })();
    

    Directive for global messages will be included in the root layout document (index.html) and will register to an event for handling all global messages.
    globalmessages.directive.js:

    (function() {
      'use strict';
      angular
        .module('reactiveClient')
        .directive('globalMessagesValidationDirective', globalMessagesValidationDirective);
      /** @ngInject */
      function globalMessagesValidationDirective(_, toastr, $rootScope, $log) {
        return {
          restrict: 'AE',
          link: function (scope) {
            var cleanUpListener = $rootScope.$on('globalMessages', globalMessagesWatchCallback);
            scope.$on('$destroy', function() {
              cleanUpListener();
            });
            function globalMessagesWatchCallback (event, messagesResponse) {
              $log.log('received rootScope event: ' + event);
              if (messagesResponse != undefined && messagesResponse.messages != undefined) {
                if (messagesResponse.messages.global != undefined) {
                  _.forEach(messagesResponse.messages.global.info, function (msg) {
                    toastr.info(msg);
                  });
                  _.forEach(messagesResponse.messages.global.warnings, function (msg) {
                    toastr.warning(msg);
                  });
                  _.forEach(messagesResponse.messages.global.errors, function (msg) {
                    toastr.error(msg);
                  });
                }
              }
            }
          }
        }
      }
    })();
    

    For a more complete example, let us consider the following response containing a local message:

    {
        "messages" : {
            "global" : {
                "info": [],
                "warnings": [],
                "errors": []
            },
            "local" : [
               {
                    "inputId" : "email",
                    "errors" : ["User already exists with this email"],
                    "warnings" : [],
                    "info" : []
                }
            ]
        },
    	"data":{
    	    "firstName": "John",
    	    "lastName": "Doe",
    	    "email": "[email protected]",
          "password": "MTIzNDU="
        }
    }
    

    The above response can lead to something as follows:

    On the other hand, with a global message in response:

    {
        "messages" : {
            "global" : {
                "info": ["User successfully created."],
                "warnings": ["User will not be available for login until is activated"],
                "errors": []
            },
            "local" : []
        },
    	"data":{
    	    "externalId": "a55ccd60-9d82-11e5-9f52-0002a5d5c51b",
    	    "firstName": "John",
    	    "lastName": "Doe",
    	    "email": "[email protected]"
        }
    }
    

    The client app can now show the message with more prominence:

    In above examples it can be seen how a unified response structure can be handled for any request with the same handler.

    Conclusion

    Applying validation on large projects can become confusing, and validation rules can be found everywhere throughout project code. Keeping validation consistent and well structured makes things easier and reusable.
    You can find these ideas implemented in two different versions of boilerplates below:

    In this article I have presented my suggestions on how to support deep, composable context validation which can be easily presented to a user. I hope this will help you solve the challenges of proper validation and error handling once and for all. Please feel free to leave your comments and share your thoughts below.

  • Build Ultra-Modern Web Apps with Angular Material

    At the Google I/O Conference back in 2014, Google announced Material Design, their new design language. They have since converted much of their popular applications to adhere to this new spec in an effort to provide a consistent experience. Now they are trying to convince you to follow along as well.
    Angular Material: Superheroic Javascript Framework Meets Ultra-Modern Design

    What is Material Design?

    After a visit to the official Material Design spec, you will immediately get a feeling of ultra-modern minimalism. Basic shapes and flat colors are the theme here. Going through the documentation is quite an experience. I recommend taking a look for yourself, but I will summarize it here.

    Goal

    The purpose is to create a visual language that synthesizes classic principles of good design with the innovation and possibility of technology and science. Also to develop a single underlying system that allows for a unified experience across various platforms and device sizes.

    Principles

    Material Design is founded on three principles.

    Material Is the Metaphor

    Inspired by the study of paper and ink, the material lives in 3D space and is grounded in tactile reality. It gives the illusion of space by using realistic shadows. The paper material must abide by the laws of physics (i.e. two pieces of paper may not travel through each other), but may supercede the physical world (i.e. a paper may grow or shrink).

    Bold, Graphic, Intentional

    Deliberate color choices, edge-to-edge imagery, large-scale typography, and intentional white space create a bold and graphic interface that immerse the user in the experience. The Floating Action Button, or FAB, is a prime example of this principle. Have you noticed that little circle with the ‘plus’ symbol floating around in your Google Inbox app? Material Design makes it very apparent that this is an important button.

    Motion Provides Meaning

    Motion is meaningful and appropriate, serving to focus attention and maintain continuity. Feedback is subtle yet clear. Transitions are efficient yet coherent. The main point here is to animate only when it has a purpose and not to overdo it.

    How does AngularJS fit into Material Design?

    AngularJS, Google’s “Superheroic JavaScript MVW Framework”, addresses many of the challenges encountered in developing single-page applications (SPA). It provides the framework needed for creating modern web applications that connect to APIs and never need the page to be refreshed.

    AngularJS: A New Approach

    Angular is what HTML would have been, had it been designed for applications. HTML is a great declarative language for static documents, but creating dynamic applications not so much.
    Creating dynamic applications with HTML has always been an exercise in tricking the browser into doing things it wasn’t meant to do. There are a couple of approaches to doing this.

    1. Library – a collection of functions. (jQuery)
    2. Framework – code dynamically fills in static elements when needed. (Durandal, Ember)

    Angular takes a different approach to solve this problem. Instead of struggling with the HTML it is given, it creates new HTML constructs. Angular teaches the browser new HTML syntax through a construct called ‘directives’. Angular comes with a set of these directives built-in, but also allows you to create custom directives, so it allows you to write your own HTML elements.
    Wouldn’t it be neat if Google created a set of directives based on Material Design principles?

    Introducing Angular Material

    Google is actively developing Angular Material, an implementation of Material Design in AngularJS. Angular Material provides a set of reusable UI components based on the Material Design system. Angular Material is composed of several pieces. It has a CSS library for typography and other elements, it provides an interesting JavaScript approach for theming, and its responsive layout uses a flex grid. But the most appealing feature of Angular Material is its amazing collection of directives.

    Getting Started

    I have created an open source project to help jumpstart your next Angular Material project. The purpose of this project is to give an example of everything Angular Material has to offer, all under one roof. Navigation, paging, theming, and the entire collection of directives are ready to go, all you have to do is feed in your data and bind it to the HTML.
    Take a look at the demo here or fork the code on GitHub.

    Directives

    Directives are a core Angular feature. Angular comes with several directives that you use all of the time like ng-model or ng-repeat. They are a very important piece of Angular that makes the framework function as it should.

    How to Use an Angular Material Directive

    Angular Material extends this directive library with a set of beautiful Material Design inspired directives. Angular Material directives are HTML tags that begin with ‘md’; short for Material Design. They couldn’t be much easier to use. For example, let’s take a look at the good old button.
    A standard HTML button might look something like this.

    <button>Click Me</button>
    

    An Angular Material button looks like this.

    <md-button>Click Me</md-button>
    

    And this is all that is needed to make a Material button. Now, there are several other options that are available for this directive such as theming it and raising it from the surface to imply importance.

    <md-button class="md-raised md-primary md-hue-1">Click Me</md-button>
    

    Services

    Services are also core to Angular functionality. They are used to share code across the application. A common core service like $http is used and reused for data calls in Angular applications.
    Angular services are:

    1. Lazily instantiated – Angular only instantiates a service when an application component depends on it.
    2. Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

    How to Use an Angular Material Service

    Angular Material comes packaged with some services that provide some extra functionality to the application. They also contribute to the performance of some of the directives. A great example of a service is the ‘toast’.

    A toast is a small notification that slides in from the top of the screen and goes away after a few seconds. Using this service is easy.
    In JavaScript,

    $mdToast.show(
          $mdToast.simple('Simple Toast!')
            .position('left bottom')
            .hideDelay(3000)
        );
    

    This example shows a simple toast that pops up on the bottom left of the screen and retreats after 3 seconds.
    Some services can be personalized with custom templates. In this case, the $mdToast service can use a custom HTML template by using the md-toast directive.

    Theming

    Material Design is a visual language where themes convey meaning through color, tones, and contrast. These themes are expressed throughout the components in the entire application to provide a more unified feel.

    According to the Material Design guidelines, you must “limit your selection of colors by choosing three color hues from the primary palette and one accent color from the secondary palette.” Angular Material makes following this guideline simple by using JavaScript to configure the theme. But first, what is a palette and a hue?

    • Hue: A hue is a single color in a palette.
    • Palette: A palette is a collection of hues.

    For example, a palette would be ‘green’ and a hue is a particular shade of green. Angular Material comes packaged with all of the valid palettes from the Material Design spec. You can learn about more about the valid color palettes here.

    Configuring the Theme

    Theming your project is a piece of cake. In the app.js file, set your desired palettes and hues using the Theming Provider service.

    angular.module('myApp', ['ngMaterial'])
    .config(function($mdThemingProvider) {
      $mdThemingProvider.theme('default')
        .primaryPalette(‘cyan’, {
          'default': '400',
          'hue-1': '100',
          'hue-2': '600',
          'hue-3': 'A100'
        })
        .accentPalette('amber')
        .warnPalette('red')
        .backgroundPalette('grey');
    });
    

    Using the Theme

    To apply the theme to the components, set the class of the element to the desired palette and hue.

    <md-button class="md-primary">Click me</md-button>
    <md-button class="md-primary md-hue-1">Click me</md-button>
    <md-button class="md-primary md-hue-2">Click me</md-button>
    <md-button class="md-accent">or maybe me</md-button>
    <md-button class="md-warn">Careful</md-button>
    

    Layout

    Flexbox is the latest and greatest addition to responsive design and Angular Material comes packaged with it. If you are familiar with the Bootstrap grid system, then you should be able to catch on quickly. In fact, Bootstrap is switching to Flexbox in its upcoming release. It has the familiar rows and columns layout you have become accustomed to, but with much more. Learn how to use Flexbox with this tutorial or study the official documentation.

    Top 9 Best Angular Material Directives

    There are too many Angular Material directives to list them all, so I would like to share with you my favorites.

    9. Progress Linear

    Often in SPAs, pages need time to load data from the server. If the application shows a blank page during this time, users may think the application is broken and will leave. Let users know the data is loading with the Progress Linear directive. Users will know to wait when they see an animated progress bar indicating that something is happening. Alternatively, use the Progress Circular directive for a round indicator.

    8. Date Picker

    The Date Picker directive makes choosing a date a clean, simple experience for the user and a true one-liner to write. Simply use md-datepicker and optionally confine the range with md-min-date and md-max-date and that’s it.

    7. Autocomplete

    Autocomplete provides a pleasant user experience by helping the user choose an option. It is what makes Google’s search engine the best. The Autocomplete directive adds this functionality to your application by completing a user’s words as they type. But the best part about this directive is customization. By filling your autocomplete with md-item-template you can give more meaning to the suggestions. For instance, if a user was searching for names in a company, the autocomplete could show the matching names with their picture and company role, giving a more robust user experience.

    6. Bottom Sheet

    The bottom sheet is a little menu that slides up from the bottom of your screen, covering content and taking focus. Originally intended to be used solely for mobile devices, the bottom sheet has been gaining popularity on larger screens. To use it, create a template with md-bottom-sheet containing either an md-grid or an md-list for a grid layout or list layout, respectively. Then call it with the Bottom Sheet service, $mdBottomSheet.show().

    5. Input

    Input forms are boring and have been since the beginning of the internet. But they don’t have to be! Give your inputs some flair with the Input directive. Wrap your input tag with md-input-container and watch it come to life. Watch as your placeholder animates into a floating label. Easily validate your input with instant, but subtle, color changes and warning messages. Input directive takes an element that is expected to be boring and delivers a pleasant surprise.

    4. Toast

    The most aggravating user experience is not knowing what the application is doing. We ease this aggravation with toasters, or little unobtrusive notifications. In the olden days, when we sent a request to the server we waited on that page until the response came back before we could move on. User attention span has dropped drastically since then. In today’s SPAs, we click a button and expect to move along immediately, dealing with the server response when it comes. The Toast directive makes this a piece of cake. A toaster is summoned by simply using the Toast Service, $mdToast.show(), and setting the text, duration, and which corner to appear in. Make your own custom toaster with md-toast.

    3. Grid List

    Are your lists lacking pizazz? Grid lists are an alternative to standard list views. A grid list is best for presenting images, and is optimized for visual comprehension. It works by laying different sized tiles on a grid, giving a scattered, eclectic feel. The tile size and layout then respond to the screen size. This directive is sure to give your application an exciting and fun look.

    2. Whiteframe

    The concept of space is the core of Material Design and its paper metaphor. Two sheets of paper in the same z-position (or depth), form a seam and must move together. Two overlapping sheets of paper, with different z-positions, form a step. They move independently of each other. To follow the design, we must be able to shift elements along the z-axis. Angular Material provides a simple way to do this. Using the Whiteframe directive, set the class to md-whiteframe-z{x}, where x is the units of depth up from the background. The larger the number, the larger the shadow cast by the paper.

    1. Sidenav

    Creating a side navigation menu has never been easier. The Sidenav directive places a navigation menu on either the left or right of the screen. Keeping mobile in mind, it swipes in and out as expected, or programmatically with a button click. A nice addition is the lock open feature. The side navigation can be set to lock open when the screen reaches a certain size. By setting the parameter md-is-locked-open=”$mdMedia(‘gt-sm’)” the menu will be tucked away on the phone but locked open on tablet and larger.

    Conclusion

    Google is converting their most popular applications to Material Design. Now they are heading the development of Angular Material, an implementation of Material Design written in AngularJS. Material Design uses a paper metaphor, bold intentions, and meaningful motion. AngularJS organizes single page applications. Angular Material applies Material Design principles to AngularJS applications.
    Material Design is here and Angular Material is a fantastic way to apply the Material design spec to your single page applications. If you want to create your own Angular Material application, don’t waste your time starting from scratch. Rather, start off with a fully functioning app with demos of the directives, theming already set up, and navigation and routing ready to go. Take a look at the demo here or fork the code on GitHub. Of course, you can also learn all about Angular Material by visiting the official documentation.
    What do you think about my picks for the best Angular Material directives? Did I get them right? What are your favorites?

  • A Step-by-Step Tutorial for Your First AngularJS App

    What is AngularJS?

    AngularJS is a JavaScript MVC framework developed by Google that lets you build well structured, easily testable, and maintainable front-end applications.

    And Why Should I Use It?

    If you haven’t tried AngularJS yet, you’re missing out. The framework consists of a tightly integrated toolset that will help you build well structured, rich client-side applications in a modular fashion—with less code and more flexibility.
    AngularJS extends HTML by providing directives that add functionality to your markup and allow you to create powerful dynamic templates. You can also create your own directives, crafting reusable components that fill your needs and abstracting away all the DOM manipulation logic.
    It also implements two-way data binding, connecting your HTML (views) to your JavaScript objects (models) seamlessly. In simple terms, this means that any update on your model will be immediately reflected in your view without the need for any DOM manipulation or event handling (e.g., with jQuery).

    Angular provides services on top of XHR that dramatically simplify your code and allow you to abstract API calls into reusable services. With that, you can move your model and business logic to the front-end and build back-end agnostic web apps.

    Finally, I love Angular because of its flexibility regarding server communication. Like most JavaScript MVC frameworks, it lets you work with any server-side technology as long as it can serve your app through a RESTful web API. But Angular also provides services on top of XHR that dramatically simplify your code and allow you to abstract API calls into reusable services. As a result, you can move your model and business logic to the front-end and build back-end agnostic web apps. In this post, we’ll do just that, one step at a time.

    So, Where Do I Begin?

    First, let’s decide the nature of the app we want to build. In this guide, we’d prefer not to spend too much time on the back-end, so we’ll write something based on data that’s easily attainable on the Internet—like a sports feed app!
    Since I happen to be a huge fan of motor racing and Formula 1, I’ll use an autosport API service to act as our back-end. Luckily, the guys at Ergast are kind enough to provide a free motorsport API that will be perfect for us.
    For a sneak peak at what we’re going to build, take a look at the live demo. To prettify the demo and show off some Angular templating, I applied a Bootstrap theme from WrapBootstrap, but seeing as this article isn’t about CSS, I’ll just abstract it away from the examples and leave it out.

    Getting Started Tutorial

    Let’s kickstart our example app with some boilerplate. I recommend the angular-seed project as it not only provides you with a great skeleton for bootstrapping, but also sets the ground for unit testing with Karma and Jasmine (we won’t be doing any testing in this demo, so we’ll just leave that stuff aside for now; see Part 2 of this tutorial for more info on setting up your project for unit and end-to-end testing).
    EDIT (May 2014): Since I wrote this tutorial, the angular-seed project has gone through some heavy changes (including the additon of Bower as package manager). If you have any doubts about how to deploy the project, take a quick look at the first section of their reference guide. In Part 2 of ths tutorial, Bower, among other tools, is covered in greater detail.
    OK, now that we’ve cloned the repository and installed the dependencies, our app’s skeleton will look like this:

    angularjs tutorial - start with the skeleton

    Now we can start coding. As we’re trying to build a sports feed for a racing championship, let’s begin with the most relevant view: the championship table.

    the championship table

    Given that we already have a drivers list defined within our scope (hang with me – we’ll get there), and ignoring any CSS (for readability), our HTML might look like:

    <body ng-app="F1FeederApp" ng-controller="driversController">
      <table>
        <thead>
          <tr><th colspan="4">Drivers Championship Standings</th></tr>
        </thead>
        <tbody>
          <tr ng-repeat="driver in driversList">
            <td>{{$index + 1}}</td>
            <td>
              <img src="img/flags/{{driver.Driver.nationality}}.png" />
              {{driver.Driver.givenName}}&nbsp;{{driver.Driver.familyName}}
            </td>
            <td>{{driver.Constructors[0].name}}</td>
            <td>{{driver.points}}</td>
          </tr>
        </tbody>
      </table>
    </body>
    

    The first thing you’ll notice in this template is the use of expressions (“{{“ and “}}”) to return variable values. In AngularJS, expressions allow you to execute some computation in order to return a desired value. Some valid expressions would be:

    • {{ 1 + 1 }}
    • {{ 946757880 | date }}
    • {{ user.name }}

    Effectively, expressions are JavaScript-like snippets. But despite being very powerful, you shouldn’t use expressions to implement any higher-level logic. For that, we use directives.

    Understanding Basic Directives

    The second thing you’ll notice is the presence of ng-attributes, which you wouldn’t see in typical markup. Those are directives.
    At a high level, directives are markers (such as attributes, tags, and class names) that tell AngularJS to attach a given behaviour to a DOM element (or transform it, replace it, etc.). Let’s take a look at the ones we’ve seen already:

    • The ng-app directive is responsible for bootstrapping your app defining its scope. In AngularJS, you can have multiple apps within the same page, so this directive defines where each distinct app starts and ends.
    • The ng-controller directive defines which controller will be in charge of your view. In this case, we denote the driversController, which will provide our list of drivers (driversList).
    • The ng-repeat directive is one of the most commonly used and serves to define your template scope when looping through collections. In the example above, it replicates a line in the table for each driver in driversList.

    Adding Controllers

    Of course, there’s no use for our view without a controller. Let’s add driversController to our controllers.js:

    angular.module('F1FeederApp.controllers', []).
    controller('driversController', function($scope) {
        $scope.driversList = [
          {
              Driver: {
                  givenName: 'Sebastian',
                  familyName: 'Vettel'
              },
              points: 322,
              nationality: "German",
              Constructors: [
                  {name: "Red Bull"}
              ]
          },
          {
              Driver: {
              givenName: 'Fernando',
                  familyName: 'Alonso'
              },
              points: 207,
              nationality: "Spanish",
              Constructors: [
                  {name: "Ferrari"}
              ]
          }
        ];
    });
    

    You may have noticed the $scope variable we’re passing as a parameter to the controller. The $scopevariable is supposed to link your controller and views. In particular, it holds all the data that will be used within your template. Anything you add to it (like the driversList in the above example) will be directly accessible in your views. For now, let’s just work with a dummy (static) data array, which we will replace later with our API service.
    Now, add this to app.js:

    angular.module('F1FeederApp', [
      'F1FeederApp.controllers'
    ]);
    

    With this line of code, we actually initialize our app and register the modules on which it depends. We’ll come back to that file (app.js) later on.
    Now, let’s put everything together in index.html:

    <!DOCTYPE html>
    <html>
    <head>
      <title>F-1 Feeder</title>
    </head>
    <body ng-app="F1FeederApp" ng-controller="driversController">
      <table>
        <thead>
          <tr><th colspan="4">Drivers Championship Standings</th></tr>
        </thead>
        <tbody>
          <tr ng-repeat="driver in driversList">
            <td>{{$index + 1}}</td>
            <td>
              <img src="img/flags/{{driver.Driver.nationality}}.png" />
              {{driver.Driver.givenName}}&nbsp;{{driver.Driver.familyName}}
            </td>
            <td>{{driver.Constructors[0].name}}</td>
            <td>{{driver.points}}</td>
          </tr>
        </tbody>
      </table>
      <script src="bower_components/angular/angular.js"></script>
      <script src="bower_components/angular-route/angular-route.js"></script>
      <script src="js/app.js"></script>
      <script src="js/services.js"></script>
      <script src="js/controllers.js"></script>
    </body>
    </html>
    

    Modulo minor mistakes, you can now boot up your app and check your (static) list of drivers.
    Note: If you need help debugging your app and visualizing your models and scope within the browser, I recommend taking a look at the awesome Batarang plugin for Chrome.