How Much Coding Should Designers Know?


Many designers think each discipline should mind their own business, while others see no problem in professionals wearing multiple hats. Many developers see designers who code as a threat, while others see it as a facilitator. This is a hotly debated subject, and although I think some great designers are also superb at coding, I will always defend that the more you focus on a particular area the best you will be at it. But this shouldn’t be a reason for you to miss out on the benefits of having another skill under your belt.

designers coding

Learn how to code and make yourself a great asset to any multi-disciplinary team.

As a designer who has gone as far to set up Linux servers and program back-end, I see no question that understanding ‘the basics’ of coding would benefit any designer. The question really is, how much coding should designers learn? At what point might designers be wasting their time, or really stepping over the line into the territory of developers?

In order to provide some insight into the potential benefits of learning to code, I’ve broken the different levels of coding knowledge down into degrees of usefulness.

Step 1: Know the basics of HTML and CSS

Any designer would greatly benefit from knowing the foundations of HTML and CSS and would be surprised by how easy it can be. Stop being lazy and just learn this, it will make you a better designer, guaranteed.

When is front-end just coding, not programming?

Is front-end coding? Yes! Is it programming? Only after a certain point.

HTML and CSS don’t involve programming logics. You can see that in HTML – HyperText Markup Language the letter M stands for Markup, what means that it’s nothing more than a coded structure of the page/screen elements. It works like a puzzle, but it doesn’t require a lot of mathematical thinking.

In laymen’s terms, HTML is an architectural map that tells the browser what to display. The HTML map will influence how search engine crawlers will interpret the site. So, the concern here is to make sure the code is very well structured and that those systems can understand it and rank it well.

CSS, or Cascading Style Sheets, is the code that tells the browser how to display things. Metaphorically, if HTML is the skeleton of a page or screen, CSS would be the skin and eyes colors, hairstyle, body shape, limbs sizes, etc. The language has a very simple code structure that determines typography, colors, positions and dimensions. The concern with HTML is to keep it very organized for maintenance and optimized for good performance.

Understanding code means understanding your pixels

Learning how to code gives you the opportunity to know how things work. Why do we need to worry about pixel-perfection, is it only for the sake of symmetry?

If you play with HTML and CSS, you’ll notice that everything is measured in pixels (there are other measurement units – not relevant here – but they will ultimately be converted to pixels). Understanding these mechanics will change your mindset and will care for design in a more efficient way for the development process. As a consequence, not only your projects will be easier to program as your projects may look much more structured.

Step 2: Front-end JavaScript and AJAX could make you a unique asset

This is where things can start to get complicated, but it’s also where a lot of fun happens. If you’re an analytical thinker, or specially motivated, you’ll get a lot out of learning JavaScript and AJAX. As well, your design perspective will improve in knowing exactly how far technology can take you and how far you can push it to be innovative. I don’t think going this deep is necessary though, because if you know the basics of HTML and CSS you’ll already be ahead of most competitors. However, you may find some fun in making things coming to life with the knowledge.

When does front-end become programming?

Although we could stop here and have the back-end implemented, we can make our project more dynamic by adding some scripting, like if we could give a few acrobatic abilities to the beautifully structured and painted body we created with HTML / CSS.

For that, we have our dear JavaScript, which is an actual logical programming language. JavaScript can be used to display dynamic interactions, animate elements, create a very responsive communication with the back-end or server, as well as other things. As there aren’t many limits to what can be accomplished with Javascript in front-end development, now we are talking about a programming language: functions, objects, logics, conditionals, math, math and more math so that it may be a little challenging. But it’s not that hard to learn, especially considering what most clients will require.

In my opinion if you want to say you’re a front-end developer, knowing (at least the basics of) JavaScript is mandatory. You should understand how AJAX works (which is used by nearly any modern website). You should test your interactions in real time, and if you’re a motion designer, like me, you can do some animations yourself rather than having to explain it to a programmer, which may not have the same eye for the kind of detail that you see as a designer.

As well, there are the pre-processors for HTML (Haml, Jade, etc.) and CSS (SCSS, LESS, etc.), which are languages that aim to facilitate and streamline the coding process using programming concepts (such as logics, modulation, among others). The code, as it states, is then pre-processed, generating the pure HTML and CSS (also called vanilla). Even if you know only the basics of programming, these could be real time-savers.

Knowing how to program informs the limitations of devices

If you, a designer, learn front-end you will clearly see various advantages for knowing it, such as knowing how things work and see the limitations of each device.

Even browsers behave differently – let alone separate devices – so knowing this when you are creating gives you a sense of making something solid, lowering the chances of future complications in projects. Every programmer I know got a layout that was impossible to reproduce at some point in their lives.

Knowing the mechanics behind a digital project will not only give you an idea of what limits your work, but also what boundaries of technology you can push. I remember when several agencies, such as Fantasy and Firstborn, made a reputation in the early 2000’s for using Javascript in a different and very creative way.

Step 3: Back-end JavaScript might be overkill

Well, maybe we’re going too far here. Knowing the basics of back-end JavaScript can be useful depending on the stack your team uses (like MEAN stack, for example). But, you don’t have to go too far if all you need to know is how to run a project. However, if you dream of leading product teams, this may be helpful. But, if you call yourself a designer, not developer, your returns are seriously diminishing at this point, so you’d be better off expanding your creative skills.

Learn to code and collaborate better with developers

Would romantic relationships be easier if men could read the minds of women? Many would think so. I wonder the same thing about designers and developers.

Knowing how developers think and what they need to be able to do their job may sound like stepping on their territory, but it will make you a great asset to any multi-disciplinary team.

This can be very useful both for internal communications, as well as in idea pitches, because you know what to expect from the other members of the team. If you can do this, know your limitations (and how to push them), then you will be able to propose much more robust solutions to clients.

A designer who can code will see more job opportunities

One of the reasons why I closed my small company (RIP!), was the fact that I started international relationships that became increasingly more attractive than local businesses. For these contacts, today I work exclusively for this the global market, so 99% of my network is foreign. The opportunity that opened up this market for me was a scenario that required an individual who could do it all, including front-end. And I fit the bill; I could even program back-end. By then I ended up getting involved more and more with the dark side of the force, even to the point of setting up and managing Linux servers.

In every opportunity I had since then, knowing how to program made a big difference both in the screening processes and the day to day work. At Toptal we see a bunch of opportunities for professionals with this hybrid profile, and startups out there are eager to find people that can take over both the design and front-end of their early-stage applications.

designers coding

Learning how to code might lead to some unexpected opportunities.

Still, there are some designers and programmers who dislike one another snooping into each other’s businesses. Why might this be? Some may be afraid of losing work, and some may be lazy to learn something new. But the truth is that you should analyze your options, and focus on what will increase your chances of success. You may not have enough time now to learn everything, but maybe knowing vanilla HTML and CSS should be sufficient to add a significant differential to your career. It should be quick and easy for you to take the first steps. The more you know, the more you expand your opportunities. So, by experience, I would never discourage any opportunity to learn new skills.

Step 4: Database Architecture and Software Engineering Won’t Get Designers Anywhere

Unless algebra and complex computing are your thing, I would say “Dear God, no!”. There are other useful side skills you could learn instead (like knitting). People are just as likely to want to hire a designer who knows how to knit as one who knows how to architect databases. Besides, you don’t want to be in a place where you need to take care of everything, believe me.

So, should designers program?

I would say no. You don’t need to. But more and more the work opportunities in the design field add web-development, or at least front-end notions, as a requirement or a differential. So you don’t need to, but maybe you should if you want to have something else to offer, especially if you’re having trouble finding work. Sometimes we can’t find an opportunity that fits our profile, and that’s when we need to adapt to what is out there.

Conclusion

All of this said, we all know that it is not mandatory for a designer to know how to program. I know a lot of designers that don’t, excellent ones in fact.

However, in some cases, I notice deficiencies from a development point-of-view, in details that could even harm a project’s productivity.

You don’t need to be a designer who is also an expert in front-end development to have these differential skills added to your CV or applied to your projects, and you have a lot of online resources to start walking down this road. Simple skills can impact your potential for success in a very positive way.

Do some research, look at what job offers are requesting, see the profile of designers startups are looking for, and maybe you can agree with me when I say you don’t need to learn how to code, but you should.

Think about it!

Article from Toptal

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


It could rightfully be said that logs are one of the most underestimated and underutilized tools at a freelance php developer’s disposal. Despite the wealth of information they can offer, it is not uncommon for logs to be the last place a developer looks when trying to resolve a problem.

In truth, PHP log files should in many cases be the first place to look for clues when problems occur. Often, the information they contain could significantly reduce the amount of time spent pulling out your hair trying to track down a gnarly bug.

But perhaps even more importantly, with a bit of creativity and forethought, your logs files can be leveraged to serve as a valuable source of usage information and analytics. Creative use of log files can help answer questions such as: What browsers are most commonly being used to visit my site? What’s the average response time from my server? What was the percentage of requests to the site root? How has usage changed since we deployed the latest updates? And much, much more.

PHP log files

This article provides a number of tips on how to configure your log files, as well as how to process the information that they contain, in order to maximize the benefit that they provide.

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

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

Our PHP Log File Example Project

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

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

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

Tips for Configuring Your Log Files

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

Error Log Confguration

Error logs represent the most basic form of logging; i.e., capturing additional information and detail when problems occur. So, in an ideal world, you would want there to be no errors and for your error logs to be empty. But when problems do occur (as they invariably do), your error logs should be one of the first stops you make on your debugging trail.

Error logs are typically quite easy to configure.

For one thing, all error and crash messages can be logged in the error log in exactly the same format in which they would otherwise be presented to a user. With some simple configuration, the end user will never need to see those ugly error traces on your site, while devops will be still able to monitor the system and review these error messages in all their gory detail. Here’s how to setup this kind of logging in PHP:

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

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

display_errors = Off
display_startup_errors = Off

System Log (syslog) Confguration

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

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

(Note: In this article, we’ll be using rsyslogd for our examples.)

The basic syslog configuration is generally adequate for capturing your log messages in a system-wide log file (normally /var/log/syslog; might also be /var/log/messages or /var/log/system.log depending on the distro you’re using).

The system log provides several log facilities, eight of which (LOG_LOCAL0 through LOG_LOCAL7) are reserved for user-deployed projects. Here, for example, is how you might setup LOG_LOCAL0 to write to 4 separate log files, based on logging level (i.e., error, warning, info, debug):

# /etc/rsyslog.d/my.conf

local0.err      /var/log/my/err.log
local0.warning  /var/log/my/warning.log
local0.info     -/var/log/my/info.log
local0.debug    -/var/log/my/debug.log

Now, whenever you write a log message to LOG_LOCAL0 facility, the error messages will go to /var/log/my/err.log, warning messages will go to /var/log/my/warning.log, and so on. Note, though, that the syslog daemon filters messages for each file based on the rule of “this level and higher”. So, in the example above, all error messages will appear in all four configured files, warning messages will appear in all but the error log, info messages will appear in the info and debug logs, and debug messages will only go to debug.log.

One additional important note; The - signs before the info and debug level files in the above configuration file example indicate that writes to those files should be perfomed asynchronously (since these operations are non-blocking). This is typically fine (and even recommended in most situations) for info and debug logs, but it’s best to have writes to the error log (and most prpobably the warning log as well) be synchronous.

In order to shut down a less important level of logging (e.g., on a production server), you may simply redirect related messages to /dev/null (i.e., to nowhere):

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

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

# /etc/rsyslog.d/fixtab.conf

$EscapeControlCharactersOnReceive off

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

service rsyslog restart

Server Log Confguration

Unlike application logs and error logs that you can write to, server logs are exclusively written to by the corresponding server daemons (e.g., web server, database server, etc.) on each request. The only “control” you have over these logs is to the extent that the server allows you to configure its logging functionality. Though there can be a lot to sift through in these files, they are often the only way to get a clear sense of what’s going on “under the hood” with your server.

Let’s deploy our Symfony Standard example application on nginx environment with MySQL storage backend. Here’s the nginx host config we will be using:

server {
    server_name my.log-sandbox;
    root /var/www/my/web;

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

    error_log /var/log/nginx/my_error.log;
    access_log /var/log/nginx/my_access.log;
}

With regard to the last two directives above: access_log represents the general requests log, while error_log is for errors, and, as with application error logs, it’s worth setting up extra monitoring to be alerted to problems so you can react quickly.

Note: This is an intentionally oversimplified nginx config file that is provided for example purposes only. It pays almost no attention to security and performance and shouldn’t be used as-is in any “real” environment.

This is what we get in /var/log/nginx/my_access.log after typing http://my.log-sandbox/app_dev.php/ in browser and hitting Enter.

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

This shows that, for serving one page, the browser actually performs 9 HTTP calls. 7 of those, however, are requests to static content, which are plain and lightweight. However, they still take network resources and this is what can be optimized by using various sprites and minification techniques.

While those optimisations are to be discussed in another article, what’s relavant here is that we can log requests to static contents separately by using another location directive for them:

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

Remember that nginx location performs simple regular expression matching, so you can include as many static contents extensions as you expect to dispatch on your site.

Parsing such logs is no different than parsing application logs.

Other Logs Worth Mentioning

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

The Debug Log

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

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

The same setting applies for Apache or whatever other webserver you use.

And incidentally, debug logs are not related to error logs, even though they are configured in the error_logdirective.

Although the debug log can indeed be verbose (a single nginx request, for example, generated 127KB of log data!), it can still be very useful. Wading through a log file may be cumbersome and tedious, but it can often quickly provide clues and information that greatly help accelerate the debugging process.

In particular, the debug log can really help with debugging nginx configurations, especially the most complicated parts, like location matching and rewrite chains.

Of course, debug logs should never be enabled in a production environment. The amount of space they use also and the amount of information that they store means a lot of I/O load on your server, which can degrade the whole system’s performance significantly.

Data Storage Logs

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

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

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

Writing to Your Log Files

PHP itself provides functions for opening, writing to, and closing log files (openlog(), syslog(), and closelog(), respectively).

There are also numerous logging libraries for the PHP developer, such as Monolog (popular among Symfonyand Laravel users), as well as various framework-specific implementations, such as the logging capabilities incorporated into CakePHP. Generally, libraries like Monolog not only wrap syslog() calls, but also allow using other backend functionality and tools.

Here’s a simple example of how to write to the log:

<?php

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

Our call here to openlog:

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

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

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

Maximizing the Value of Your PHP Log Files

Now that we’re all good with theory and basics, let’s see how much we can get from logs making as few changes as possible to our sample Symfony Standard project.

First, let’s create the scripts src/log-begin.php (to properly open and configure our logs) and src/log-end.php(to log information about successful completion). Note that, for simplicity, we’ll just write all messages to the info log.

# src/log-begin.php

<?php

define('START_TIME', microtime(true));
openlog(uniqid(), LOG_ODELAY, LOG_LOCAL0);
syslog(LOG_INFO, 'BEGIN');
syslog(LOG_INFO, "URI\t{$_SERVER['REQUEST_URI']}");
$browserHash = substr(md5($_SERVER['HTTP_USER_AGENT']), 0, 7);
syslog(LOG_INFO, "CLIENT\t{$_SERVER['REMOTE_ADDR']}\t{$browserHash}"); <br />

# src/log-end.php

<?php

syslog(LOG_INFO, "DISPATCH TIME\t" . round(microtime(true) - START_TIME, 2));
syslog(LOG_INFO, 'END');

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

<?php

require_once(dirname(__DIR__) . '/src/log-begin.php');
syslog(LOG_INFO, "MODE\tPROD");

# original app.php contents

require_once(dirname(__DIR__) . '/src/log-end.php');

For the development environment, we want to require these scripts in app_dev.php as well. The code to do so would be the same as above, except we would set the MODE to DEV rather than PROD.

We also want to track what controllers are being invoked, so let’s add one more line in Acme\DemoBundle\EventListener\ControllerListener, right at the beginning of the ControllerListener::onKernelController() method:

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

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

Analyzing the Data in Your Log Files

For starters, let’s see how many HTTP requests are required to serve each page load.

Here’s the info in the logs for one request, based on the way we’ve configured our logging:

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

So now we know that each page load is actually served with two HTTP requests.

Actually there are two points worth mentioning here. First, the two requests per page load is for using Symfony in dev mode (which I have done throughout this article). You can identify dev mode calls by searching for /app-dev.php/ URL chunks. Second, let’s say each page load is served with two subsequent requests to the Symfony app. As we saw earlier in the nginx access logs, there are actually more HTTP calls, some of which are for static content.

OK, now let’s surf a bit on the demo site (to build up the data in the log files) and let’s see what else we can learn from these logs.

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

# grep -c BEGIN info.log
10

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

# grep -c END info.log
10

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

What was the percentage of requests to the site root?

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

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

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

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

# grep 54f58724b1ccc info.log | grep CONTROLLER
Mar  3 12:04:23 log-sandbox 54f58724b1ccc: CONTROLLER   Acme\DemoBundle\Controller\WelcomeController

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

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

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

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

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

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

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

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

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

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

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

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

Did anyone ever supply GET parameters?

# grep URI info.log | grep \?

No, Symfony standard uses only URL slugs, so this also tells us here that no one has attempted to hack the site.

These are just a handful of relatively rudimentary examples of the ways in which logs files can be creatively leveraged to yield valuable usage information and even basic analytics.

Other Things to Keep in Mind

Keeping Things Secure

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

Fighting Log File Bloat

Since log files are text files to which you always append information, they are constantly growing. Since this is a well-known issue, there are some fairly standard approaches to controlling log file growth.

The easiest is to rotate the logs. Rotating logs means:

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

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

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

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

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

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

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

Remote Logs

As the project grows, parsing information from logs gets more and more resource hungry. This not only means creating extra server load; it also means creating peak load on the CPU and disk drives at the times when you parse logs, which can degrade server response time for users (or in a worst case can even bring the site down).

To solve this, consider setting up a centralized logging server. All you need for this is another box with UDP port 514 (default) open. To make rsyslogd listen to connections, add the following line to its config file:

$UDPServerRun 514

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

*.*   @HOSTNAME:514

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

Conclusion

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

Indeed, PHP log files are a most powerful tool that can be of tremendous benefit.

Resources

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


Appendix: Reading and Manipulating Log Files in the Unix Shell

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

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

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

This article was originally posted on Toptal

The Vital Guide to React.js Interviewing


Intro

Another wave of evolution in client-side application development is approaching. It involves ES6, the new version of JavaScript, universal applications, functional programming, server-side rendering and a webpack, which is like a task-runner with a jetpack.

Also, React is super hot right now. It is a concise and excellent framework to build performant components. Since we already have all that, how do you find the missing piece — the engineer who will embrace it and build state-of-the-art software for you?

React revolutionized the way we think about apps

React revolutionized the way we think about apps

React Plainly

First things first. In the context of React being marketed as only a views library, and as client-side applications consist of more than just views, React won’t be the only tool that your candidate will use. Still, it is a crucial one. Here are a few screening questions.

Q: What are higher-order components in React?

Broadly speaking, a higher-order component is a wrapper. It is a function which takes a component as its argument and returns a new one. It can be used to extend or modify the behaviour (including the rendered output) of the contained component. Such use of components that change behavior without modifying the underlying class in React is well characterized by the decorator pattern.

The higher-order components are a way to build components using composition. An example use case would be to abstract out pieces of code, which are common to multiple components:

Player.js

import React, {Component, PropTypes} from 'react';

export default class Player extends Component {
  static propTypes = {
    black: PropTypes.bool,
    data: PropTypes.object,
    styles: PropTypes.object
  };

  static defaultProps = {
    black: false,
    data: {
      src: null,
      caption: ''
    },
    styles: {}
  };

  render() {
    const { black, data, styles } = this.props.data;
    return (
      <div className={
        'module-wrapper' +
        (styles ? ' ' + styles : '') +
        (black ? ' module-black' : '')}>
        <section className="player-wrapper video-player-wrapper">
          <video className="player" src={data.src} />
          <p className="player-caption">{data.caption}</p>
        </section>
      </div>
    );
  }
}

Consider this component, which holds a Player but also contains module markup. That markup could be reused for other components. Let’s abstract it, and also allow for passthrough of properties:

Player.js

import React, {Component, PropTypes} from 'react';
import ModuleContainer from './ModuleContainer';

export class PlayerInline extends Component {
  static propTypes = {
    data: PropTypes.object
  };

  static defaultProps = {
    data: {
      src: null,
      caption: ''
    }
  };

  render() {
    const { src, caption } = this.props.data;
    return (
      <section className="player-wrapper video-player-wrapper">
        <video className="player" src={src} />
        <p className="player-caption">{caption}</p>
      </section>
    );
  }
}

const Player = new ModuleContainer(Player);
export default Player;

ModuleContainer.js

import React, {Component, PropTypes} from 'react';

export default function ModuleContainer(Module) {
  return class extends Component {
    static propTypes = {
      black: PropTypes.bool,
      styles: PropTypes.object
    };

    render() {
      const { black, styles } = this.props // eslint-disable-lint
      return (
        <div className={
          'module-wrapper' +
          (styles ? ' ' + styles : '') +
          (black ? ' module-black' : '')
        }>
          <Module {...this.props} />
        </div>
      );
    }
  };
}

Now we can still use the previous way of instantiating Player, no changes here. We can also use the inline player if we prefer. Then the module wrapper markup and props can be used with other modules:

<Player data={playerData} styles={moduleStyles} />

<PlayerInline data={playerData} />

Higher order components are the immediate answer to the design decision of moving away from mix-ins in React for ES6, which was done in early 2015. In fact, higher-order components make for a clearer structure, and they are easier to maintain because they are hierarchical, whereas mix-ins have a bigger chance of conflicting due to a flat structure.

To learn more, check out another example use case of higher order components, with a focus on messaging props. Also check the introduction to the preference of higher-order components over mixins, outlined by Dan Abramov, the author of Redux, and an interesting example of advanced composition using refs by Ben Nadel.

Q: Which components should rely on state, and why?

Having separation of concerns in mind, it seems wise to decouple the presentation from the logic. In the React world, everything is a component. But the components used to present data should not have to obtain that data from an API. The convention is to have presentational (dumb) components stateless, and container components that rely on the state.

That said, the convention is not strict. There is also more than one type of state in React. Despite varying opinions, utilising local state in presentational and especially interactive components does not seem to be a bad practice.

Another distinction is between component classes and stateless function components. Obviously, the latter does not have a state. Speaking of the stateless function components, it is an official recommendation to use them when possible.

Q: What is JSX? How does it work, and why would you use it?

JSX is syntactic sugar for React JavaScript, which makes it easy to write components because it has XML-like syntax. However, JSX is JavaScript and not HTML, and React transforms the JSX syntax to pure JavaScript.

It looks awkward at first sight, although many developers are used to it by now. The main reason to use it is simplicity. Defining even mildly complex structures which will eventually be rendered into HTML can be daunting and repetitive:

React.createElement('ul', { className: 'my-list' }, 
  React.createElement('li', { className: 'list-element' }, 
    React.createElement('a', { className: 'list-anchor', href: 'http://google.com' }, 'Toptal.com'),
    React.createElement('span', { className: 'list-text' }, ' Welcome to the network')
  ),
  React.createElement('li', { className: 'list-element' }, 
    React.createElement('div', { className: 'list-item-content' }, 
      React.createElement(SomeCustomElement, {data: elementData})
    )
  )
);

Versus:

<ul className="my-list">
  <li className="list-element">
    <a className="list-anchor" href="http://toptal.com">Toptal.com</a>
    <span className="link-text"> Welcome to the network</span>
  </li>
  <li className="list-element">
    <div className="list-item-content">
      <SomeCustomElement data={elementData} />
    </div>
  </li>
</ul>

Consider more complex elements navigation components, with multiple nestings. Conciseness is one reason most frameworks have some template engine, and React has JSX.

To learn more, check influential discussion on JSX in the context of container components.

The New Approach to Front-End Development

ES6 (ECMA Script 2015), the new version of JavaScript, was released some time ago. The majority of React materials in the open-source community utilise ES6, and sometimes even ES7. The new version adds in expressiveness to JavaScript and also fixes a few problems of the language. The current standard procedure is to use Babel, which compiles ES6 to ES5. It allows us to write code in ES6, and let it execute correctly on the majority of current browsers as ES5. Therefore, it is crucial that the developer you will hire is proficient with ES6.

Q: What are the new features for functions in ES6?

There are a few, actually. The most prominent is the arrow function expression, which is a concise way of writing anonymous function expressions:

var counterArrow = counter => counter++;
// equivalent to function (counter) { return counter++; }

There is a significant difference. With arrow functions, the this object captures the value of the enclosing scope. So there is no more need to write var that = this.

Another difference is in the way arguments can be defined or passed in. ES6 brings default parameters and rest parameters. Default parameters are a very useful way to set the default value of a parameter when it is not provided in the call. The rest parameters, which have a similar syntax to the spread operator, allow processing an indefinite number of arguments passed to a function in an elegant manner.

var businessLogic = (product, price = 1, ...rest) => {
  product.price = price;
  product.details = rest.map(detail => detail);
};

Q: What are classes in ES6 and React?

ES6 classes provide means to create objects, and actually still rely on prototypal inheritance. They are mostly syntactical sugar, but very handy. However, they are not required for React classes.

React classes are components. They can be defined in one of three ways: using the React.createClass()method, using an ES6 class, or using a function to create stateless function components:

const Counter1 = React.createClass({
  propTypes: {
    count: PropTypes.number
  }

  defaultProps: {
    count: 0
  }

  render: function() {
    return <span>Count: {this.props.count}</span>;
  }
});
class Counter2 extends Component {
  static propTypes = {
    count: PropTypes.number
  }

  static defaultProps = {
    count: 0
  }

  render() {
    return <span>Count: {this.props.count}</span>;
  }
}
function Counter3(props) {
  return <span>Count: {props.count}</span>;
}

Counter3.propTypes = {
  count: PropTypes.number
};

Counter3.defaultProps = {
  count: 0
};

As we previously stated, stateless function components are recommended to use when possible. However, those components are not yet optimised for performance. Consider following GitHub issues in Redux and React to learn more.

Q: What are local, or inline styles, the new trend for styles in web development?

This one is pretty rad. Until now, the declarative CSS always shared a global scope. To add styles to a reusable component, the developer had to choose a namespace carefully. Another thing, sometimes it is hard to work with CSS, because some style had to be computed, and so that single style became an exception. Of course, there is calc(), but it is not always sufficient.

Local styles, sometimes also called referred to as inline styles, solve both these problems. Now it is possible to bind a stylesheet to a component know that they remain local in relation to their scope. The styles will not affect elements out of their scope. If that was not enough, the styles become readily available in JavaScript.

AlertWidget.scss

.alertWidget {
  font-variant: italics;
  border: 1px solid red;
  padding: 13px;
}

.alert {
  font-weight: 700;
  color: red;
}

AlertWidget.js

import React, {PropTypes} from 'react';

function AlertWidget(props) {
  const styles = require('./AlertWidget.scss');
  return (
    

{props.alert}

{props.text}

</div> ); } AlertWidget.propTypes = { alert: PropTypes.text, text: PropTypes.text }; export default AlertWidget;

It may not always be the case all styles have to be local, but it certainly is a very powerful tool. To learn more, check influential introduction to local styles on Medium and discussion on the pros and cons of inline styles on CSS-tricks

React revolutionized the way we think about apps

How Do You State

Applications which encompass more than a single component, especially larger applications, can be difficult to maintain using just local component states. It also feels like a bad practice to put anything more than controller-style logic into React. But do not worry, there are already solutions for that.

Q: What is the application state in React, and what governs the state?

The answer is simple – it is an object which represents the current set of data and other properties of the application. The application state differs from the component local state in the way it can be referred to by multiple components.

Another difference is that the application state should not be changed directly. The only place where it can be updated is a store. Stores govern application state, and also define actions which can be dispatched, such as a result of user interactions.

Most React components should not depend on application scope. It is likely the presentational components should have access to pieces of data, but then that data should be provided to them via properties. In React, the convention is to have only the container elements dispatching actions and referring to the application scope.

Q: So, what tools for governing the state in React are out there?

Handling application state in applications built with React is usually done outside of React. Facebook, who brought us React, also introduced the Flux architecture and just enough of its implementation. The Flux part of the client-side application is where front-end business logic takes place.

React is not tightly coupled with Flux. There is also more than one Flux implementation. In fact, there are many, and there are also other very popular ones which are inspired by Flux. The most popular Flux implementations are Facebook Flux, Reflux and Alt.js. There is also Redux, which is based on Flux principles and many people believe improves on Flux.

These libraries will all get the job done. However, a choice needs to be made and it is crucial for the developer to do it consciously. Some reasonable criteria for making the choice:

  • How popular is the repository? Look for GitHub stars and fork count.
  • Is the framework maintained? Check how many commits were done in the last two weeks. Also, read the author’s notes and the open and closed issue counts.
  • What is the state of the documentation? This one is particularly important, team members can be added or changed but the codebase of your software needs to be clear.
  • How well does the developer know that particular framework?

At the moment of writing this article, Redux is by far the most popular of the bunch. It was also reviewed by the authors of Flux, who agreed that it was excellent work. The documentation is excellent, and there are 30 free short video tutorial lessons by the author. The framework itself is very simple, and most aligned with functional programming paradigms.

Alt.js also has a vibrant community, is highly praised in numerous articles, and has excellent documentation. Alt.js is also a pure Flux implementation. Several other implementations were dropped in favour of the two mentioned.

Here’s an article on the different Flux implementations by Dan Abramov, the author of Redux

Q: What is the unidirectional data flow? What benefits does it bring?

The unidirectional data flow constitutes that all changes to the application state are done in the same general way. That flow follows a similar pattern in Flux implementations, as well as in Redux. The pattern starts with an action, which is dispatched and processed by the stores and has the effect of an updated state, which in turn results in updated views.

By following that pattern, applications which govern their state with Flux or Redux are predictable and normalised. Every state version is a result of calling a set of actions. That means that it is now easier to reproduce every user experience by monitoring which actions were dispatched. A useful example is this article about logging and replaying user actions with Flux on Auth0.

It is also extremely helpful when debugging. In fact, one of the most popular frameworks inspired by Flux, Redux, was created as a side effect of creating a new set of developer tools which themselves rely on Flux concepts. There is a speech to it, called “Hot Reloading with Time Travel”, by Dan Abramov.

Miscellaneous

There are many approaches to programming, and also to software engineering in general. The programming paradigms differ far beyond the style. Recently, there are many mentions of functional programming in JavaScript. There are many advantages awaiting for the developers who seek to embrace it.

Q: Explain the functional programming paradigm.

Functional programming is a paradigm, which stresses on:

  • Writing pure functions.
  • Not having a global state.
  • Not mutating data.
  • Composition with higher-order functions.

Pure functions do not produce side-effects, and also are idempotent, meaning they always return the same value when given the same arguments.

Programs which rely on functional programming have two major advantages. They are easy to understand, and also easy to test. In contrast, assigning variables to the global scope, relying on events, and mutating data makes it very easy for the application to become chaotic. From a JavaScript developer’s perspective, I would even say it is overly easy to end up with code which is difficult to understand and prone to errors.

JavaScript is not a strictly functional language. However, with functions as first-class citizens, which means that they can be assigned and passed around just like other types and are composable, it is certainly possible to embrace functional programming for JavaScript developers.

There are many recent articles that praise this style. Still, what seems to be most important are the new tools, which become very popular very quickly. The tools incorporate the key functional programming ideas in various degrees, and include Redux, recent updates to React, and also others like Bacon.js.

Q: How to incline towards functional programming in React?

Primarily, writing React code is mostly focused on writing good JavaScript code. The general way of writing functional programming in JavaScript would be to keep a consistent style of programming, focused on:

  • Writing pure functions.
  • Keeping the functions small.
  • Always returning a value.
  • Composing functions (utilising higher order functions).
  • Never mutating data.
  • Not producing side effects.

There are many tools in JavaScript which are suited for functional programming, among others: .map(), .reduce(), .filter(), .concat. There are also new ES6 features available, like native promises or the …spread operator.

Also, there are available linters, like eslint in particular, combined with linter configurations based on the Airbnb JavaScript and React style guides. There are also other tools, like immutable.js and code patterns like deepFreeze function, which help prevent the data from mutating which is particularly valuable in tests.

React version 0.14 introduced stateless function components, which are a step towards functional programming from object-oriented programming. Those components are minimal, and should be used when possible. Generally, the vast majority of components in React applications should be presentational.

Using Redux is yet another step in functional programming direction. Redux uses function calls, unlike Flux which relies on events. All Redux reducers are also pure functions. Redux never mutates the application state. Instead, the reducers always return a new state.

Q: How to test React applications?

Last but not least comes the developer’s approach to testing. Regression issues are the ultimate source of frustration. Besides allowing the developer and the client to be assured that the application is working as expected, the tests are the remedy for regression issues.

Building a continuous integration or deployment environment in which every pushed commit is automatically tested, and if successful is deployed, has become a standard these days. It is very easy to set up, with free plans on many SaaS. Codeship for example, has good integrations and a free plan. Another good example is Travis CI which delivers a more stable and mature feeling, and is free for open source projects.

There also have to be actual tests to run. Tests are usually written using some framework. Facebook provided a testing framework for React, it is called Jest, and is based on the popular Jasmine. Another industry standard and a more flexible one is Mocha, often combined with the test runner Karma.

React provides another super feature, the TestUtils. Those provide a full quiver of tools, built specifically for testing the components. They create an abstraction instead of inserting the components into an actual page, which allows to compile and test components using unit tests.

To get more insight into testing React applications, you can read on our blog. I also recommend watching the materials available at egghead.io, where there are some series addressing React, and also Flux and Redux, and even a series with a focus on testing React applications.

Conclusion

React brings high performance to client-side apps, and aligns projects which use it in a good position. The library is widely used, and has a vibrant community. Most often, turning to React, also requires the inclusion of other tools to deliver complete apps. Sometimes, it may call for a more general technology upgrade.

Web development is known to evolve at a very fast pace. New tools gain popularity, become valuable and ready to use within months. The innovations encompass more than just the tools, and often span to the code style, application structure and also system architecture. Front-end developers are expected to build reliable software and to optimize the process. The best are open-minded, and state sound arguments with confidence. Toptal engineers are also able lead teams and projects, and introduce new technology for the benefit of the products.

This article originally appeared on Toptal

Tips & Tricks for a Successful Online Portfolio


Our friends at Toptal screen a lot of designers, so over time we have learned what goes into making a captivating and coherent portfolio. Each designer’s portfolio is like an introduction to an individual designer’s skill set and strengths and represents them to future employers, clients and other designers. It shows both past work, but also future direction. There are several things to keep in mind when building a portfolio, so here is the Toptal Guide of tips and common mistakes for portfolio design.

1. Content Comes First

The main use of the portfolio is to present your design work. Thus, the content should inform the layout and composition of the document. Consider what kind of work you have, and how it might be best presented. A UX designer may require a series of animations to describe a set of actions, whereas the visual designer may prefer spreads of full images.

The portfolio design itself is an opportunity to display your experiences and skills. However, excessive graphic flourishes shouldn’t impede the legibility of the content. Instead, consider how the backgrounds of your portfolio can augment or enhance your work. The use of similar colors as the content in the background will enhance the details of your project. Lighter content will stand out against dark backgrounds. Legibility is critical, so ensure that your portfolio can be experienced in any medium, and considers all accessibility issues such as color palettes and readability.

You should approach your portfolio in the same manner you would any project. What is the goal here? Present it in a way that makes sense to viewers who are not essentially visually savvy. Edit out projects that may be unnecessary. Your portfolio should essentially be a taster of what you can do, a preparation for the client of what to expect to see more of in the interview. The more efficiently that you can communicate who you are as a designer, the better.

2. Consider Your Target Audience

A portfolio for a client should likely be different than a portfolio shown to a blog editor, or an art director. Your professional portfolio should always cater to your target audience. Edit it accordingly. If your client needs branding, then focus on your branding work. If your client needs UX Strategy than make sure to showcase your process.

Even from client to client, or project to project your portfolio will need tweaking. If you often float between several design disciplines, as many designers do, it would be useful to curate a print designer portfolio separately from a UX or visual design portfolio.

3. Tell the Stories of Your Projects

As the design industry has evolved, so have our clients, and their appreciation for our expertise and what they hire us to do. Our process is often as interesting and important to share with them, as the final deliverables. Try to tell the story of your product backwards, from final end point through to the early stages of the design process. Share your sketches, your wireframes, your user journeys, user personas, and so on.

Showing your process allows the reader to understand how you think and work through problems. Consider this an additional opportunity to show that you have an efficient and scalable process..

4. Be Professional in Your Presentation

Attention to detail, both in textual and design content are important aspects of any visual presentation, so keep an eye on alignment, image compression, embedded fonts and other elements, as you would any project. The careful treatment of your portfolio should reflect how you will handle your client’s work.

With any presentation, your choice of typeface will impact the impression you give, so do research the meaning behind a font family, and when in doubt, ask your typography savvy friends for advice.

5. Words Are As Important As Work

Any designer should be able to discuss their projects as avidly as they can design them. Therefore your copywriting is essential. True, your work is the main draw of the portfolio – however the text, and how you write about your work can give viewers insight into your portfolio.

Not everyone who sees your work comes from a creative, or visual industry. Thus, the descriptive text that you provide for images is essential. At the earlier stages of a project, where UX is the main focus, often you will need to complement your process with clearly defined content, both visual diagrams, and textual explanation.

Text can also be important for providing the context of the project. Often much of your work is done in the background, so why not present it somehow? What was the brief, how did the project come about?

Avoid These Common Mistakes

The culture of the portfolio networks like Behance or Dribble have cultivated many bad habits and trends in portfolio design. A popular trend is the perspective view of a product on a device. However, these images often do little to effectively represent the project, and hide details and content. Clients need to see what you have worked on before, with the most logical visualisation possible. Showcasing your products in a frontal view, with an “above the fold” approach often makes more sense to the non-visual user. Usually, the best web pages and other digital content are presented with no scrolling required. Avoid sending your website portfolio as one long strip, as this is only appropriate for communicating with developers.

Ensure that you cover the bases on all portfolio formats. Today it is expected for you to have an online presence, however some clients prefer that you send a classic A4 or US letterhead sized PDF. You need to have the content ready for any type of presentation.

Try to use a consistent presentation style and content throughout the projects in your portfolio. Differentiate each project with simple solutions like different coloured backgrounds, or textures, yet within the same language.

Source: Toptal

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.

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 withthis tutorial or study theofficial 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 theProgress 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 yourinputs 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 demohere 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?


This post originally appeared on toptal.com

The 10 Most Common Mistakes That WordPress Developers Make


We are only human, and one of the traits of being a human is that we make mistakes. On the other hand, we are also self-correcting, meaning we tend to learn from our mistakes and hopefully are thereby able to avoid making the same ones twice. A lot of the mistakes I have made in the WordPress realm originate from trying to save time when implementing solutions. However, these would typically rear their heads down the road when issues would crop up as a result of this approach. Making mistakes is inevitable. However, learning from other people’s oversights (and your own of course!) is a road you should proactively take.

WordPress

Engineers look like superheroes, but we’re still human. Learn from us.

Common Mistake #1: Keeping the Debugging Off

Why should I use debugging when my code is working fine? Debugging is a feature built into WordPress that will cause all PHP errors, warnings, and notices (about deprecated functions, etc.) to be displayed. When debugging is turned off, there may be important warnings or notices being generated that we never see, but which might cause issues later if we don’t deal with them in time. We want our code to play nicely with all the other elements of our site. So, when adding any new custom code to WordPress, you should always do your development work with debugging turned on (but make sure to turn it off before deploying the site to production!).

To enable this feature, you’ll need to edit the wp-config.php file in the root directory of your WordPress install. Here is a snippet of a typical file:

// Enable debugging
define('WP_DEBUG', true);

// Log all errors to a text file located at /wp-content/debug.log
define('WP_DEBUG_LOG', true);

// Don’t display error messages write them to the log file /wp-content/debug.log
define('WP_DEBUG_DISPLAY', false);

// Ensure all PHP errors are written to the log file and not displayed on screen
@ini_set('display_errors', 0);

This is not an exhaustive list of configuration options that can be used, but this suggested setup should be sufficient for most debugging needs.

Common Mistake #2: Adding Scripts and Styles Using wp_head Hook

What is wrong with adding the scripts into my header template? WordPress already includes a plethora ofpopular scripts. Still, many developers will add additional scripts using the wp_head hook. This can result in the same script, but a different version, being loaded multiple times.

Enqueuing here comes to the rescue, which is the WordPress friendly way of adding scripts and styles to our website. We use enqueuing to prevent plugin conflicts and handle any dependencies a script might have. This is achieved by using the inbuilt functions wp_enqueue_script or wp_enqueue_style to enqueue scripts and styles respectively. The main difference between the two functions is that with wp_enqueue_script we have an additional parameter that allows us to move the script into the footer of the page.

wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false )
wp_enqueue_script( $handle, $src = false, $deps = array(), $ver = false, $in_footer = false )

wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' )
wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = 'all' )

If the script is not required to render content above the fold, we can safely move it to the footer to make sure the content above the fold loads quickly. It’s good practice to register the script first before enqueuing it, as this allows others to deregister your script via the handle in their own plugins, without modifying the core code of your plugin. In addition to this, if the handle of a registered script is listed in the array of dependencies of another script that has been enqueued, that script will automatically be loaded prior to loading that highlighted enqueued script.

Common Mistake #3: Avoiding Child Themes and Modifying WordPress Core Files

Always create a child theme if you plan on modifying a theme. Some developers will make changes to the parent theme files only to discover after an upgrade to the theme that their changes have been overwritten and lost forever.

To create a child theme, place a style.css file in a subdirectory of the child theme’s folder, with the following content:

/*
 Theme Name:   Twenty Sixteen Child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  Twenty Fifteen Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     twentysixteen
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  twenty-sixteen-child
*/

The above example creates a child theme based on the default WordPress theme, Twenty Sixteen. The most important line of this code is the one containing the word “Template” which must match the directory name of the parent theme you are cloning the child from.

The same principles apply to WordPress core files: Don’t take the easy route by modifying the core files. Put in that extra bit of effort by employing WordPress pluggable functions and filters to prevent your changes from being overwritten after a WordPress upgrade. Pluggable functions let you override some core functions, but this method is slowly being phased out and replaced with filters. Filters achieve the same end result and are inserted at the end of WordPress functions to allow their output to be modified. A trick is always to wrap your functions with if ( !function_exists() ) when using pluggable functions since multiple plugins trying to override the same pluggable function without this wrapper will produce a fatal error.

Common Mistake #4: Hardcoding Values

Often it looks quicker to just hardcode a value (such as a URL) somewhere in the code, but the time spent down the road debugging and rectifying issues that arise as a result of this is far greater. By using the corresponding function to generate the desired output dynamically, we greatly simplify subsequent maintenance and debugging of our code. For example, if you migrate your site from a test environment to production with hardcoded URLs, all of a sudden you’ll notice your site it is not working. This is why we should employ functions, like the one listed below, for generating file paths and links:

// Get child theme directory uri
stylesheet_directory_uri();
//  Get parent theme directory
get_template_directory_uri();
// Retrieves url for the current site
 site_url();

Another bad example of hardcoding is when writing custom queries. For example, as a security measure, we change the default WordPress datatable prefix from wp_ to something a little more unique, like wp743_. Our queries will fail if we ever move the WordPress install, as the table prefixes can change between environments. To prevent this from happening, we can reference the table properties of the wpdb class:

global $wpdb;
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );

Notice how I am not using the value wp_users for the table name, but instead, I’m letting WordPress work it out. Using these properties for generating the table names will help ensure that we return the correct results.

Common Mistake #5: Not Stopping Your Site From Being Indexed

Why wouldn’t I want search engines to index my site? Indexing is good, right? Well, when building a website, you don’t want search engines to index your site until you have finished building it and have established a permalink structure. Furthermore, if you have a staging server where you test site upgrades, you don’t want search engines like Google indexing these duplicate pages. When there are multiple pieces of indistinguishable content, it is difficult for search engines to decide which version is more relevant to a search query. Search engines will in such cases penalize sites with duplicate content, and your site will suffer in search rankings as a result of this.

As shown below, WordPress Reading Settings has a checkbox that reads “Discourage search engines from indexing this site”, although this does have an important-to-note underneath stating that “It is up to search engines to honor this request”.

WordPress Reading Settings

Bear in mind that search engines often do not honor this request. Therefore, if you want to reliably prevent search engines from indexing your site, edit your .htaccess file and insert the following line:

Header set X-Robots-Tag "noindex, nofollow"

Common Mistake #6: Not Checking if a Plugin is Active

Why should I check if a plugin function exists if my plugin is always switched on? For sure, 99% of the time your plugin will be active. However, what about that 1% of the time when for some reason it has been deactivated? If and when this occurs, your website will probably display some ugly PHP errors. To prevent this, we can check to see if the plugin is active before we call its functions. If the plugin function is being called via the front-end, we need to include the plugin.php library in order to call the function is_plugin_active():

include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'plugin-folder/plugin-main-file.php' ) ) {
// Run plugin code
}

This technique is usually quite reliable. However, there could be instances where the author has changed the main plugin directory name. A more robust method would be to check for the existence of a class in the plugin:

if( class_exists( ‘WooCommerce’ ) ) {
	// The plugin WooCommerce is turned on
}

Authors are less likely to change the name of a plugin’s class, so I would generally recommend using this method.

Common Mistake #7: Loading Too Many Resources

Why should we be selective in loading plugin resources for pages? There is no valid reason to load styles and scripts for a plugin if that plugin is not used on the page that the user has navigated to. By only loading plugin files when necessary, we can reduce our page loading time, which will result in an improved end user experience. Take, for example, a WooCommerce site, where we only want the plugin to be loaded on our shopping pages. In such a case, we can selectively remove any files from being loaded on all the other sites pages to reduce bloating. We can add the following code to the theme or plugin’s functions.php file:

function load_woo_scripts_styles(){
	
if( function_exists( 'is_woocommerce' ) ){
    // Only load styles/scripts on Woocommerce pages   
	if(! is_woocommerce() && ! is_cart() && ! is_checkout() ) { 		
		
		// Dequeue scripts.
		wp_dequeue_script('woocommerce'); 
		wp_dequeue_script('wc-add-to-cart'); 
		wp_dequeue_script('wc-cart-fragments');
		
		// Dequeue styles.	
		wp_dequeue_style('woocommerce-general'); 
		wp_dequeue_style('woocommerce-layout'); 
		wp_dequeue_style('woocommerce-smallscreen'); 
			
		}
	}	
}

add_action( 'wp_enqueue_scripts', 'load_woo_scripts_styles');

Scripts can be removed with the function wp_dequeue_script($handle) via the handle with which they were registered. Similarly, wp_dequeue_style($handle) will prevent stylesheets from being loaded. However, if this is too challenging for you to implement, you can install the Plugin Organizer that provides the ability to load plugins selectively based on certain criteria, such as a post type or page name. It’s a good idea to disable any caching plugins, like W3Cache, that you may have switched on to stop you from having to refresh the cache constantly to reflect any changes you have made.

Common Mistake #8: Keeping the Admin Bar

Can’t I just leave the WordPress Admin Bar visible for everyone? Well, yes, you could allow your users access to the admin pages. However, these pages very often do not visually integrate with your chosen theme and don’t provide a seamless integration. If you want your site to look professional, you should disable the Admin Bar and provide a front-end account management page of your own:

add_action('after_setup_theme', 'remove_admin_bar');

function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
  show_admin_bar(false);
}
}

The above code, when copied into your theme’s functions.php file will only display the Admin Bar for administrators of the site. You can add any of the WordPress user roles or capabilities into the current_user_can($capability) function to exclude users from seeing the admin bar.

Common Mistake #9: Not Utilizing the GetText Filter

I can use CSS or JavaScript to change the label of a button, what’s wrong with that? Well, yes, you can. However, you’re adding superfluous code and extra time to render the button, when you can instead use one of the handiest filters in WordPress, called gettext. In conjunction with a plugin’s textdomain, a unique identifier that ensures WordPress can distinguish between all loaded translations, we can employ the gettextfilter to modify the text before the page is rendered. If you search the source code for the function load_plugin_textdomain($domain), it will give you the domain name we need to override the text in question. Any reputable plugin will ensure that the textdomain for a plugin is set on initialization of the plugin. If it’s some text in a theme that you want to change, search for the load_theme_textdomain($domain) line of code. Using WooCommerce once again as an example, we can change the text that appears for the “Related Products” heading. Insert the following code into your theme’s functions.php file:

function translate_string( $translated_text, $untranslated_text, $domain ) {
	if ( $translated_text == 'Related Products') {
			$translated_text = __( 'Other Great Products', 'woocommerce' );
	}
	return $translated_text;
}

add_filter( 'gettext', 'translate_string', 15, 3 );

This filter hook is applied to the translated text by the internationalization functions __() and _e(), as long as the textdomain is set via the aforementioned functions.

_e( 'Related Products', 'woocommerce' );

Search your plugins for these internationalization functions to see what other strings you can customize.

By default, WordPress uses a query string with the post’s ID to return the specified content. However, this is not user-friendly and users may remove pertinent parts of the URL when copying it. More importantly, these default permalinks do not use a search engine friendly structure. Enabling what we call “pretty” permalinks will ensure our URLs contain relevant keywords from the post title to improve performance in search engine rankings. It can be quite a daunting task having to retrospectively modify your permalinks, especially if your site has been running for a significant period of time, and you’ve got hundreds of posts already indexed by search engines. So after you’ve installed WordPress, ensure you promptly change your permalinks structure to something a little more search engine friendly than just a post ID. I generally use the post name for the majority of sites I build, but you can customize the permalink to whatever format you like using the availablepermalink structure tags.

WordPress Permalink Settings

Conclusion

This article is by no means an exhaustive list of mistakes made by WordPress developers. If there’s one thing you should take away from this article, though, it’s that you should never take shortcuts (and that’s true in any development platform, not just in WordPress!). Time saved now by poor programming practices will come back to haunt you later. Feel free to share with us some mistakes that you have made in the past – and more importantly any lessons learned – by leaving a comment below.

Source: Toptal

Guide to Showcasing Sketch and Photoshop Skills in Your Portfolio


Both Sketch and Photoshop are great tools used by almost every designer to accomplish a huge variety of tasks. To Photoshop has even become a dictionary verb. It doesn’t come as a surprise that most clients will expect a designer to have a high level of Sketch and Photoshop expertise. The majority of Toptal design jobs have either Sketch or Photoshop listed as one of their main required software. All of this is probably making you want to demonstrate your Sketch and Photoshop mastery throughout your portfolio.

Before proceeding, keep in mind that both Sketch and Photoshop are just tools and although tools do not make great designers, being a master of the tool gives the ability to execute your ideas professionally and efficiently.

So, how do you showcase that you are a Sketch or Photoshop expert in your portfolio? It mostly depends on the kind of design work you mainly use either program for.

You do visuals, photo manipulation and illustration

If the focus of your design work is in the creation of visuals, illustration, photo manipulation and photo editing in Photoshop, you’ll want that to shine from your portfolio. When deciding which projects to showcase in the portfolio be sure to choose only your best work and try not to be repetitive. There might be some clients that fall in love with your unique style but often clients prefer designers who can adapt to different styles and trends.

Choose work that demonstrates your mastery in detailed visual compositions, combining various layers, masks and advanced blending and some other qualities that demonstrate your proficiency with using light and shadow. Show that you understand perspective. Include an example that illustrates how immaculately you manage colors. In addition to showing complete visuals or illustrations put some emphasis on perfectly crafted details and make a few close-ups of the most interesting details that really demonstrate your perfection. Share your work process in the portfolio, give some sketches, display how raw materials looked like and what you’ve accomplished to make out of them. If it’s appropriate to showcase photo editing skills, put in some before and after the visuals.

You are the branding expert

While developing the visual identity as a part of a branding project you preferably won’t use Photoshop as your main tool of choice but one of the vector tools such as Illustrator. However, Photoshop will come in handy to visualize how that identity (logo, chosen colors palette, and typography) will work and look on stationary, signage, visual identity guidelines, website, apps and other additional advertising materials.

To showcase your branding project at its best, the first step you’ll need to do is to find or make some 3D mockup templates. Be careful to choose ones that won’t interfere with work that you are primarily showing, but instead, choose ones that will put emphasis on its best features. Avoid weird perspectives, too many distractions in the form of surrounding objects, colors, patterns.

Remember that you are showcasing your branding capabilities to prospective clients and not trying to sell them good looking mockups, especially if you haven’t made them by yourself. If you are buying or using some free templates be sure they are of quality. When applying your work inside a mockup, give attention to details, align everything perfectly, take care that there are no pixels hanging around.

Double check that you are putting your pages or screens in the right perspective, that lighting, white balance and shades are all adjusted and that nothing looks pixelated or distorted. Keep in mind that the scene you are building must look like a real one and although it might not be noticed at the first glance some inconsistencies could signify to a potential client that you are not giving enough attention to details or that you are not so versed in Photoshop.

You are a web or UI designer

Photoshop was not developed for web and user interface visual design, but since no completely corresponding tool existed at the time, most web designers were using it as their primary tool. With the adoption of responsive design and the arrival of more appropriate tools and workflows developed specifically for web and user interface design, Photoshop lost its web design tool throne. There are still some designers, especially those not working on Macs that use Photoshop, but Sketch is now the leader in the field.

If you are working as a web or user interface designer, no matter which tool you use you’ll want to show your proficiency and effectiveness in it and that could hardly be accomplished without revealing your process. High-quality visuals can be produced even if you are not a master of your tools, but glancing through your work files and workflow can show potential clients and collaborators that you are one. That is the reason for showing and describing in your portfolio how you use grids, artboards, structure your layers, and deal with Sketch symbols or Adobe CC libraries, handle typography and styles. Show some close-ups that will place emphasis on your attention to detail. If you craft your pixel-perfect icons and other elements in Sketch, display them with pride.

When choosing mockups in which to present web design or UI work stick with ones that won’t interfere with your designs. Let them be clear, without any unnecessary clutter. If using 3D perspective views, be sure that your work, which is core content of your portfolio, is shown in a way all important components are visible and understandable and there are no perspective distortions.

No matter what, take care of this

If you claim to be a Sketch or Photoshop expert, be sure that all your portfolio projects and presentations look professional. Some minor details, like the wrong direction of a shadow, or any pixelation might show a well-trained eye that your design skills are weak or that you lack the ability to polish your projects up to the last detail.

Be sure that all pictures you are putting in a portfolio are sharp and that nothing is pixelated, posterized or distorted. All elements in photomontages should blend seamlessly, and perspectives of different elements must be aligned and lighting effects, shadows and white balance in compliance.

Remember also that although the presentation of projects in your portfolio is very important, and can be a good means of showing your Photoshop skills, don’t let it become more important than the work itself. If by looking at your portfolio, one is more aware of the presentation than the content, be sure that something went wrong and reconsider rebuilding the portfolio around your best projects.

Source: Toptal

Guide to Building a Top UI Design Portfolio


Writer’s Note: This is the 2nd of a series of portfolio guides that aims to help those among our readers with the skill set that is featured.

Before We Begin

Professionals who work in the creative industry need portfolios to showcase their skills to attract clients and peers. Once upon a time this was solved by creating stunning printed pieces. However, no matter how you look at it, times have changed and designers are no longer just designers. We’ve got different specialties that cover many different fields within design. It’s important that you identify your strengths before starting to build your own portfolio.

Today we will cover all the bases that lead to the creation of an amazing User Interface Portfolio, so if this happens to be your specialization, keep reading!

Quality and Quantity

Take the creation of your portfolio as any other important project you would work on and start by picking the number of products or projects you would like to showcase. Think of a number that can cover all of what you can do from the point of view of a UI designer, that can be enough to represent you as the perfect candidate for the next big contract and not a lot to turn your portfolio into an overwhelming and never ending trip for your future clients. Edit your selection with a sharp eye, as you will be judged by your worst piece.

Picking up to 9 projects is more than enough to show a variety of pieces, however, if that would be too many for what you would like to show in your portfolio then don’t worry, as 6 is also an acceptable number of projects to offer.

We all know working on a portfolio can feel endless because it’s hard for us as designers to objectively select the best work. However, the sooner you publish your portfolio, the faster your work will be ready for potential clients to see. Set realistic deadlines for every step of the process: from the very beginning, to when you pick your projects, through to its publication.

What About the Target?

This will mainly depend on you: are you a UI designer focusing on gaming? How about a UI designer specialized in designing mobile apps? Maybe you do both plus more! Each of them has a different solution but these tips are applicable to all UI cases.

Benchmark

A little research has never truly hurt anyone and it’s useful to see what kinds of portfolios are out there, what trends you should avoid for your portfolio to not look the same as everyone else’s, and what details are definitely worth exploring to apply to your own presentation. Inspiration is your best friend when you’re starting to build something from scratch.

Awwwards is a good place to look for web-based portfolios and some users at Dribbble offer more on their profiles to a web portfolio than you might think.

Of course, learning from your fellow colleagues on Toptal is always a good idea, there are stunning portfolios out there for you to check out!

The Three Pillars

There are three things that should be kept in mind throughout the process of building a UI portfolio: remember the importance of the visuals, have a solid process and show the result of each project by telling a story. Be as specific as you want yet keep an equilibrium between all three of them.

While it’s important to pay attention to details and UI designers focus mainly on those, it’s vital for your pieces to be “more than just a pretty face.” UI designers mostly work with UX designers to achieve incredible products, or sometimes hybrid designers do both UX and UI at the same time. Therefore it’s key to keep the essence of your designs by having some storytelling on every single page and by dodging the commonly known “Dribbblisation of Design” which will differentiate you from regular designers.

Layouts & Styles

The recommended size for portfolios nowadays are:

  • A4 Horizontal, the width will benefit the amount of content you can show
  • Sizes that are always larger in width and no smaller than 1280x800px

Note: Most devices nowadays allow retina images which will make your images look sharper and better. Remember to upload them twice their original size with @2x.

When thinking of the kind of layout you should design for each product, keep in mind that most of your projects will be different and will have a particular style that makes them unique: this will help you with the previously mentioned storytelling. Start from beginning to end, or backward; the possibilities are endless as long as you keep coherence on every single page.

Think of the most eye-catching cover page for each project. Whether it’s the logo of the product with a color background, a mobile product displayed in a beautiful mockup, or the interface of a video game close up, all of them can work as long as you keep the visual noise to a minimum. Clients have only a few minutes per page to spare on your portfolio so it’s important to show and tell as much as possible in a clean and organized way.

Don’t be afraid to put two or three dispositive together for a cover page as it will show how adaptable and dynamic your product is and will also tell the client beforehand how much content they can expect from a project.

Be Meticulous

We live and breathe visuals so we can’t afford to have pixelated rounded corners on a mockup, different screen sizes or slightly different alignments for the same product.

Keep in mind:

  • The alignment of your mockups or screens should be the same as not to generate a slight jump between one page and another. Make sure to check alignments on Y and X.
  • Work with vector images. If you’re using Sketch, it’s quite handy to have mockups that can be scalable and will never look pixilated; use the “scale” option instead of manually scaling your mockup, as it will lose its shape. If you happen to be using Photoshop, on the other hand, scale your mockup and use Command + Z (or Control + Z on a PC) to go back and scale again, as every time you scale your image it will get more and more pixelated.
  • Check for details once you’re done with the general alignment of your objects by working with zoom. This will help you discard any lines or shapes that are slightly out of place.
  • If you’re using mockups for mobile or tablets, there are two ways to go regarding the top bar: if you wish to keep it, make sure the battery is on a 100% charge and that the carrier shows a real company, for example, AT&T, T-Mobile, Virgin, among others, because it will give a realistic touch to your product. If you wish to take the top bar away, mobile products usually look better in a rounded container with 2px of radius, without a mockup.
  • The background should always highlight the product you’re trying to show and not turn the client’s view away from it. There are two ways to go about this: 1. either use a plain color background that can make a friendly contrast with your product (keep in mind the mock up’s color and the color scheme of your design altogether) or 2. use a pattern or picture as background but get creative with its opacity and/or add a color layer on top with some transparency. Once again, the options are endless as long as the background is always secondary.
  • For web pages or landing pages, you can go ahead and divide them into three pages to allow for a smooth tour through each portion. Making it small and placing them into a single page would make the client miss key points and details that will differentiate your product from others.

The Process

It doesn’t matter whether you do UX, UI or a complete different specialization within design: it’s always important to show that your work had a process and that it didn’t just magically appear. Don’t be shy to include rough sketches, the good old technique of paper and pencil, collage or even photography that could have helped you in the thought process of building outstanding UI for your product.

Depending how you want to go to your portfolio, there are different ways and techniques to show these sketches:

  • The simplest method is to scan your sketches and make good use of Photoshop to handle levels, contrast, and brightness before using them in the correct size (not too big nor too small). Depending what you want to show with these sketches, they can all be on the same page spread everywhere or more organized, selecting just a few of the most polished ones.
  • If you got inspired by particular objects, taking photographs from above at a 90° angle would show the object in a real size and it’s a trend that’s been quite useful as of lately (be careful of any shadows over your object!). If your object isn’t as flattering at that angle, however, using non-conventional angles like diagonals could help give the photograph more movement.
  • Other tips regarding photography: 1. make sure the photograph is not blurry and that there aren’t other items creating noise or disturbing the general picture, and 2. consider properly cutting those objects and placing them over solid color backgrounds or alternatively create a scenario that serves as context. For both cases, do check contrasts, brightness, and levels as we don’t want it to be too bright or too dark.
  • Collages, paintings or experimentation over a paper with different items like brushes, pens or watercolor pencils can also be scanned or photographed. It mostly depends on what is important to show for each project, and what experiences are important for our client to have when they’re taking a look at those pages.

Storytelling

This is your work process and the way you show it will depend on what kind of projects you’ve worked on. If your main focus is iconography, showing rough sketches and a step-by-step process through to the final form are recommended. If you’re focusing on mobile products instead, screens that are connected to one another to show a feature can also tell a story, and initial sketches of the interface itself are always helpful as well.

Consistency and coherence are important to tell a story no matter how you want to show it. And even though each product will have its own unique style there is a rhythm that will guide your client’s eyes through each page.

Recap

To summarize everything, remember to:

  1. Keep in mind your target which will probably depend on your specialization as a UI Designer.
  2. Pick reasonable numbers of pages for your portfolio that can showcase the kind of professional you are.
  3. Do some benchmark; research has never hurt anyone.
  4. Set realistic deadlines, and treat your portfolio building as another project.
  5. Whatever you do, don’t forget about visuals, including written details and your work process. If there’s something a UI Designer can stand out in, it is by being quite meticulous with details.
  6. You live and breathe visuals but storytelling is just as important to differentiate you from regular designers who fall into the “Dribbblisation of Design” category.
  7. Be coherent and consistent with your style through every part of your portfolio.

Last but not least: have fun! Your portfolio, whether UI, UX or any other kind, should show not only how capable you are as a professional but also part of your personality and that you have a unique voice and style to offer.

Source: Toptal

Guide to Building a Top Web Design Portfolio


Writer’s Note: This is the first of a series of portfolio guides that aims to help those among our readers with the skill set that is featured.

A portfolio is a very important link between a designer and a client. It aims to impress a potential client by showing the designer’s work and skills. At Toptal, we screen a lot of web designers and review a lot of portfolios. Creating a top web design portfolio is by no means easy, even for experienced designers. We’re sharing our tips to help you create a top portfolio.

1. Content Is King

Most web designers are no strangers to the concept of content first. Content is king in web design, so why not apply that same concept to your portfolio? Make content the star of the show and focus on the quality of the message you are trying to get across. Try to avoid eye candy in the images you use and concentrate on engaging potential customers through the statement you are making. This is not to say you should neglect the images — after all, they will without a doubt attract clients and open a few doors — but the copy is likely to make you the ideal candidate for a job. Without great copy, there’s no top portfolio. As a result, you might easily appear less professional and the client could choose a different designer. Well-written content is your best chance to communicate your skills and expertise and sell your work to a future employer.

2. Take Your Target Audience Into Account

Another well-known web design strategy is not to think of yourself (the web designer) as the user. As you would with a web design project, think of your target audience and their wants, needs, and possible limitations. Put yourself into the shoes of the people who will be viewing your portfolio, find pain points and fix them. Help them understand the message you are sending.

Remember that a portfolio is about projects, so aim to find the right balance and remove everything that gets in a way of a clear, concise message. The goal of a portfolio is to showcase your work to potential clients and impress them. They need to find a quick and easy path to the information they want, so think of a way to provide just that.

3. Tell a Story

Engage potential clients by telling a story. For instance, explaining the process behind a project could come a long way. Showcase not only a finished product but also the way you solve real problems. This will help clients appreciate the time and effort invested behind the scenes and get to know you as a web designer. Explain your role in the project and mention the techniques and technologies used to demonstrate the value of your work. Your skills should be reflected in the images you provide.

If you were a member of a team, mention and promote the success of the entire team and the project, not only your role. Are there some detailed UI problems you solved which you can share? What deliverables were produced and why? Which of the major KPIs can be used to demonstrate project goals and success? Was there a part of the project that was not a success and why was that the case? Try to be objective and honest — not every step of the project is without flaws and no web designer is error free. Honesty might just be the best policy and it might impress clients. While you could do all this in a Skype meeting with a potential employer, why not save yours and their time and tell a story in your portfolio? It’s a definite win-win situation.

4. Don’t Make Your Clients Think

“Don’t make me think” by Steve Krug is one of the most famous web design books and, generally speaking, lessons in web design. Avoid being vague to let clients accomplish their task without hitting roadblocks. Make sure your work, as well as personal and contact information is easy to understand and digest. Present goals, results, and features in a direct and concise, intuitive fashion. If your project is live, make sure to provide a link to the website and let the client discover more. The browser is the natural environment for any website, so it only makes sense to let clients view your project in it. If the project is not online, maybe you can provide a link to a detailed case study, a front-end prototype, or a style guide. This might be your only opportunity to make a lasting impression, so invest extra effort.

5. Be Professional

The final tip may be obvious, but is by no means insignificant: be professional in your presentation. Assure clients you are not willing to gamble with the quality of their projects.

There is a number of ways you can do this. Here are a few:

  • Use spell-check software to avoid spelling errors and come off superficial.
  • Consider specifying the start and end dates to provide additional information and add to the credibility.
  • Optimize images without sacrificing quality — no-one wants to see pixelated images, but no-one wants to wait for them to load, either. After all, we’re web designers and therefore no strangers to image optimizations.
  • Be honest when stating your work experience and job title.
  • Give credit where credit is due. If other agencies and team members were involved in a project, mention them and their role.
  • Select only your strongest portfolio pieces — quality will always win over quantity and you may well be judged by your weakest work.
  • If the project was a success, ask the client for a testimonial and add it to your portfolio.
  • Ask peers for a review to find ways of improving your portfolio.
  • Much like any website, your portfolio is never finished, so remember to update it regularly and keep improving it.

This wraps up our tips for creating a top web design portfolio.

Source: Toptal.

10 Essential WordPress Interview Questions


  1. Consider the following code snippet. Briefly explain what changes it will achieve, who can and cannot view its effects, and at what URL WordPress will make it available.
add_action('admin_menu', 'custom_menu');

function custom_menu(){
    add_menu_page('Custom Menu', 'Custom Menu', 'manage_options', 'custom-menu-slug', 'custom_menu_page_display');
}

function custom_menu_page_display(){
    echo '<h1>Hello World</h1>';
    echo '<p>This is a custom page</p>';
}

With default settings and roles, admins can view it and all lower roles can’t. In fact this menu item will only be visible to users who have the privilege to “manage options” or change settings from WordPress admin dashboard.

The admin custom page will be made available at this (relative) URL: “?page=custom-menu-slug”.

2. How would you change all the occurrences of “Hello” into “Good Morning” in post/page contents, when viewed before 11AM?

In a plugin or in theme functions file, we must create a function that takes text as input, changes it as needed, and returns it. This function must be added as a filter for “the_content”.

It’s important that we put a little effort to address some details:

  • Only change when we have the full isolate substring “hello”. This will prevent words like “Schellong” from becoming “sgood morningng”. To do that we must use “word boundary” anchors in regular expression, putting the word between a pair of “\b”.
  • Keep consistency with the letter case. An easy way to do that is to make the replace case sensitive.
<?php
function replace_hello($the_content){
    if(current_time('G')<=10){
        $the_content=preg_replace('/\bhello\b/','good morning',$the_content);
        $the_content=preg_replace('/\bHello\b/','Good Morning',$the_content);
    }
    return $the_content;
}
add_filter('the_content', 'replace_hello');

3. What is the $wpdb variable in WordPress, and how can you use it to improve the following code?

<?php
function perform_database_action(){
    mysql_query(“INSERT into table_name (col1, col2, col3) VALUES ('$value1','$value2', '$value3');
}

$wpdb is a global variable that contains the WordPress database object. It can be used to perform custom database actions on the WordPress database. It provides the safest means for interacting with the WordPress database.

The code above doesn’t follow WordPress best practices which strongly discourages the use of any mysql_query call. WordPress provides easier and safer solutions through $wpdb.

The above code can be modified to be as follows:

<?php
function perform_database_action(){
    global $wpdb;
    $data= array('col1'=>$value1,'col2'=>$value2,'col3'=>$value3);
    $format = array('%s','%s','%s');
    $wpdb->insert('table_name', $data, $format);
}
add_custom_script();
function add_custom_script(){
    wp_enqueue_script( 
        'jquery-custom-script',
        plugin_dir_url( __FILE__ ).'js/jquery-custom-script.js'
    );
}

wp_enqueue_script is usually used to inject javascript files in HTML.

The script we are trying to queue will not be added, because “add_custom_script()” is called with no hooks. To make this work properly we must use the wp_enqueue_scripts hook. Some other hooks will also work such as init, wp_print_scripts, and wp_head.

Furthermore, since the script seems to be dependent on jQuery, it’s recommended to declare it as such by adding array(‘jquery’) as the 3rd parameter.

Proper use:

add_action(‘wp_enqueue_scripts’, ‘add_custom_script’);
function add_custom_script(){
    wp_enqueue_script( 
        'jquery-custom-script',
        plugin_dir_url( __FILE__ ).'js/jquery-custom-script.js',
        array( 'jquery')
    );
}

5. Assuming we have a file named “wp-content/plugins/hello-world.php” with the following content. What is this missing to be called a plugin and run properly?

<?php
add_filter('the_content', 'hello_world');
function hello_world($content){
    return $content . "<h1> Hello World </h1>";
}

The file is missing the plugin headers. Every plugin should include at least the plugin name in the header with the following syntax:

<?php
/*
Plugin Name: My hello world plugin
*/

6. What is a potential problem in the following snippet of code from a WordPress theme file named “footer.php”?

...
        </section><!—end of body section- ->
        <footer>All rights reserved</footer>
    </body>
</html>

All footer files must call the <?php wp_footer() ?> function, ideally right before the </body> tag. This will insert references to all scripts and stylesheets that have been added by plugins, themes, and WordPress itself to the footer.

7. What is this code for? How can the end user use it?

function new_shortcode($atts, $content = null) {
    extract(shortcode_atts(array(
        “type” => “warning”
    ), $atts));
    return '
'.$content.'
'; } add_shortcode(“warning_box”, “new_shortcode”);

This shortcode allows authors to show an info box in posts or pages where the shortcode itself is added. The HTML code generated is a div with a class name “alert” plus an extra class name by default, “alert-warning”. A parameter can change this second class to change the visual aspect of the alert box.

Those class naming structures are compatible with Bootstrap.

To use this shortcode, the user has to insert the following code within the body of a post or a page:

[warning_box]Warning message[/warning_box]

8. Is WordPress safe from brute force login attempts? If not, how can you prevent such an attack vector?

No, WordPress on its own is vulnerable to brute force login attempts.

Some good examples of actions performed to protect a WordPress installation against brute force are:

  • Do not use the “admin” username, and use strong passwords.
  • Password protect “wp-login.php”.
  • Set up some server-side protections (IP-based restrictions, firewall, Apache/Nginx modules, etc.)
  • Install a plugin to add a captcha, or limit login attempts.

9. The following line is in a function inside a theme’s “function.php” file. What is wrong with this line of code?

wp_enqueue_script('custom-script', '/js/functions.js');

Assuming that “functions.js” file is in the theme’s “js/” folder, we should use ‘get_template_directory_uri()’. '/js/functions.js' or the visitors’ browser will look for the file in the root directory of the website.

10. Suppose you have a non-WordPress PHP website with a WordPress instance in the “/blog/” folder. How can you show a list of the last 3 posts in your non-WordPress pages?

One obvious way is to download, parse, and cache the blog’s RSS feeds. However, since the blog and the website are on the same server, you can use all the WordPress power, even outside it.

The first thing to do is to include the “wp-load.php” file. After which you will be able to perform any WP_Query and use any WordPress function such as get_posts, wp_get_recent_posts, query_posts, and so on.

<?php
    require_once('../blog/wp-load.php');
?>
<h2>Recent Posts</h2>
<ul>
<?php
    $recent_posts = wp_get_recent_posts(array(‘numberposts’=>3));
    foreach($recent_posts as $recent){
        echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"] . '</a></li> ';
    }
?>
</ul>

Source: Toptal