Set Up Routing in PHP Applications Using the Symfony Routing Component

Today, we’ll go through the Symfony Routing component, which allows you to set up routing in your PHP applications.

What Is the Symfony Routing Component?

The Symfony Routing Component is a very popular routing component which is adapted by several frameworks and provides a lot of flexibility should you wish to set up routes in your PHP application.

If you’ve built a custom PHP application and are looking for a feature-rich routing library, the Symfony Routing Component is more than a worth a look. It also allows you to define routes for your application in the YAML format.

Starting with installation and configuration, we’ll go through real-world examples to demonstrate a variety of options the component has for route configuration. In this article, you’ll learn:

  • installation and configuration
  • how to set up basic routes
  • how to load routes from the YAML file
  • how to use the all-in-one router

Installation and Configuration

In this section, we’re going to install the libraries that are required in order to set up routing in your PHP applications. I assume that you’ve installed Composer in your system as we’ll need it to install the necessary libraries that are available on Packagist.

Once you’ve installed Composer, go ahead and install the core Routing component using the following command.

Although the Routing component itself is sufficient to provide comprehensive routing features in your application, we’ll go ahead and install a few other components as well to make our life easier and enrich the existing core routing functionality.

To start with, we’ll go ahead and install the HttpFoundation component, which provides an object-oriented wrapper for PHP global variables and response-related functions. It makes sure that you don’t need to access global variables like $_GET, $_POST and the like directly.

Next, if you want to define your application routes in the YAML file instead of the PHP code, it’s the YAML component that comes to the rescue as it helps you to convert YAML strings to PHP arrays and vice versa.

Finally, we’ll install the Config component, which provides several utility classes to initialize and deal with configuration values defined in the different types of file like YAML, INI, XML, etc. In our case, we’ll use it to load routes from the YAML file.

So that’s the installation part, but how are you supposed to use it? In fact, it’s just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.

Set Up Basic Routes

In the previous section, we went through the installation of the necessary routing components. Now, you’re ready to set up routing in your PHP application right away.

Let’s go ahead and create the basic_routes.php file with the following contents.

Setting up routing using the Symfony Routing component usually goes through a series of steps as listed below.

  • Initialize the Route object for each of your application routes.
  • Add all Route objects to the RouteCollection object.
  • Initialize the RequestContext object which holds the current request context information.
  • Initialize the UrlMatcher object by passing the RouteCollection object and the RequestContext object.

Initialize the Route Object for Different Routes

Let’s go ahead and define a pretty basic foo route.

The first argument of the Route constructor is the URI path, and the second argument is the array of custom attributes that you want to return when this particular route is matched. Typically, it would be a combination of the controller and method that you would like to call when this route is requested.

Next, let’s have a look at the parameterized route.

The above route can match URIs like foo/1, foo/123 and similar. Please note that we’ve restricted the {id} parameter to numeric values only, and hence it won’t match URIs like foo/bar since the {id} parameter is provided as a string.

Add All Route Objects to the RouteCollection Object

The next step is to add route objects that we’ve initialized in the previous section to the RouteCollection object.

As you can see, it’s pretty straightforward as you just need to use the add method of the RouteCollection object to add route objects. The first argument of the add method is the name of the route, and the second argument is the route object itself.

Initialize the RequestContext Object

Next, we need to initialize the RequestContext object, which holds the current request context information. We’ll need this object when we initialize the UrlMatcher object as we’ll go through it in a moment.

Initialize the UrlMatcher Object

Finally, we need to initialize the UrlMatcher object along with routes and context information.

Now, we have everything we could match our routes against.

How to Match Routes

It’s the match method of the UrlMatcher object which allows you to match any route against a set of predefined routes.

The match method takes the URI as its first argument and tries to match it against predefined routes. If the route is found, it returns custom attributes associated with that route. On the other hand, it throws the ResourceNotFoundException exception if there’s no route associated with the current URI.

In our case, we’ve provided the current URI by fetching it from the $context object. So, if you’re accessing the http://your-domain/basic_routes.php/foo URL, the $context->getPathInfo() returns foo, and we’ve already defined a route for the foo URI, so it should return us the following.

Now, let’s go ahead and test the parameterized route by accessing the http://your-domain/basic_routes.php/foo/123 URL.

It worked if you can see that the id parameter is bound with the appropriate value 123.

Next, let’s try to access a non-existent route like http://your-domain/basic_routes.php/unknown-route, and you should see the following message.

So that’s how you can find routes using the match method.

Apart from this, you could also use the Routing component to generate links in your application. Provided RouteCollection and RequestContext objects, the UrlGenerator allows you to build links for specific routes.

The first argument of the generate method is the route name, and the second argument is the array that may contain parameters if it’s the parameterized route. The above code should generate the /basic_routes.php/foo/123 URL.

Load Routes From the YAML File

In the previous section, we built our custom routes using the Route and RouteCollection objects. In fact, the Routing component offers different ways you could choose from to instantiate routes. You could choose from various loaders like YamlFileLoader, XmlFileLoader, and PhpFileLoader.

In this section, we’ll go through the YamlFileLoader loader to see how to load routes from the YAML file.

The Routes YAML File

Go ahead and create the routes.yaml file with the following contents.

An Example File

Next, go ahead and make the load_routes_from_yaml.php file with the following contents.

The only thing that’s different in this case is the way we initialize routes!

We’ve used the YamlFileLoader loader to load routes from the routes.yaml file instead of initializing it directly in the PHP itself. Apart from that, everything is the same and should produce the same results as that of the basic_routes.php file.

The All-in-One Router

Lastly in this section, we’ll go through the Router class, which allows you to set up routing quickly with fewer lines of code.

Go ahead and make the all_in_one_router.php file with the following contents.

Everything is pretty much the same, except that we’ve instantiated the Router object along with the necessary dependencies.

With that in place, you can straight away use the match method of the Router object for route mapping.

Also, you will need to use the getRouteCollection method of the Router object to fetch routes.

Conclusion

Go ahead and explore the other options available in the Routing component—I would love to hear your thoughts!

Today, we explored the Symfony Routing component, which makes implementation of routing in PHP applications a breeze. Along the way, we created a handful of examples to demonstrate various aspects of the Routing component. 

I hope that you’ve enjoyed this article, and feel free to post your thoughts using the feed below!


Source: Nettuts Web Development

Monthly Web Development Update 7/2018: Practical Accessibility, Design Mistakes, And Feature Control

Monthly Web Development Update 7/2018: Practical Accessibility, Design Mistakes, And Feature Control

Monthly Web Development Update 7/2018: Practical Accessibility, Design Mistakes, And Feature Control

Anselm Hannemann

2018-07-13T14:20:17+02:00
2018-07-13T12:33:42+00:00

The web continues to amaze me. With all its variety and different changes to the platform, it’s hard to see a straight pattern — if there even is (just) one. But it’s wonderful to see what is being changed, which features are added to the platform, which ones get deprecated, and how browsers implement more and more technology to protect the user from malicious website attacks. It’s interesting to see that these security features nowadays are getting as much attention as a feature for developers; this shows the importance of privacy and security and how unstable and insecure the web was in the past.

But the best thing about all of this is that it shows how important it is to stick to the things that people give us. Instead of implementing our own solutions for everything, it’s often much better to re-use an existing system. Not only is it safer to rely on, but also less work while more inclusive to extend a native DOM element with a custom element (instead of writing our own custom element from scratch). If we think about whether we should build our own version of SSL or use an existing software for this, why would we build a clickable element based on nothing instead of altering the behavior of an a or button element? And why would we check for resource host validation on our own, if the browser already gives us an API for that? This week’s articles are all dedicated to these topics.

Another thing that has been stuck in my head is Andrea Giammarchi’s article, “A Bloatless Web,” in which he describes how we blindly use Babel as developers when we write JavaScript to be able to write modern ECMAScript. But we usually don’t realize that transpiling all of our modern code in modern browsers isn’t the most efficient way. I’m glad that Andrea offers some ideas on how we can improve that situation and improve our web apps’ performance. Wouldn’t it be amazing to just serve a third of the bundle size by not transpiling the code anymore for each and every browser?

News

  • Site Isolation effectively makes it harder for untrusted websites to access or steal information from your accounts on other websites. Chrome 67 is now shipping with it and Cross-Origin Read Blocking (CORB) will no longer load, e.g. a JSON file as image. But even further, these changes mean that full-page layout is no longer guaranteed to be synchronous. This new feature affects you if you read out calculated sizes from an element in JavaScript or use unload event listeners. Ensure that you know about this and check if your sites still work as expected.
  • By now, we know a bit about Content Security Policies — a feature that lets developers limit the load of certain resources by hostnames. But browser vendors have come up with something new now: Feature Policy. This allows web developers to selectively enable, disable, or modify the behavior of certain APIs and web features in the browser. It’s like CSP but instead of controlling security, it controls features and Eric Bidelman wrote an introduction to Feature Policy explaining everything.
  • The Brave browser team shows their latest feature to protect their users’ privacy: Tabs that connect via the Tor network.

Generic

  • Anton Sten asks if Tech Sector Values are Broken? Analyzing the marketing strategies by Apple, Microsoft, Google, Amazon but also small other companies and how we can do really purposeful work and stick to our values instead of treating them as marketing-material that we don’t need to respect or stick to.
  • Now that the technology sector of the world is rapidly transforming all of the world’s things into digital things, many have called for more ethics in our field. That is in many instances quite a vague goal, so let’s apply it to one part of digital: front-end development. How can we be more ethical as front-end developers, what kinds of things can we do? Hidde de Vries wrote an article about that.

Security

UI/UX


what we design vs. what a user needs
Users do not have time to read more than necessary, and yet designers still tend to put a lot of text because they think people need to know that. (Image source)

Privacy

  • This is an interesting report about how Google allows outside app developers to read people’s Google emails when they grant permission during app authorization. The issue with that is that there is no way to easily prevent that and it might have quite some impact if you use Gmail for your company as it might affect privacy policies and is under subject of GDPR.

Web Performance

  • Max Böck on how we can build components that react to the actual device connection speed using the Network Information API. And despite it’s currently only available in Chrome and Samsung Internet browsers, it’s worth trying it out and maybe already serve it to these users.
  • From time to time, we can still read articles mentioning the importance of optimizing CSS selectors in order to improve performance. This originates in research done several years ago but Ivan Čurić researched this again and found out it doesn’t matter.

Accessibility


A form with color-based indicators
In her article, Sara Novak explains why it’s important not to rely on color alone as an indicator. Symbols and error message can be much more helpful to users. (The image above shows a form with color-based indicators. Left: How a person with normal vision sees a form with color-based indicators. Right: How a deuteranomalous person sees the same form.) (Image source)

JavaScript

CSS

Work & Life

Smashing Editorial
(il)


Source: Smashing Magazine

4 Handpicked Design & Dev Collaboration Tools You Should Know About

This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible.

If you’re a web designer or developer, your work involves some teamwork and collaboration. Even when you’re working on a personal project it never hurts to have someone you can rely on. You might need somebody for guidance, assistance, or fresh ideas.

Software projects have a reputation for late deliveries and budget overruns. These often occur due to a lack of insufficient collaboration among the parties.

Setting up a manual system that promotes collaboration can be a good step forward. But it often requires extra effort to keep it functioning smoothly. There is a better approach to it. Invest in a tool that makes sharing information and design concepts a breeze.

These tools fill the bill nicely.

1. Mason

Mason

Mason is a front-end-as-a-service tool. Its users can design, build, deploy, and maintain products from a single platform. Since all information is kept in one place, there’s no fragmentation of data or information exchanged during any phase of the design/build/deploy cycle.

Mason works in ways that may at first appear unfamiliar, but nevertheless makes sense. It assembles digital products by breaking them down into their constituent parts and reassembling them using a drag-and-drop building block approach. In this way, it’s far easier to make small changes or modifications not only during design, but after the product has been deployed.

The net result, and a major advantage of using Mason, is that changes can be made to deployed digital products without the need to wait for the next deployment cycle. Changes can literally be made on the spot.

It costs nothing to use Mason during design and testing. You only pay when the product is to be viewed by downstream customers.

2. monday.com

monday.com

This team management tool is exceptionally suitable for any industry sector and by any sized team. monday.com will perfectly serve a team of two or a team of hundreds spread around the globe, and it can manage multiple projects at once. It is as popular among non-tech teams as well as tech-oriented teams; in fact, 70% of its 22,000 paying teams fall outside the tech sector.

monday.com promotes effortless collaboration and transparency, it’s “cheetah fast”, it displays status in as many as 20 different colors, and its status board can be customized to fit your needs and your workflow.

It serves as an excellent alternative to having to force fit your work to meet the demands of your project management tools or systems. Freelancers, teams representing small agencies or startups, and teams working for Fortune 500 companies all profit from using monday.com.

The post 4 Handpicked Design & Dev Collaboration Tools You Should Know About appeared first on SitePoint.


Source: Sitepoint

Ethereum DApps: Compiling, Deploying, Testing TNS tokens

In part 2 of this tutorial series on building DApps with Ethereum, we wrote the TNS token’s code. But we haven’t yet compiled it, deployed it, tested it or verified it. Let’s do all that in this part so that we’re ready for what comes next.

Compiling

At this point we have a file containing some Solidity code. But to make the Ethereum Virtual Machine understand it, we need to turn it into machine code. Additionally, in order to communicate with it from a web application, we need an ABI (application binary interface), which is a universally readable description of the functions that exist in a certain smart contract — be it a token or something more complex. We can create machine code for the EVM and the ABI all at once by using Truffle’s compiler.

In the project folder, run:

truffle compile

This command will look inside the contracts subfolder, compile them all and place their compiled version into the build subfolder. Note that if you used the alternative development flow from the last part, all the parent contracts from which our TNSToken contract is inheriting functionality will also be compiled one by one each in its own file.

Compiled contracts

Feel free to inspect the contents of the generated JSON files. Our TNSToken should have over 10000 lines of JSON code.

Deploying to Ganache

Now let’s see if we can deploy this to our simulated Ganache blockchain. If Ganache isn’t running already in a tab of your terminal or among your operating system’s applications, run it with:

ganache-cli

Or run the app to get a screen like this one:

Ganache UI

Then, back in the folder where we just compiled the contracts, we have to add a migration. Create the file migrations/2_deploy_tnstoken.js. If you’re not familiar with migrations in the Truffle ecosystem, see this guide.

Let’s put the following into that file:

var Migrations = artifacts.require("./Migrations.sol");
var TNSToken = artifacts.require("./TNSToken.sol");

module.exports = function(deployer, network, accounts) {
  deployer.deploy(TNSToken, {from: accounts[0]});
};

First the ability to do migrations at all is imported by requesting Migrations.sol. This is required in every migration. Next, deploying a token means we need to import its Solidity code, and we do this by pulling in TNSToken.sol, the code we wrote in the previous part. Finally, this is cookie cutter migrating with only the part between function(deployer, network, accounts) { and the last } changing.

In this case, we tell the deployer to deploy the TNSToken and pass in the from argument in order to set the initial token holder. The address used here is a random one generated by Ganache, but by using the accounts array automatically passed to the deployer, we make sure we have access to the list of accounts present in the running node (be it a live Geth node or Ganache). In my particular example, the account[0] address was 0xdFb659D556d926dd3585d0f18d4F8eD7939E8061, also evident in the screenshot above.

Let’s also not forget to configure a development environment in truffle.js:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 7545,
      network_id: "*"
    }
  }
};

Note: take care of the port and IP; yours might be different!

Finally, in the project folder, run truffle migrate. You should see something like this:

A successful migration

Notice the Ethereum address next to TNStoken: 0x3134bcded93e810e1025ee814e87eff252cff422. This is where our token was deployed. Now let’s see it in action.

The post Ethereum DApps: Compiling, Deploying, Testing TNS tokens appeared first on SitePoint.


Source: Sitepoint

How To Create A Flat Vector Illustration In Affinity Designer

How To Create A Flat Vector Illustration In Affinity Designer

How To Create A Flat Vector Illustration In Affinity Designer

Isabel Aracama

2018-07-11T20:00:02+02:00
2018-07-11T18:05:32+00:00

(This is a sponsored post.) If you are in the design world, chances are that you’ve already heard about Affinity Designer, a vector graphics editor for Apple’s macOS and Microsoft Windows.

It was July 2015 when Serif Europe launched the amazing software that many designers and illustrators like me are using now as their main tool for professional work. Unlike some other packages, its price is really affordable, there’s no subscription model and, as mentioned already, it’s available for both Macs and PCs.

In this article, I would like to walk you through just some of its very user-friendly main tools and features as an introduction to the software and to show you how we can create a nice flat vector illustration of a Volkswagen Beetle. The illustration will scale up to whatever resolution and size needed because no bitmaps will be used.

Note: As of today, July 11, Affinity Designer is also available for the iPad. Although the iPad app’s features and functionality almost completely match the desktop version of Affinity Designer, it relies much more on using the touch screen (and the Apple Pencil) and because of that, you may expect to find some differences in the workflows.


Final image that we’ll be creating in this tutorial.
Final image that we’ll be creating in this tutorial. (View large version)

I will also explain some of the decisions I take and methods I follow as I work. You know the old saying, “All roads lead to Rome”? In this case, many roads will take us where we’d like to get to, but some are better than others.

We will see how to work with the Pen tool to trace the main car outline, how to break curves and segments, how to convert objects into curves, and how to use the wonderful Corner tool. We will also, among other things, learn how to use the Gradient tool, what is a “Smart copy”, how to import a color palette from an image that we can use as a reference for our artwork, how to use masks, and how to create a halftone pattern. Of course, along the way, you will also learn some helpful keyboard shortcuts and commands.

Note: Affinity Designer has three work environments, referred to as “personas”. By default, Affinity Designer is set to the draw persona. To switch from the draw persona to the pixel persona or to the export persona, you have to click on one of the three icons located in the top-left corner of the main window. You can start working in the draw persona and switch to the pixel persona at any time, when you need to combine vectors and bitmaps.

The three work environments: draw persona (leftmost icon), bitmap persona (middle icon) and export persona (rightmost icon).
The three work environments: draw persona (leftmost icon), bitmap persona (middle icon) and export persona (rightmost icon). (View large version)

Introduction: The Flat Design Era

In recent years, we’ve seen the rise of “flat design”, in contrast to what is known as skeuomorphic representation in design.

To put it simply, flat design gets rid of the metaphors that skeuomorphic design uses to communicate with users, and we’ve seen these metaphors in design, especially in user interface design, for years. Apple had some of the best examples of skeuomorphism in its early iOS and app designs, and today it is widely used in many industries, such as music software and video games. With Microsoft’s (with Metro) and later Google’s material design and Apple’s iOS 7, mobile apps, user interfaces and most systems and OS’ have moved away from skeuomorphism, using it or elements of it as mere enhancements to a new design language (including gradients and shadows). As you can imagine, illustrations on these systems were also affected by the new design currents, and illustrators and designers started creating artwork that would be consistent with the new times and needs. A whole new world of flat icons, flat infographics and flat illustrations opened in front of our eyes.


iPhone’s home screen (iOS 6 versus iOS 7).
iPhone’s home screen (iOS 6 versus iOS 7). (View large version)


(Image source) (View large version)


(Image source) (View large version)


(Image source) (View large version)


(Image source) (View large version)

Let’s Draw A Flat Illustration!

I am providing here the source file for this work, so you can use it to explore it and to better follow along as we design it. If you do not yet have a copy of Affinity Designer, you can download a trial.

1. Canvas Settings

Open Affinity Designer, and create a new document by clicking Cmd + N (Mac) or Ctrl + N (Windows). Alternatively, you can go to “Menu” → “File” → “New”. Be sure not to check the “Create Artboard” box.

Set the type to “Web”, which will automatically set the field DPI to 72. It should be understood now as PPI, but we won’t dive into the details here. If you want to learn more on the topic, check the following two resources:

Also, remember that you can change this setting at any time. The vectors’ quality won’t be affected by scaling them.

Set the size to 2000 × 1300 pixels, and click “OK”.

Our white canvas is now set, but before we start, I’d suggest you first save this file and give it a name. So, go to “File” → “Save”, and name it “Beetle”.

2. Importing A Color Palette From An Image

One of the things I use a lot in Affinity Designer is its ability to import the colors contained in an image and creating a palette from them.

Let’s see how this is done.

For the illustration I want to draw, I thought of warm colors, like in a sunset, so I searched Google with this query: “warm colors yellows oranges reds palette”. From all the images it found, I chose one that I liked and copied it into Affinity Designer in my recently created canvas. (You can copy and paste the image to the canvas directly from the browser.)

If the Swatches panel isn’t open yet, use menu “View” → “Studio” → “Swatches”. Click the menu in the top-right corner of the panel, and select the option “Create Palette From Document”, and then click on “As Document Palette”. Click “OK” and you’ll see the colors contained in the image form a new palette in the Swatches panel. The default name for it will be “Palette” if you still haven’t saved your file with a name. In case you have, the name of this palette will be the same as your document, but if you want to rename it, simply go to the menu on the right in the Swatches panel again and select the option “Rename Palette”.

I will call it “Beetle Palette”.


Creating a palette from an image.
Creating a palette from an image. (View large version)

We can now get rid of that reference image, or simply hide it in the Layers panel. We will be using this palette as a guide to create our artwork with harmonious colors.

Interface: Before we continue, I will present a quick overview of the main sections of the user interface in Affinity Designer, and the names of some of the most used tools.


Main areas of the UI in Affinity Designer when using the draw persona.
Main areas of the UI in Affinity Designer when using the draw persona. (View large version)

Tools for the (default) draw persona in Affinity Designer.
Tools for the (default) draw persona in Affinity Designer. (View large version)

3. Creating The Background With The Gradient Tool

The next thing is to create a background. For this, go to the tools displayed on the left side, and select the Rectangle tool. Drag it along the canvas, making sure to give it an initial random fill color so that you can see it. The fill color chip is located in the top toolbar.


Click the Rectangle tool and drag it along the canvas. Fill it with a random color.
Click the Rectangle tool and drag it along the canvas. Fill it with a random color. (View large version)

Next, select the Fill tool (the color wheel icon, or press G on the keyboard), and in the top Context toolbar, select the type: “Linear”.


Select “Linear” from the Fill tool’s contextual menu.
Select “Linear” from the Fill tool’s contextual menu. (View large version)

We have several options here: “None” removes the fill color, “Solid” applies one solid color, and all of the rest are different types of gradients.

To straighten the gradient and make it vertical, place your cursor over one of the ends and pull. When you are near the vertical line, press Shift: This will make it perfectly vertical and perpendicular to the base of the canvas.

To straighten a linear gradient, pull from one end, and then press the Shift key to make it perfectly vertical.
To straighten a linear gradient, pull from one end, and then press the Shift key to make it perfectly vertical. (View large version)

Next, in the Context toolbar, click on the color chip, and you’ll see a dialog that corresponds exactly with the gradient we just applied. Click now on the color chip, and an additional dialog will open.

In the combo, click on the “Color” tab, and then select “RGB Hex Sliders”; in the field marked with a #, input the value: FE8876. Press “OK”. You’ll see now how the gradient has been updated to the new color. Repeat this action with the other color stop in the gradient dialog, and input this value: E1C372.

You should now have something like this:


Setting gradient colors.
Setting gradient colors (View large version)

Let’s go to the Layers panel and rename the layer to “Background”. Double-click on it to rename it, and then lock it (by clicking on the little lock icon in the top-right corner).

4. Drawing The Car Outline With The Pen Tool

The next thing we need to do is look for an image that will serve as our reference to draw the outline of the car. I searched Google for “Volkswagen Beetle side view”. From the images I found, I selected one of a green Beetle and copied and pasted it into my document. (Remember to lock the layer with the reference image, so that it doesn’t move accidentally.)

Next, in the side toolbar, select the Pen tool (or press P), zoom in a bit so that you can work more comfortably, and start tracing a segment, following the outline of the car in the picture. Give the stroke an 8-pixel width in the Stroke panel.

Note: You won’t need to create a layer, because the segments you trace will be automatically placed on top of the image.

The Pen tool is one of the most daunting tools for beginners, and it is obviously one of the most important tools to learn in vector graphics. While practice is needed to reach perfection, it is also a matter of understanding some simple actions that will help you use the tool better. Let’s dive into the details!

As you trace with the Pen tool in Affinity Designer, you will see two types of nodes: squared nodes appear first, and as you pull the handles, they will turn into rounded nodes.


Sharp, smooth nodes and handles on a path segment
Sharp, smooth nodes and handles on a path segment (View large version)

Affinity Designer comes with several pen modes, but we will only be using the default one, called “Pen Mode”, and as we trace the car, we will get rid of one of the handles by clicking Alt in such a way that the next section of the segment to be traced will be independent of the previous one, even if connected to it.

Here’s how to proceed. Select the Pen tool, click once, move some distance away, click a second time (a straight line will be created between nodes 1 and 2), drag the second node (this will create a curve), Alt-click the node to remove the second control handle, then proceed with node 3, and so on.

An alternative way would be to select the Pen tool, click once, move some distance away, click a second time (a straight line will be created between nodes 1 and 2), drag the second node (this will create a curve), then, without moving the mouse, Alt-click the second handle’s point to remove this handle, then proceed with node 3, and so on.

Trace the outline of the car and get rid of the handles we don’t need by Alt-clicking.
Trace the outline of the car and get rid of the handles we don’t need by Alt-clicking. (View large version)

Note: Don’ be afraid to trace segments that are not perfect. With time, you’ll get a better grip of the Pen tool. For now, it’s not very important that each node and line looks as we want it to look in the end. In fact, Affinity Designer makes it really easy to amend segments and nodes, so tracing a rough line to start is just fine. For more insight on how to easily use the Pen tool (for beginners), check out Isabel Aracama’s video tutorial.

5. Resculpting Segments And Using The Corner Tool

What we need now is to make all of those rough lines look smooth and curvy. First, we will pull the straight segments to smoothen them, and then we will improve them using the Corner tool.

Click the Node tool in the side toolbar, or select it by pressing A on your keyboard. Now, start pulling segments to follow the lines of your reference picture. You can also use the handles to help make the line take the shape you need by moving and pulling them accordingly. Just do it in such a way that it all fits the reference image, but don’t bother much if it’s not yet perfect. With the Node tool (A), you can both select and move nodes, but you can also click and drag the curves themselves to change them.

Resculpt and correct segments with the Node tool A.
Resculpt and correct segments with the Node tool (A). (View large version)

Once all of the segments are where we need them, we are going to smoothen their corners using the Corner tool (shortcut: C). This is one of my favorite tools in Affinity Designer. The live Corner tool allows you to adjust your nodes and segments to perfection. Select it by pressing C, or select it from the Tools sidebar. The method is pretty simple: Pass the corner tool over the sharp nodes (squared nodes) that you want to smoothen. If you need to, switch back to the Node tool (A) to adjust a section of a segment by pulling it or its handles. (Smooth nodes (rounded nodes) don’t allow for more softening, and they will display a smaller circle the moment you select the Corner tool.)



View large version


View large version
Use the Corner tool on sharp nodes to smoothen the lines.
Use the Corner tool on sharp nodes to smoothen the lines. (View large version)

Once our corners and segments look good, we’ll want to fill the shape and change the color of the stroke. Select the closed curve line that we just created for the car, click on the fill color chip, and in the HEX color field input FFCF23. Click on the stroke color chip beside it and input 131000.


This is what you should have after applying the fill color and stroke color.
This is what you should have after applying the fill color and stroke color. (View large version)

Create now a shape with the Pen tool, and fill it with black (000000). Place it behind the car’s bodywork (the yellow shape). The exact shape of the new object that you will create does not really matter, except that its bottom side needs to be straight, as in the image below. Place it behind the main bodywork (the yellow shape) via either the Layers panel or through the menu “Arrange” → “Back One”.


Black shape behind the car bodywork.
Black shape behind the car bodywork (View large version)

6. Creating The Wheels Using Smart Copy

We need to put the wheels in place next. In the Tools, pick the Ellipse tool, and drag over the canvas, creating a circle the same size as the wheel in the reference picture. Click Shift as you drag to make the circle proportionate. Additionally, holding Ctrl (Windows) or Cmd (Mac), you can create a perfect circle from the center out.

Note: If you need to, hide the layers created thus far to see better, or simply reduce their opacity temporarily. You can change the opacity by selecting any shape and pressing a number on the keyboard, from 1 to 9, where 1 will apply a 10% opacity and 9 a 90% opacity value. To reset the opacity to 100%, press 0 (zero).

Choose a random color that contrasts with the rest. I like to do so initially just so that I can see the shapes well contrasted and differentiated. When I am happy with them, I apply the final color. Set the opacity to 50% (click 5 on the keyboard) to be able to see through as you draw it.

Zoom into your wheel shape. Press Z to select the Zoom tool, and drag over the shape while holding Alt key, or double-click on the thumbnail corresponding to it in the Layers panel. (It doesn’t need to be previously selected, although this will help you to visually locate it in the Layers panel.)

We will now learn how to use Smart copy, and we will paste some concentric circles.

Select the circle and press Cmd + J (Mac) or Ctrl + J (Windows). A new circle will be placed on top of the original one. Select it. This command is found under “Edit” → “Duplicate”, and it’s also known as Smart copy or Smart duplicate.

Click Shift + Cmd (Mac) or Shift + Ctrl (Windows), and drag in to transform it into a smaller concentrical circle. Repeat three times, reducing a bit more in size each time, to fit your reference. Smart duplicating a shape by pressing Shift + Cmd (Mac) or Shift + Ctrl (Windows) will make the shape transform in a relative way. This will happen from your third smart-duplicated shape onwards.

smart copy via keyboard shortcuts
Smart copy via Cmd + J or Ctrl + J. (View large version)

So, we have our concentric circles for the wheel, and now we have to change the colors. Go to the Swatches panel, and in the previously created palette, choose colors that work well with the yellow that we have applied to the car’s bodywork. You can select a color and modify it slightly to adapt to what you think works best. We need to apply fill and stroke colors. Remember to give the stroke the same width as the rest of the car (8 pixels) except for the innermost circle, where we will apply a stroke of 11.5 pixels. Also, remember to put back to 100% the opacity of each concentric circle.

I chose these colors, from the outer to inner circles: 5D5100, 918A00, CFA204, E5DEAB.

Now we want to select and group all of them together. Select them all and press Cmd + G (Mac) or Ctrl + G (Windows). Name the new group “Front Wheel” in the Layers panel. Duplicate this group and, while pressing Shift, select it and drag along the canvas until it overlaps with the back wheel. Name the layer accordingly.


The car should look similar to this now.
The car should look similar to this now. (View large version)

7. Breaking Curves And Clipping Masks To Draw The Inner Lines Of The Car’s Bodywork

To keep working, either hide all layers or bring down the opacity so that they don’t get in your way. We need to trace the front and back fenders. We have to do the same as what we did for the main bodywork. Pick the Pen tool and trace an outline over it.

Once it is traced, modify it by using the handles, nodes and Corner tool. I also modified the black shape behind the car a bit, so that it shows a bit more in the lower part of the body work.


Fenders added to the car.
Fenders added to the car. (View large version)

Now we want to trace some of the inner lines that define the car. For this, we will duplicate the main yellow shape, remove its fill color and place it onto our illustration in the canvas.

Press A on the keyboard, and click on any of the bottom nodes of the segment. In the top Context toolbar, click on “Action” → “Break Curve”. You will see now that the selected node has turned into a red-outlined squared node. Click on it and pull anywhere. As you can see, the segment is now open. Click the Delete or Backspace key (Windows) or the Delete key (Mac), and do the same with all of the bottom nodes, leaving just the leftmost and rightmost ones, and also being very careful that what is left of the top section of the segment is not deformed at all.

(View large version)

I use this method for one main reason: Duplicating an existing line allows for a more consistent look and for more harmonious lines.

Select now the newly opened curve, and make it smaller in such a way that it fits into the main yellow shape when you place them on top of one another. In the Layers panel, drag this curve into the yellow shape layer to create a clipping mask. The reason for creating a clipping mask is simple: We want an object inside another object so that they do not overlap (i.e. both objects are visible), but one nested inside the other. Not doing so would result in some bits of the nested object being visible, which is not what we want; we need perfect, clean-cut lines.

Note: Clipping masks are not to be mistaken for masks. You will know you’re clipping and not masking because of the thumbnail (masks show a crop-like icon when applied) and because when you are about to clip, a blue stripe is displayed horizontally, a bit more than halfway across the layer. Masks, on the other hand, display a small vertical blue stripe beside the thumbnail.


Clipping versus masking in Affinity Designer
Clipping versus masking in Affinity Designer (View large version)
Clipping mask once it is applied
Clipping mask once it is applied (View large version)

Now that we have applied our clipping mask to insert the newly created segment inside the main shape of the car, I’ve broken some nodes and moved some others around a bit in order to place them exactly how I want. I’ve stretched the width a bit, and separated the front from the rest of the segment using exactly the same methods we’ve already seen. Then, I applied a bit more Corner tool to soften whatever I felt needed to be softened. Finally, with the Pen tool, I added some extra nodes and segments to create the rest of the inner lines that define the car.

Note: In order to select an object in a mask, a clipping mask or a group when not selecting the object directly in the Layers panel, you have to double-click until you select the object, or hold Ctrl (Windows) or Cmd (Mac) and click.

Adding extra lines to a segment.
Adding extra lines to a segment (View large version)

After some amendments and tweaking using the mentioned methods, our car looks like this:


How the car looks after a little tweaking of the segments and nodes
How the car looks after a little tweaking of the segments and nodes (View large version)

8. Drawing The Windows Using Some Primitive Shapes

In the side Toolbar, select the Rounded Rectangle tool. Drag on the canvas to create a shape. The size of the shape should fit in the car’s bodywork and look proportionate. No matter how you create it, you will be able to resize it later, so don’t worry much.

Note: When you create a shape with strokes and resize it, be sure to check “Scale with object” in the Stroke panel if you want the stroke to scale in proportion with the object. I recommend that you visually compare the difference between having this option checked and unchecked when you need to resize an object with a stroke.


Make sure this is checked if you plan to resize your artwork, so that it scales the strokes accordingly.
Make sure this is checked if you plan to resize your artwork, so that it scales the strokes accordingly. (View large version)

Once you have placed your rounded rectangle on the canvas, fill it with a blue-ish colour. I’ve used #93BBC1. Next, select it with the Node tool (press A). You will now see a little orange circle in the top-left corner. If you pull outwards or inwards, you’ll see how the angle in that corner changes. In the top Context toolbar, you can uncheck “Single radius”, and apply the angle you want to each corner of the rectangle individually. Uncheck it, and pull inwards on the tiny orange circle in the top-left corner. If you pull, you will be able to round it to a certain percentage, but you can also input the desired value in the input field for it, or even use the slider it comes with (it will show whether you’ve clicked on the little chevron). Let’s apply a value of 100%.



View large version

How the rounded rectangle primitive shape looks in default mode and how it changes when we uncheck the single radius box. Now we can manipulate the corners individually.
How the rounded rectangle primitive shape looks in default mode and how it changes when we uncheck the single radius box. Now we can manipulate the corners individually. (View large version)

Primitive shapes are not so flexible in terms of vector manipulation (compared to curves and lines), so, in order to apply further changes to such a shape (beyond fill, stroke, corners, width and height), we will need to convert it to curves.

Note: Once you convert a primitive shape into curves, there is no way to go back, and there will be no option to manipulate the shape through the little orange stops. If you need further tweaking, you will need to do it with the Corner tool.

Select the rectangle with the Node tool (A), and in the top Context toolbar, click the button “Convert to Curves”. The bounding box will disappear, and all of the nodes forming the shape will be shown. Also, note how in the Layers panel, the name of the object changes from “Rounded Rectangle” to “Curve”.

Now you need to manipulate the shape in order to create an object that looks like a car window. Look at the reference picture to get a better idea of how it should look. Also, tweak the rest of the drawn lines in the car, so that it all fits together nicely. Don’t worry if the shapes don’t look perfect (yet). Getting them right is a matter of practice! Using the Pen tool, help yourself with the Alt and Shift keys and observe how differently the segment nodes behave. After you have created the front window, go ahead and create the back one, following the same method.

We also need to create the reflections of the window, which we’ll do by drawing three rectangles, filling them with white color, overlapping them with a bit of offset from one another, and setting the opacity to 50%.

Place the cursor over the top bounding-box white circle, and when it turns into a curved arrow with two ends, move it to give the rectangles an angle. Create a clipping mask, dragging it over the window shape in the Layers panel as we saw before. You can also do this by following the following alternative methods:

  • Under the menu “Layer” → “Insertion” → “Insert Inside” the selected window object.
  • With the keyboard shortcut Ctrl + X (Windows) and Cmd + X (Mac), select your window object → “Edit” → “Paste Inside” (Ctrl/Cmd + Alt + V).

Repeat this for the back window. To add visual interest, you can duplicate the reflections and slightly change the rectangles’ opacities and widths.

Create the reflections on the windows, and clip them inside.
Create the reflections on the windows, and clip them inside. (View large version)

9. Adding Visual Interest: Halftone Pattern, Shadows And Reflections

Before we start with the shadows and reflections, we need to add an extra piece onto the car so that all of the elements look well integrated. Let’s create the piece that sits below the doors. It is a simple rectangle. Place it on the corresponding layer order, so that it looks like the picture below, and keep inserting all of the pieces together so that it looks compact. I will also move a bit the front fender to make the front shorter.


The car, once the final bodywork pieces have been placed and tweaks made. We’re getting there!
The car, once the final bodywork pieces have been placed and tweaks made. We’re getting there! (View large version)

Now let’s create the halftone pattern.

Grab the Pen tool (P) and trace a line on your canvas. In the Stroke panel (you can also do this in the Pen tool’s Context toolbar section for the stroke, at the top), set the size to something like 7 pixels. We can easily change this value later if needed. Select the “Dash” line style, and the rest of the dialog settings should be as follows:


Settings for the first part of creating the halftone pattern.
Settings for the first part of creating the halftone pattern. (View large version)

Now, duplicate this line, and place the new one below with a bit of an offset to the left.



View large version

Group both lines, duplicate this group with a Smart copy, and create something like this:


Smart copy the first two lines, and create the whole pattern.
Smart copy the first two lines, and create the whole pattern. (View large version)

When you drag a selection in Affinity Designer, only objects that are completely within the selection area will be selected. If you want to select all objects without having to drag over all of them completely, you have the following options:

  • Mac: Holding the (Ctrl) key will allow you to select all objects touching the selection marquee as you draw it.
  • Windows: Click and hold the left mouse button, start dragging a selection, and then click and hold the right mouse button as well. As you are holding both buttons, all objects touching the selection marquee will be selected.
  • Alternatively, you can make this behavior a global preference. On Mac, go to “Affinity Designer” → “Preferences” → “Tools”, and check “Select object when intersects with selection marquee”. On Windows, go to “Edit” → “Preferences” → “Tools”, and check “Select object when intersects with selection marquee”.

To make the illustration more interesting, we are going to vary the beginning and end of some of the lines a bit. To do this, we select the Node tool (A), and move the nodes a bit inwards.

It should now look like this:



View large version

To apply the pattern to our design, make sure everything is grouped, copy and paste it into our car artwork, reduce its opacity to 30%, and also reduce the size (making sure “Scale with object” is checked in the Stroke panel). We will then create a clipping mask. It is important to keep consistency in the angle, color and size of this pattern throughout the illustration.

Applying the halftone mask.
Applying the halftone mask (View large version)

Now, apply the halftone pattern to the back fender and to the car’s side; make sure to create a placeholder for it first, be it the fender itself or a new shape. Make some tweaks if you need to adapt the pattern to your drawing in a harmonious way. You can change the overall size, the dots’ size, the transparency, the angle and so on, but try to be consistent when applying these changes to the pattern bits.

For the shadow below the windows, I drew a curve to be the placeholder, and applied the color #CFA204 so that it looks darker.

10. Creating The Remaining Elements Of The Car

Now, it’s all about creating the rest of the elements that make up the car: the bumpers, the back wheel and the surf board, plus the design stickers.

  • The front and back lights
    For the front light, switch to the Segment tool and draw the shape. Then we need to rotate it a bit and place it somewhere below the car’s main bodywork. The same can be done for the back light but using the Rectangle tool. The colors are #FFDA9D for the front light and #FF0031 for the back light.
Creating the front light
Creating the front light (View large version)
  • Surfboard
    To create the surfboard, we will use the Ellipse tool and draw a long ellipse. Convert it to curves and pull up the lower segment, adjusting a bit the handles to give it the ideal shape.
Creating the surf board
Creating the surf board (View large version)

Now, just create two small rounded rectangles, with a little extra line on top for the board’s rack. Place them in a layer behind the car’s main body shape.


Board rack pieces
Board rack pieces (View large version)

With the Pen tool, add the rudder. Its color is #B2E3EF. And for the stroke, use a 6-pixel width and set the color to #131000.

  • Spare wheel
    Now let’s create the the spare wheel! Switch to the Rounded Rectangle tool. Drag over the canvas to draw a shape. Color it #34646C, and make the stroke #131000 and 8 pixels in size. The size of the spare wheel should fit the proportions of your car and should have the same diameter as the other wheels, or perhaps just a bit smaller. Pull the orange dots totally inwards, and give it a 45-degree angle. For the rack that holds the wheel, create a small piece with the Rectangle tool, and give it the same 45-degree angle, color it #4A8F99, and make the stroke #131000 and 4.5 pixels in size. Create the last piece that rests over the car in the same way, with a color of #34646C, and a stroke that is #131000 and 4.5 pixels in size.

Lastly, let’s create a shadow inside the wheel to add some more interest. For this, we’ll create a clipping mask and insert an ellipse shape with a color of #194147, without a stroke.

Note: We may want to create the same shadow effect for the car wheels. Use the Rectangle tool and a color of #312A00, create a clipping mask, and insert it in the wheel shape, placing it halfway.


Three simple shapes to draw the spare wheel and its rack
Three simple shapes to draw the spare wheel and its rack (View large version)
  • Bumpers
    For the bumpers, we will apply the boolean operation “add” to two basic shapes and then clip-mask a shadow, just as we did for the wheels.

Boolean operations are displayed in the section of icons labeled “Geometry” (Mac) and “Operations” (Windows). (Yes, the label names are inconsistent, but the Affinity team will likely update them in the near future, and one of the labels will become the default for both operating systems.) If you don’t see them in the upper toolbar, go to “View” → “Customize Toolbar”, and drag and drop them into the toolbar.

Important: If you want the operation to be non-destructive, hold the Alt key while clicking on the “Add” icon (to combine the two basic shapes).


Boolean operations: Add, Subtract, Intersect, Divide, Combine.
Boolean operations: Add, Subtract, Intersect, Divide, Combine. (View large version)

Applying the (destructive) Add operation to create a single shape from two shapes.
Applying the (destructive) Add operation to create a single shape from two shapes. (View large version)

Note: If you try to paste the “shadow” object inside the bumper, it will only work if the bumper is one whole object (a destructive operation). So, if you used Alt + “Add”, this will not work now. However, you can still work around this by converting the Compound shape (the result of a non-destructive operation that is a group of two objects) to one Curve (one whole vector object). You just need to click on the Compound shape, then in the menu go to “Layer” → “Convert to Curves” (or use the key combination Ctrl + Enter).

  • Back window
    We are still missing the back window, which we will create with the Pen tool, and the decoration for the car. For the two colored stripes, we need the Square tool and then clip-mask these two rectangles into the main bodywork. The size is 30 × 380 pixels, and the colors are #0AC8CE and #FF6500. Clip them by making sure you’ve put them on the right layer, so that the dark lines we drew before are above them.

  • Number 56
    For the number “56” decoration, use the Artistic Text tool (“T”), and type in “56”. Choose a nice font that matches the style of the illustration, or try the one I’ve used.

The color for the text object is #FFF3AD.

(I added an extra squared shape behind the back fender, which will look like the end of the exhaust pipe. The color is #000000.)

  • Color strips
    Now that we’ve done this, check the color stripes and the window they overlap with. As you can see (and because we put some transparency in the window glass), the orange stripe is visible through it. Let’s use some Boolean power again to fix this.

Bumpers and exhauster added. Check out the overlapped window and the orange stripe!
Bumpers and exhauster added. Check out the overlapped window and the orange stripe! (View large version)

Duplicate the window object. Select both the window object (the one you just duplicated) and the orange stripe in the Layers panel. Apply a “subtract” operation.


Stage 1, before the subtract operation.
Stage 1, before the subtract operation. (View large version)

tage 2, once the subtract operation is applied.
Stage 2, once the subtract operation is applied. (View large version)

Now, the orange stripe has the perfect shape, fitting the window in such a way that they don’t overlap.


Stripe and window with subtraction operation applied.
Stripe and window with subtraction operation applied. (View large version)
  • Smoke
    To create the smoke from the exhaust, draw a circle with a white stroke, 5.5 pixels in size and no fill. Transform it to curves and break one of its points. From the bottom node, trace a straight line with the Pen tool.

Duplicate this “broken” circle, and resize to smaller circles, and flip and place them so that they look like this:


Creating the exhaust smoke
Creating the exhaust smoke (View large version)

Note: Now that the car is finished, group all of its layers together. It will be much easier to keep working if you do so!

11. Creating The Ground And The Background Elements.

  • Ground
    Let’s trace a simple line for the ground, and add two bits breaking it in order to create visual interest and suggest a bit of movement. We also want to add an extra piece to create the ground. For this, we will use the Rectangle tool and draw a rectangle with a gradient color of #008799 for the left stop and #81BEC7 for the right stop. Give it 30% opacity.

Gradient for the ground piece and the grouped car layers for a clean view in the Layers panel.
Gradient for the ground piece and the grouped car layers for a clean view in the Layers panel. (View large version)
  • Clouds
    For the clouds, select the Cloud tool from the list of (primitive) vector shapes. Draw a cloud by holding Shift to keep the proportions. Make it white. Transform it into curves, and with the Node tool (A) select the bottom nodes and delete them. Sub-select the bottom-left and bottom-right nodes (after deleting all of the others), and then in the Context toolbar, select “Convert to Sharp” in the Convert section. This will make your bottom segment straight. Apply some transparency with the Transparency tool (Y), and duplicate this cloud. Place the clouds in your drawing, spread apart as you wish and in different sizes.

My clouds have 12 bubbles and an inner radius of 82%. You can do the same or change these values to your liking.

Creating the clouds with the Cloud tool and the Transparency tool
Creating the clouds with the Cloud tool and the Transparency tool (View large version)
  • Palm trees
    To create the palm trees, use the Crescent tool from the list of primitive shapes on the left. Give it a gradient color, with a left stop of #F05942 and a right stop of #D15846.

Drag to draw the crescent shape. Move its center of rotation to the bottom of the bounding box, and give it a -60-degree angle.

The center of rotation can be made visible in the Contextual toolbar section for the Move (and Node) tool. It looks like a little crosshair icon. When you click on it, the crosshair for moving the rotation center of an object will show. Duplicate it, either via Cmd + C and Cmd + V (Mac) or Ctrl + C and Ctrl + V (Windows), or by clicking and then Alt + dragging on the object, and move the angle of the new crescent to -96 degrees. Make it a bit smaller. Copy the two shapes and flip them horizontally.

I also created and extra crescent.

Creating the palm leaves
Create the palm leaves (View large version)

To create the indentations on the leaves, transform the object to curves, add a node with the Node tool, and pull inwards. To make the vortex sharp, use “Convert” → “Sharp”.

Creating the leaves’ indentations
Creating the leaves’ indentations (View large version)

Create the trunk of the palm tree with the Pen tool, group all of the shapes together, and apply an “add” boolean. This way, all of the shapes will transform into just one. Apply a 60% opacity to it.


The palm tree once the Add boolean operation has been applied.
The palm tree once the Add boolean operation has been applied (View large version)

Duplicate the tree shape several times, changing the sizes and tweaking to make the trees slightly different from one another. (Making them exactly the same would result in a less interesting image.)

The last thing we need to make is the sun.

  • The sun
    For this, simply draw an ellipse and apply a color of #FFFFBA to it. Apply a transparency with the Transparency tool (Y), where the bottom is transparent and gets opaque at the top.

Transparency applied to the sun shape
Transparency applied to the sun shape (View large version)

Now we will add some detail by overlapping several rounded rectangles over the sun circle and subtracting them (click Alt for a non-destructive action, if you prefer).

Applying a subtract operation
Applying a subtract operation (View large version)

Place your sun in the scene, and we are done!

12. A Note On The Stacking Order (And Naming Of Layers)

While you work, and as the number of objects (layers) grows, which will also make your illustration more and more complex, keep in mind the stacking order of your layers. The sooner you start naming the layers and placing them in the right order, the better. Also, lock those layers that you’re done with (especially for things such as the background), so that they don’t get in the way as you work.

In this illustration, the order of elements from bottom to top is:

  • background,
  • ground,
  • sun,
  • clouds,
  • palm trees,
  • car.

Conclusion

I hope you could follow all of the steps with no major problems and now better understand some of Affinity Designer’s main tools and actions. (Of course, if you have some questions or need help, leave a comment below!)

These tools will allow you to create not only flat illustrations, but many other kinds of artwork as well. The tools, actions and procedures we’ve used here are some of the most useful and common that designers and illustrators use daily (including me), be it for simple illustration projects or much more complex ones.

However, even my most complex illustrations usually need the same tools that we’ve seen in action in this tutorial! It’s mainly a matter of understanding how much you can get out of each tool.

Remember the few important tips, such as locking the layers that could get in your way (or using half-transparency), stacking the layers in the right order, and naming them, so that even the most complex of illustrations are easy to organize and work with. Practice often, and try to organize things so that your workflow improves — this will lead to better artwork and better time management as well.

Also, to learn more about how to create this type of illustration, check out the video tutorial that I posted on my YouTube channel.


The completed Volkswagen Beetle illustration.
The completed Volkswagen Beetle illustration. (View large version)
Smashing Editorial
(mb, ms, ra, yk, al, il)


Source: Smashing Magazine

Best Market for WordPress Themes: TemplateMonster or ThemeForest?

This article was created in partnership with TemplateMonster. Thank you for supporting the partners who make SitePoint possible.

Most users feel overwhelmed when they need to select the best ready-made design for their website. There are plenty of agencies and web design studios offering unique designs to help users get started with websites for multiple purposes.

The number of web platforms selling themes crafted by vendors worldwide grows quickly all the time. If you want to select the best ready-made design for your site and feel confident that you’ve made the right choice, then it’s always a great idea to choose the industry leaders.

TemplateMonster and ThemeForest have proven to be the two leading digital marketplaces selling WordPress templates of top quality. Comparing these two options, which one is a better place to buy themes for your websites? That’s the question that we are going to answer in this post.

Why You Should Select WordPress Themes with Caution

WordPress has become one of the leading content management systems in the world. With its help, you will find no difficulty launching any kind of website, representing any business niche in an effective style.

Selecting the most optimal starting point for your site, you need to make sure that your WordPress theme complements the content that you are going to share on your site. Using WordPress, you can create stunning blogs, portfolios, business and corporate web projects, landing pages, and even eCommerce sites. Depending on the goal and the type of the online project that you need to launch, you need to select WordPress themes that meet your specific requirements. For example, launching a blog, you need to select a template that improves the readability of your content. If you want to launch a portfolio site, then the template of your choice should be optimized for handling image-rich web projects perfectly well.

Many WordPress templates available today are pre-installed with plugins and extensions intended to enhance the performance of niche-specific web projects. Just in case the selected WordPress theme isn’t loaded with the necessary tools, make sure that it’s compatible with the respective functionality.

Security is one of the top priorities that you need to take into consideration while selecting the best WordPress theme for your site. Although WordPress is known as one of the safest CMSs on the web, featuring regular updates, you need to make sure that you download a template that features regular updates so it won’t become outdated a few months after the launch of your site.

Let’s compare the functionality included in two of the top-selling business WordPress themes from both marketplaces. There are some features they have in common and certain peculiarities that make each of them unique. So, let’s compare and choose the best theme of the two reviewed.

EasyJet vs Argenta Multipurpose WordPress Themes

EasyJet is a functional multipurpose template sold by ZEMEZ in the TemplateMonster digital marketplace. This is a usable ready-made solution that is easy-to-handle by both beginners and expert webmasters. This is a feature-rich WordPress template that comes loaded with everything that you need for the launch of personal, business or eCommerce sites. There is no need to be an expert web designer or a programming specialist in order to handle the theme on your own. The theme’s download pack includes a wide range of features that will appeal to users of all skill levels.

Argenta is a creative multipurpose WordPress template sold by Colabrio on the ThemeForest marketplace. This is one of those feature-rich WordPress templates suited to be used for content-heavy web projects. Collections of the fully editable layouts that are included in the theme’s download pack are ready to be customized by means of the usable modification features that can be accessed via the dashboard.

Both of the reviewed WordPress templates are multipurpose solutions that include a handful of tools and features that provide for specific needs. Both templates include similar options and different sets of tools, which make one of them stronger than the other. Well, enough said. Let’s get straight to the comparison.

Installation

In order to start working with any WordPress template, you need to have WordPress installed. If you haven’t done this yet, make sure you install the latest WordPress version on your web host.

In order to start working with the EasyJet WordPress template, you need to make all the necessary preparations and run the plugin installations. This guarantees that the chosen template will work correctly after the installation of all its components.

The post Best Market for WordPress Themes: TemplateMonster or ThemeForest? appeared first on SitePoint.


Source: Sitepoint

Learning To Code By Writing Code Poems

Learning To Code By Writing Code Poems

Learning To Code By Writing Code Poems

Murat Kemaldar

2018-07-11T14:00:32+02:00
2018-07-11T13:57:24+00:00

Back in 2008, I started studying design and clearly remember how the sheer sight of code just intimidated me. I had some coding classes, and without any prior coding experience, I had a tough time understanding the code I first got in touch with. Suddenly, the words that I was used to in the English language (such as “new,” “return” and “throw/catch”) took on a whole new meaning; the cryptic syntax, semicolons, brackets and completely new rules didn’t make things any easier for me.

If you are new to JavaScript and/or have struggles adding it to your skillset, I may have an approach for you to overcome those barriers. You are definitely not alone, and you have every right to think that learning to code is a tough nut to crack.

Why Is Learning To Code So Tough?

Here are some of the misconceptions about why I think people are having a hard time learning or getting interested in JavaScript (or any coding language):

  • Code is cryptic, purely functional and scary;
  • Code is meant for machines only, so people do not feel addressed or engaged;
  • Code is not treated as a language because it has a completely different use case and looks very different from anything they have seen before;
  • People think of stereotypes (evil hackers, maybe some Matrix dudes), and thus do not identify themselves with it.

A young and unexperienced student with a pacifier and pillow
Me, before any contact with code (Large preview)

As a developer, you are expected to treat code in a very specific way — even to think in a quite different (and highly logical) way. Coding languages are quite strict and intolerant; a single character can make the machine fail to understand what you mean and make applications crash. You are expected to ignore and override certain things you know from speaking and writing a human language (which is, by the way, also the case when learning a new human language).

But not all programming languages, documentations or tutorials on the web are made with this “human to programming language transition” in mind. Of course, they don’t have to. After all, the main purpose of code is to tell machines what to do.

Still, due to that purpose, a chance for comparison is simply missing and the languages you speak (vocabulary and rules) seem to be rendered useless for learning a programming language. There is no word for “love” in the JavaScript language, nor does it make sense to say “I love you.” A machine (or browser) simply does not know or care about love (yet?). This “completely new” and “don’t know where to start” feeling can be scary as hell.


 A student who is intimidated by coding languages
Me, after my first contact with code. (Large preview)

This is why I am here. I think that you can learn JavaScript in a much easier and artistic fashion, by holding on to your human language knowledge, and by treating JavaScript like any other human language. Let me demonstrate with a small example.

Fun fact: Some programming languages actually have the transition from one programming language to another in mind. This is why it is so much easier to learn a lot of programming languages — just by learning a single one.

A Small Example

In a lot of cases, when you want to execute JavaScript code, you want the “document” (basically the website, a user is downloading on each visit) to be ready so that you can interact with HTML elements, for example. In pure JavaScript, you may stumble over something this:

(function() {
   // Your code goes here
})();

(Yuck! 😖 In this case, a function is defined in brackets, and then immediately called with another pair of brackets at the end. This is referred to as an IIFE.)

Or sometimes like this:

if (document.readyState === ‘complete’) {
  // Your code goes here
}

The first snippet definitely requires an explanation, while with the second (and maybe some fantasy), one could comprehend that there is a condition which needs to be fulfilled so that something else happens just by just looking at it.

Imagine something like this, though:

onceUponATime(function () {
  // Your code (story) goes here
})

“Once upon a time” is something (dare I say) even a child might understand. It addresses the developer (by referring to childhood memories), while theoretically doing the same thing. This is what I consider “having the human to coding language transition” in mind.

Quick note on “functions“: A function is basically a skill, which is dormant until you call upon it. “To read” is a skill function read() { … }, which is called upon when you are want to read something like this: read(). There is also something called “anonymous functions”, i.e. "function() { … } (has no name, like in the snippets above) which are basically “one-time / casual actions” that you wouldn’t consider to be a skill, such as “to push a button.”

Turning The Tables: From Message To Basics

So let’s take this idea a bit further. Let’s take the reasons and misconceptions above, and turn them upside-down:

A small poem.

Written in JavaScript.

Made for human beings.

About the love between two individuals.

// Love at first sight
if (me.getDistanceTo(you.position) < 200) {
  me.setFeelings({
    inLove: true,
  });
}

It is not functional. It is currently not meant for machines. It is meant for you to read and understand.

If you got the message of the poem, you actually understood a piece of JavaScript code, which you might have compared to the English language.

Now you might ask yourself: I understand this, but why is it written like this? What are the rules (grammar) of this language? What is the meaning of “me” (in a technical sense), and why does this code look so similar to English?

Rules, Vocabulary, And Variables

One of the most important things to understand when learning a programming language is the concept of variables.

Every human language has its rules (grammar) and a lot of vocabulary (pre-defined). Obviously, both of these first need to be learned in order to be able to speak the language.

JavaScript, like many other programming languages, also comes with its own set of rules (e.g. the . between the words or how if statements are written) and its own vocabulary (if, document, window, Event, and so on). These keywords are reserved (or ‘pre-defined’) by JavaScript (and the browser), and each one of them has its specific purpose.

But like I mentioned earlier, a chance to compare the words and sentences you know from the English language is seemingly missing because there are no equivalents.

This is where variables come in; you (the developer) can (or even have to) define the variables in order to make machines and developers understand what something stands for. Variables can take a lot of forms (hence the name): They can be a chain of words and letters (strings), a number, an action (function), or even a collection (array). You name it.

In all languages, there is probably a word for love. You kinda know what it means, but not really, because it is so subjective. But still, there is a word for it.

But in JavaScript, there is no “love,” until you say there is. It can be whatever you want it to be.

var love = {
  color: ‘red’,
  duration: 365,
  loveTarget:  ‘cats’,
};
// a simple variable expression,
// where love is an object “{ … }”, a thing
// with some properties (color, duration, loveTarget).

const love2 = { color: ‘purple’, duration: ‘forever’, loveTarget: ‘dogs’, };

// also a variable expression, where love2 (a constant), // cannot be redefined / overwritten completely: // love2 = undefined; // => will not work

// (“undefined” is a pre-defined javascript keyword, // basically saying “has no value”)

It is crucial to be able to distinguish between what is pre-defined in JavaScript (JavaScript rules and vocabulary), and what is actually custom defined by the developer (also known as ‘application logic’ or ‘business logic’).

Returning to the poem written above:

// Love at first sight
if (me.getDistanceTo(you.position) < 200) {
  me.setFeelings({
    inLove: true,
  });
}

These expressions come from the following JavaScript vocabulary/ruleset:

if (…) { … }
// if statement: when … is met, do things in { … }

{ inLove: true, } // an “object” with some info, some thing in the world. // can contain other info, and “skills” (functions). // “inLove” is a custom property, // “true” is pre-defined in javascript, (meaning: “yes”) // and the value of “inLove”.

. // needed to access an objects property “my name: me.name”

getDistanceTo() // an expression to “call” a function (a “skill”). // getDistanceTo is custom (not JavaScript), and a function, // so it can be executed / called upon with the “()” after. // sometimes you can pass arguments in those brackets (like “position”) // to change the outcome of a function.

And these are the variables (where you have free reign over defining their names and behavior):

me // an object, some thing in the world
you // an object, some thing in the world
position // an info about “you”, accessed by the “.”
getDistanceTo // a skill of me, accessed by the “.”
getDistanceTo() // the skill, with javascript grammar telling: do it.
getDistanceTo(position) // same, but do it with “position”.
setFeelings // another skill of me, accessed by the “.”
setFeelings({ inLove: true }); // the skill, with some instructions (an object).

Let’s assume the poem is now human-readable. You might have understood the message, you also might see the difference between JavaScript language rules you need to follow, and the things you actually have to come up with yourself (the variables).

But what about the machine?

If the machine (the browser) were to read this poem, it would throw an error. The machine needs a definition of “me” and “you” because it tries to access its properties (via the . in me.getDistanceTo()). With the distinction ability mentioned above, you can actually engineer “me” and “you” to make the poem executeable/machine-readable, like this:

// This is how the definition of a being (me/you) could look like

var me = { position: {x: 0, y: 0} // some coordinates, maybe getDistanceTo: function(position) { // calculate the distance, relative to own position }, setFeelings: function(feelings) { // handle those feelings… } }

var you = { position: {x: 0, y: 0} // some coordinates, maybe }

// the poem itself if (me.getDistanceTo(you.position) < 200) { me.setFeelings({ inLove: true, }); }

So what happened here?

  • We read a JavaScript poem, written with JavaScript “grammar” with the only goal to be understood by human beings.
  • After understanding the message, we distinguished between rules, vocabulary, and variables, to understand the structure of the poem (grammar and basics of JavaScript).
  • With that distinction, we engineered the rest of the poems variables, with JavaScript rules in order to make it runnable by a machine (in the browser).

This was possible, because we treated JavaScript just like the English language.

A Bigger Example: Interactive Code Poetry

This is how my personal project LoveBits came to be. LoveBits is a code learning/storytelling experience.

Animated demonstration of the LoveBits project
LoveBits: Code poetry project in JavaScript (Large preview)

It tries to get people interested in JavaScript/coding by:

  • Putting readability and human language first;
  • Combining code with an art the reader might already be familiar with.

Storywise, it is about two Bits (rectangular beings); one of the Bits (blueBit) is the romantic one and writes JavaScript love poems to the other Bit (purpleBit).

When you start LoveBits, you can select one of the multiple love poems (written in JavaScript). Each poem has a code snippet which is written in a way that it is supposed to be understood by people who are not even familiar with programming. The only requirement is the English language.

“Love at first sight” (actually one of the LoveBits poems), for example, is about these two Bits in which the blueBit basically says, “If I get close enough to your position, I will ‘set my feelings’ to inLove: true.”

The special thing about these poems though is that you can “run” or “play” them simply by pressing the “play” button below. In the case of “Love at first sight,” you would see a blue and purple rectangle along with a number. As you might’ve already guessed, those are the two Bits mentioned in the poem, and the number below the blueBit is actually the distance between the blueBit and the purpleBit.

As the poem suggests, you may want to make the blueBit fall in love with the purpleBit by reducing the distance between them, right? So what can you do? You can interact and drag the blueBit around, and make it fall in love. But be careful, sometimes there is more than just one outcome.

One might actually say that you are the machine here. You’re the one who needs to interpret JavaScript code to be able to act and help two digital beings fall in love.

Where To Go From Here?

If you are a struggling developer, try treating JavaScript like a human language, and just understand what code snippets are supposed to do first instead of what they actually end up doing.

This is what I would recommend you to do next:

  • Always prefer going straight for examples and code for entire applications that combine rules, vocabulary, and variables together to form an application logic;
  • Application logic will tell the stories that will help you fill the gaps like in the code examples above. Code libraries and utilities such as lodash will only provide you with new vocabulary which will become helpful after being able to read and understand JavaScript code;
  • Review existing code, and try to break it down into small functions with names that reflect what they do. Write code which addresses humans and machines alike. Write code in such a way that it can be read like a sentence. Use comments wherever needed. Think about: How would I express this in a human language (to another developer)?

Conclusion

Learning to code can become easier once you start treating code as a human language and not as something aliens may have invented. Learning to distinguish between language features (built-ins) and variables/custom code for application logic is crucial. Being able to understand the application logic will put you in a powerful position to improve and change things, without even knowing language features.

Message before basics: Understand the message of any code snippet, and the basics of JavaScript will naturally follow. How many times have you heard someone say, “I understand the language, but I do not speak it yet”? It is a natural process, which can and maybe should be applied for learning both human and coding languages.

Also, always keep in mind that code has a clear functional purpose, but it does not always have to be like that. Even human languages were purely functional once, but then there came poems and even songs (JavaScript songs, anyone?), which connected people in entirely different ways. I think, or hope, that the same can apply here.

Always explore code projects, and perhaps even try writing a poem yourself (maybe even in another programming language you are familiar with)? I enjoyed creating the LoveBits project and would love to see some of your ideas in the comments below!

Further Reading

  • If Hemingway wrote JavaScript,” Angus Croll
    This is one of my favorite books which I actually stumbled upon after LoveBits. It’s about several famous poets and artists, and how they would have written JavaScript code snippets. It’s hilarious!
Smashing Editorial
(rb, ra, il)


Source: Smashing Magazine

How to Add Auth to Your PWA with Okta and Stencil

This article was originally published on OKTA Blog. Thank you for supporting the partners who make SitePoint possible.

Progressive Web Applications (PWAs) are the newest technology on the web dev block, and they’ve arrived just in time to solve a growing problem. Many companies are struggling to keep isolated development teams across their organization up-to-date when new features are released. Some companies are even trying to decide if it’s worth the cost to develop both a web app and a mobile application. Not surprisingly, it’s a headache most companies are looking to avoid. PWAs can give companies a lot of the features they need from a mobile app without the need to manage multiple teams and codebases.

A PWA performs spectacularly when on a fast connection, and still performs well when offline or on Wi-Fi that’s not really fast enough to be called Wi-Fi (sometimes called “Lie-Fi”). It does so via caching and a JavaScript “Service Worker” that intercepts server calls and tries to serve the data from cache first, then when the server finally responds, it will replace the cached data with possibly “fresher” data from the server.

Recently, the Ionic team released a new project called Stencil. Stencil is a compiler that generates standards-compliant web components. Unlike most JavaScript frameworks, it doesn’t deliver a “framework” of code to the browser. It simply takes the code you write and uses its compiler to create vanilla components. You can also use Stencil’s compiler with your favorite framework. The Stencil starter project is the easiest way to get started with Stencil and produces a base application that scores nearly a 100% score on Lighthouse’s progressive web app scorecard.

To get started building a PWA using Stencil, clone the starter application and detach it from the GitHub remote.

WARNING: Stencil is not at a 1.0 release yet (as of this writing). So be aware that if you continue, you’re in early-adopter territory. If you find bugs, submit an issue.

Set Up the Starter Application

git clone https://github.com/ionic-team/stencil-starter.git first-stencil
cd first-stencil
git remote rm origin

Then, install all the dependencies that your new Stencil app will need.

npm install

You may see a couple of warnings from node-pre-gyp around fsevents. There’s nothing to see here. This is just to get around a nasty little npm bug.

Next, add the Okta Auth SDK (via CDN) to the bottom of the index.html page, right before the closing </body> tag.

<script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/1.8.0/okta-auth-js.min.js" type="text/javascript"></script>

While there is an npm package for Okta’s Auth SDK, Stencil has a hard time compiling it. Overall it works better for now if you just use the CDN to include it.

If you’re like me, the next thing you’ll want to do is run npm start and check the site with Lighthouse. If you do, you’ll notice that the score is kind of low. In particular, it doesn’t register a service worker or return a 200 when offline. That’s because it’s a development build, and generally, you don’t want the service worker intercepting server calls and returning cached data in development.

To ensure an accurate depiction of the kind of PWA you get out of the box with Stencil, make sure to run a production build using npm run build. Once you do, you’ll see a www folder and inside that folder, you’ll see a sw.js file. That’s your service worker!

Set Up Your Okta Application

If you haven’t already done so, create a free-forever developer account.

Once you’ve registered, click on Applications in the top menu. Then click Add Application.

Application Listing Screen

You will then be taken to the application creation wizard. Choose Single-Page App and click Next at the bottom.

Create Application Screen SPA

On the next screen, you’ll see the default settings provided by the single-page application template. Change the name of the application to something more descriptive, like “Stencil SPA”. Also, change the base URIs and the login redirect URIs settings to use port 3333 because that’s where your application will be running. The rest of the default settings are fine.

Application Settings Screen

Click Done at the bottom.

Select your newly created application from the listing, and click on the General tab to view the general settings.

General Settings Client Id

At the bottom, you’ll see a Client ID setting (yours won’t be blurred out, obviously). Copy this to use in your Stencil application. You will also need your Okta organization URL, which you can find at the top right of the dashboard page. It will probably look something like “https://dev-XXXXXX.oktapreview.com”.

Add the Authentication Component

In the components folder, add a new folder called app-auth. This is where your login page component will go. You can call it whatever you want, I’m just following the naming conventions set out by the starter app here. I’d definitely recommend deciding on a naming convention early and sticking with it.

Inside the newly created app-auth folder create two files: app-auth.css and app-auth.tsx. Start by creating the shell of the app-auth.tsx file.

import { Component } from '@stencil/core';

@Component({
  tag: 'app-auth',
  styleUrl: 'app-auth.css'
})
export class AppAuth {
  render() {
    return <div>Hello</div>;
  }
}

If you are like I was, you might be thinking, “What kind of Frankenstein framework is this?”

You’ll notice the @Component decorator over the AppAuth class declaration like Angular, and then a render() method at the bottom like React. To me, that’s the beauty of Stencil. It takes some of the best parts of both popular frameworks and uses them to compile reusable components!

Add a Login Form

Next, you’ll add the JSX (that’s right, I said it) to the new component. Change the render() method to:

render() {
  return (
    <form class="app-auth">
      <div class="form-item">
        <label>
          Username:
          <input type="text" name="username" autocomplete="username" />
        </label>
      </div>
      <div class="form-item">
        <label>
          Password:
          <input
            type="password"
            name="password"
            autocomplete="current-password"
          />
        </label>
      </div>
      <div class="form-actions">
        <button type="button" onClick={() => this.login()}>
          Login
        </button>
      </div>
    </form>
  );
}

This is just a regular JSX form, but the login button’s onClick event is currently wired to function that doesn’t exist.

Add the Login Method’s Dependencies

Before you create that function, you’ll need to set up the OktaAuth JavaScript object to call the Okta API for authentication. You’ll add the object to the component’s state, so right below the class declaration, add the following line:

@State() authClient: any;

You will also have to import the @State() decorator. This is is used for values related to the internal state of the component. In the first import statement add State to the deconstruction list.

import { Component, State } from '@stencil/core'

You’ll also need to get the username and password values from the form itself, so add an @Element() to the code right below that @State() like you just created, so it read like this:

@State() authClient: any;
@Element() host: HTMLElement;

Then also add the @Element() decorator to the import so it reads:

import { Component, State, Element } from '@stencil/core';

One last thing that the login() function will need is access to the router, so you can redirect the user to their profile page if their authentication is successful. You’ll need a class property, so add it right below the @Element.

@State() authClient: any;
@Element() host: HTMLElement;
@Prop() history: RouterHistory;

To import it, add the @Prop() decorator to the main import and then import the RouterHistory from @stencil/router right below the core import statement. The @Prop decorator is used to define properties that can be passed in to your component. In this case, it’s not a passed in value, but it could be if need be. Your final import section should read:

import { Component, Prop, State, Element, Listen } from '@stencil/core';
import { RouterHistory } from '@stencil/router';

Finally, to use the OktaAuth JavaScript library you brought in from the CDN, add a declaration for it right below the import statements.

declare const OktaAuth: any;

Add the Login Method

Now you included everything you’ll need to get the login function to authenticate users with your Okta organization. First, set up the OktaAuth object in the constructor of the AppAuth class. Right below the property for the RouterHistory object, add:

constructor() {
  this.authClient = new OktaAuth({
    clientId: '{yourClientId}',
    url: 'https://{yourOktaDomain}.com',
    issuer: 'default'
  });
}

You can get your Client ID from that general settings page of your Okta application.

The post How to Add Auth to Your PWA with Okta and Stencil appeared first on SitePoint.


Source: Sitepoint

Building DApps with Ethereum: Creating, Deploying TNS Tokens

In part 1 of this tutorial series on building DApps with Ethereum, we bootstrapped two versions of a local blockchain for development: a Ganache version, and a full private PoA version.

In this part, we’ll dive right into it and build and deploy our TNS token — the token users will use to vote on proposals in the Story DAO.

Prerequisites

Have a Ganache version up and running, as per the previous part. Alternatively, have any local version of a blockchain running if you’re not following along from the first part, but make sure you can connect to it with tools we’ll need.

We’ll assume you have a working private blockchain and the ability to type commands into its console and the operating system’s terminal via the Terminal app or, on Windows, an app like Git Bash, Console, CMD Prompt, Powershell, etc.

The Basic Dependencies

To develop our application, we can use one of several frameworks and starter kits at our disposal: Dapp, eth-utils, Populus, Embark … and so on. But we’ll go with the current king of the ecosystem, Truffle.

Install it with the following:

npm install -g truffle

This will make the truffle command available everywhere. Now we can start the project with truffle init.

Starting the Token

Let’s get right into it and build our token. It’ll be a somewhat standard cookie-cutter ERC20 token with a twist. (You’ll see which twist lower in this post.) First, we’ll pull in some dependencies. The OpenZeppelin libraries are battle-tested high quality solidity contracts usable for extending and building contracts from.

npm install openzeppelin-solidity

Next, let’s create a new token file:

truffle create contract TNSToken

The default template that truffle generates here is a little out of date, so let’s get it updated:

pragma solidity ^0.4.24;

contract TNStoken {
    constructor() public {

    }
}

Up until now, the constructor of the token contract was supposed to be called the same as the contract itself, but for clarity it was changed to constructor. It should also always have a modifier telling the compiler who is allowed to deploy and interact with this contract (public meaning everyone).

SafeMath

The only Zeppelin contract we’ll be using in this case is their SafeMath contract. In Solidity, we import contracts with the import keyword, while the compiler will generally not require a full path, only a relative one, like so:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

contract TNStoken {
    using SafeMath for uint256;
    constructor() public {

    }
}

So, what is SafeMath? Long ago, there was an issue of 184 billion bitcoins being created because of a math problem in code. To prevent issues even remotely similar to these (not that this one in particular is possible in Ethereum), the SafeMath library exists. When two numbers are of the MAX_INT size (i.e. the maximum possible number in an operating system), summing them up would make the value “wrap around” to zero, like a car’s odometer being reset to 0 after reaching 999999 kilometers. So the SafeMath library has functions like these:

/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
  c = a + b;
  assert(c >= a);
  return c;
}

This function prevents this issue: it checks whether the sum of two numbers is still bigger than each of the two operands.

While it’s not too easy to make such silly mistakes when writing Solidity contracts, it’s still better to be safe than sorry.

By using SafeMath for uint256, we replace the standard uint256 numbers in Solidity (256bit unsigned — a.k.a. positive-only — whole numbers) with these “safe” versions. Instead of summing numbers like this: sum = someBigNumber + someBiggerNumber, we’ll be summing them like this: sum = someBigNumber.add(someBiggerNumber), thereby being safe in our calculations.

ERC20 from Scratch

With our math made safe, we can create our token.

ERC20 is a standard with a well-defined interface, so for reference, let’s add it into the contract. Read about the token standards here.

So the functions that an ERC20 token should have are:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

contract ERC20 {
    function totalSupply() public view returns (uint256);
    function balanceOf(address who) public view returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    function allowance(address owner, address spender) public view returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract TNStoken {

    using SafeMath for uint256;

    constructor() public {

    }
}

This might seem complex, but it’s actually very simple. This is a “directory” of functions our token needs to have, and we’ll build them one by one, explaining what each of them means. Consider the above an interface for our token. We’ll see how and why this is useful when we create the Story DAO application.

Basic balances

Let’s start. A token is actually just a “spreadsheet” in the Ethereum blockchain, like this:

| Name | Amount |
|:--|:--|
| Bruno | 4000 |
| Joe | 5000 |
| Anne | 0 |
| Mike | 300 |

So let’s create a mapping, which is essentially exactly like a spreadsheet in the contract:

mapping(address => uint256) balances;

According to the interface above, this needs to be accompanied by a balanceOf function, which can read this table:

function balanceOf(address _owner) public view returns (uint256) {
    return balances[_owner];
}

The function balanceOf accepts one argument: _owner is public (can be used by anyone), is a view function (meaning it’s free to use — does not require a transaction), and returns a uint256 number, the balance of the owner of the address sent in. Everyone’s balance of tokens is publicly readable.

Total supply

Knowing the total supply of the token is important for its users and for coin tracking applications, so let’s define a contract property (variable) to track this and another free function through which to read this:

uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
    return totalSupply_;
}

The post Building DApps with Ethereum: Creating, Deploying TNS Tokens appeared first on SitePoint.


Source: Sitepoint

Better Collaboration By Bringing Designers Into The Code Review Process

Better Collaboration By Bringing Designers Into The Code Review Process

Better Collaboration By Bringing Designers Into The Code Review Process

Ida Aalen

2018-07-10T13:50:26+02:00
2018-07-10T14:35:58+00:00

Smooth collaboration between developers and designers is something everyone aspires to, but it’s notoriously difficult. But with today’s advanced web, it’s difficult — if not impossible — to build a truly great product without collaborating across disciplines. Because of the range of technologies required to build a product, the product can only truly succeed when all disciplines — developers and designers, content creators, and user experience strategists — are deeply involved from the early stages of the project. When this happens, all ends of what it takes to build a product come naturally together into a unified whole, and a thus great product.

Because of this, no one is really promoting waterfall processes anymore. Nevertheless, involving other people early on, especially people from other disciplines, can feel scary. In the worst case scenario, it leads to “design by committee.”

Moreover, both designers and content strategists often have backgrounds in fields in which a sole creative genius is still the ideal. Having someone else proof your work can feel like a threat to your creativity.

So how can you involve people early on so that you’re avoiding the waterfall, but also making sure that you’re not setting yourself up for design by committee? I found my answer when learning about code reviews.

The Aha! Moment

In July 2017, I founded Confrere together with two developers, and we quickly hired our first engineer (I’m not a developer myself, I’m more of a UX or content designer). Our collaboration was running surprisingly smoothly, so much so that at our retrospectives, the recurring theme was that we all felt that we were “doing it right.”


Three people are smiling and sitting next to each other around a computer. From left to right, they are Dag-Inge (CTO), Ida (CPO) and Ingvild (Sr. Engineer).
Dag-Inge (CTO), myself (CPO) and Ingvild (Sr. Engineer). (Large preview)

I sat down with my colleagues to try to pinpoint what exactly it was that we were “doing right” so that we could try to preserve that feeling even as our company grew and our team expanded. We came to the realization that we all appreciated that the whole team was involved early on and that we were being honest and clear in our feedback to each other. Our CTO Dag-Inge added: “It works because we’re doing it as peers. You’re not being berated and just getting a list of faults”.

The word “peer” is what gave me the aha moment. I realized that those of us working within UX, design, and content have a lot to learn from developers when it comes to collaboration.

Peer reviewing in the form of code reviews is essential to how software gets built. To me, code reviews offer inspiration for improving collaboration within our own fields, but also a model for collaborating across fields and disciplines.

If you’re already familiar with code reviews, feel free to skip the next section.

What Is A Code Review?

A code review can be done in various ways. Today, the most typical form of code review happens in the way of so-called pull requests (using a technology called git). As illustrated below, the pull requests let other people on the team know that a developer has completed code that they wish to merge with the main code base. It also allows the team to review the code: they give feedback on the code before it gets merged, in case it needs improvement.

Pull requests have clearly defined roles: there is an author and a reviewer(s).


Ingvild and Dag-Inge is setting next to each other and smiling. An arrow indicated that Ingvild has sent code to Dag-Inge.
Ingvild (the author) requests a review from Dag-Inge (the reviewer). (Large preview)

As an example, let’s say our senior engineer Ingvild has made a change to Confrere’s sign-up flow. Before it is merged into the main code base and gets shipped, she (the author) creates a pull request to request a review from our CTO Dag-Inge (the reviewer). He won’t make any changes to her code, only add his comments.


Ingvild and Dag-Inge is setting next to each other. An arrow indicates that Dag-Inge has sent comments on code back to Ingvild.
Dag-Inge comments on Ingvild’s code. (Large preview)

It’s up to Ingvild how she wants to act on the feedback she received in the review. She’ll update her pull request with the changes she sees fit.


Ingvild and Dag-Inge are sitting next to each other. An arrow indicates that Ingvild is sending back her code to Dag-Inge, having looked through the code he commented on.
Ingvild updates her code with the changes she sees fit in light of Dag-Inge’s comments. (Large preview)

When the reviewer(s) approve the pull request, Ingvild can then merge her changes with the main code base.


Ingvild and Dag-Inge are sitting next to each other. A thumbs-up is displayed on the code review Dag-Inge has sent to Ingvild. And arrow indicates she pushes this code to the main repository.
After Dag-Inge gives the thumbs up, Ingvild can push the fix to production. (Large preview)

Why Bother Doing Code Review?

If you’ve never done code review, the process above might sound bureaucratic. If you have doubts, here’s a ton of blog posts and academic research about the advantages of code review.

Code reviews set the tone for the entire company that everything we do should be open to scrutiny from others, and that such scrutiny should be a welcome part of your workflow rather than viewed as threatening.

Bruce Johnson, co-founder of Full Story

Code review reduces risk. Having someone proof your work, and also knowing someone will proof your work, helps weed out
 errors and
 heightens quality. In addition, it ensures consistency and helps every team member familiarize with more of the code base.

When done right, code review also builds a culture for collaboration and openness. Trying to understand and critique other people’s work is an excellent way to learn, and so is getting honest feedback on your work.

Always having at least two people look over the code also curtails ideas of “my” code 
and “your” code.
 It’s our code.

Considering these advantages, a review shouldn’t just be for code.

Review Principles For All Disciplines, Not Just Code

With reviews, there is always one author and one or more reviewers. That means you can involve people early on without falling into design by committee.

First, I have to mention two important factors which will affect your team’s ability to do beneficial reviews. You don’t necessarily have to have mastered them, but as a minimum, you should aspire to the following:

  • You and your colleagues respect each other and each other’s disciplines.
  • You’re sufficiently self-assured in your own role so that you feel like you can both give and receive criticism (this is also connected to the team’s psychological safety).

Even if we’re not reviewing code, there’s a lot to learn from existing best practices for code reviews.

Within our team, we try to adhere to the following principles when doing reviews:

  1. Critique the work, 
not the author.
  2. Be critical, but remain 
affable and curious.
  3. Differentiate between a) Suggestions b) Requirements, c) Points that need discussion or clarification.
  4. Move discussions from
 text to face-to-face. (Video counts)
  5. Don’t forget to 
praise the good parts! What’s clever, creative, solid, original, funny, nice, and so on?

These principles weren’t actually written down until after we discussed why our collaboration was working so well. We all felt we were allowed to and expected to ask questions and suggest improvements already, and that our motivations were always about building something great together, and not about criticising another person.

Because we were being clear about what kind of feedback we were giving, and also remembered to praise each other’s good work, doing reviews was a positive force rather than a demotivating one.

An Example

To give you an idea of how our team uses review across disciplines and throughout a process, let’s look at how the different members of our team switched between the roles of author and reviewer when we created our sign-up flow.

Step 1: Requirements gathering

Author: Ida (UX)

Reviewers: Svein (strategy), Dag-Inge (engineering), Ingvild (engineering).


A whiteboard is showing rough sketches of a sign-up form. A man (Svein) and a woman (Ingvild) are smiling and discussing.
The team gathered around the whiteboard. Svein (CEO) to the left, Ingvild (Sr. Eng), to the right. (Large preview)

Whiteboard sessions can be exhausting if there’s no structure to them. To maintain productivity and creativity, we use the author/reviewer structure, even for something as seemingly basic as brainstorming on a whiteboard. In this case, in which we were coming up with the requirements for our sign-up flow, I got to be the author, and the rest of the team gave their feedback and acted as reviewers. Because they also knew they’d be able to review what I came up with in step 2 (plenty more opportunity for adjustments, suggestions, and improvements), we worked swiftly and were able to agree upon the requirements in under 2 hours.

Step 2: Mockup with microcopy

Author: Ida (UX)

Reviewers: Ingvild (engineering), Eivind (design), Svein (strategy).


A screenshot of a Google Doc mocking up a sign-up form with comments from team members Ingvild and Ida.
By mocking up in Google docs, it’s easy for people from all disciplines to provide feedback early on. (Large preview)

As an author, I created a mockup of the sign-up flow with microcopy. Did the sign-up flow make sense, from both the user and engineering perspective? And how could we improve the flow from a design and frontend perspective? At this stage, it was essential to work in a format in which it would be easy for all disciplines to give feedback (we opted for Google Docs, but it could also have been done with a tool like InvisionApp).

Step 3: Implementing the sign-up flow

Author: Ingvild (engineering)

Reviewer: Ida (UX) and Dag-Inge (engineering).

We had agreed upon the flow, the input fields, and the microcopy, and so it was up to Ingvild to implement it. Thanks to Surge, we can automatically create preview URLs of the changes so that people who can’t read code are able to give feedback at this stage as well.

Step 4: User testing

Author: Ida (UX)

Reviewer: The users.


Two women (Ida and a user) sitting next to eachother in front of a laptop.
Ida doing user testing on a small budget. (Large preview)

Yes, we consider user testing a form of review. We brought our newly built sign-up flow face-to-face with actual users. This step gave us a ton of insight, and the most significant changes in our sign-up flow came as a result.

Step 5: Design

Author: Eivind (design)

Reviewers: Ingvild (engineering) and Ida (UX).


A screenshot from Slack. Eivind, the designer, has posted a screenshot, and Ida replies with enthusiasm.
The first version of the sign-up flow was based on existing design components. In this stage, Eivind developed some new components to help improve the design. (Large preview)

When design suddenly shows up here in step 5, it might look a lot like a waterfall process. However, our designer Eivind had already been involved as a reviewer since step 2. He gave a bunch of useful feedback at that stage and was also able to start thinking about how we could improve the design of the sign-up flow beyond the existing modules in our design system. At this step, Eivind could also help solve some of the issues that we identified in the user testing.

Step 6: Implementation

Author: Ingvild (engineering)

Reviewer: Eivind (design), Ida (UX) and Dag-Inge (engineering).

And then we’re back to implementing.

Why review works

In summary, there’s always just one author, thus avoiding design by committee. By involving a range of disciplines as reviewers early on, we avoid having a waterfall process.

People can flag their concerns early and also start thinking about how they can contribute later on. The clearly defined roles keep the process on track.

Regular Review Walkthroughs

Taking inspiration from code walkthroughs, we also do regular review walkthroughs with different foci, guided by the following principles:

  • The walkthrough is done together.
  • One person is in charge of reviewing and documenting.
  • The idea is to identify issues, not necessarily to solve them.
  • Choose a format that gives as much context as possible, so that it’s easy to act upon the findings later (e.g. InvisionApp for visual reviews, Google Docs for text, and so on).

We’ve done review walkthroughs for things such as accessibility audits, reviewing feature requests, auditing the implementation of the design, and doing heuristic usability evaluations.

When we do our quarterly accessibility reviews, our accessibility consultant Joakim first goes through the interface and documents and prioritizes the issues he’s found in a shared Google Sheet. Joakim then walks us through the most important issues he’s identified.

Meeting face-to-face (or at least on video) to go through the issues helps create an environment for learning rather than a feeling of being supervised or micromanaged.


Three people in a sofa gathered around a laptop. They’re discussing and smiling.
Accessibility review: Joakim (right) walks Ingvild and Dag-Inge through the accessibility issues he found in his audit. (Large preview)

If you find yourself always being tied up with something that’s due for release, or fixing whatever is at the top of your inbox, reviews can help remedy that. If you set aside regular half days for reviewing work you’ve already done, you can identify issues before they become urgent. It can also help you refocus and make sure you’re priorities are keeping along the right lines. Your team should maybe not begin building that new feature before you’re confident that the existing features are living up to your standards.

User Testing Is A Form Of Review

An important motivation for code reviews is to reduce risk. By doing it every single time you introduce a change or add something new to your product, and not just when you suspect something is maybe not up to par, you diminish the chance of shipping bugs or subpar features. I believe we should look at user testing from the same perspective.

You see, if you want to reduce the risk of shipping with major usability issues, user testing has to be part of your process. Just having your UX designers review the interface isn’t enough. Several studies have found that even usability experts fail in identifying every actual usability problems. On average, 1 in 3 issues identified by experts were false alarms — they weren’t issues for users in practice. But worse, 1 in 2 issues that users did in fact have, were overlooked by the experts.

Skipping user testing is just as big a risk as skipping code review.

Does Review Mean Death To Creativity?

People working within design, user experience, and content often have educational backgrounds from art schools or maybe literature, in which the sole creator or creative artistic genius is hailed as the ideal. If you go back in history, this used to be the case for developers as well. Over time, this has changed by necessity as web development has grown more complex.

If you cling to the idea of creativity coming from somewhere deep within yourself, the idea of review might feel threatening or scary. Someone meddling in your half-finished work? Ouch. But if you think about creativity as something that can spring from many sources, including dialogue, collaboration, or any form of inspiration (whether from the outside or from someplace within you), then a review is only an asset and an opportunity.

As long as we’re building something for the web, there’s no way around collaborating with other people, be it within our own field or others. And a good idea will survive review.

Let’s create something great together.

Smashing Editorial
(rb, ra, yk, il)


Source: Smashing Magazine