Serverless development with Node.js, AWS Lambda and MongoDB Atlas

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

The developer landscape has dramatically changed in recent years. It used to be fairly common for us developers to run all of our tools (databases, web servers, development IDEs…) on our own machines, but cloud services such as GitHub, MongoDB Atlas and AWS Lambda are drastically changing the game. They make it increasingly easier for developers to write and run code anywhere and on any device with no (or very few) dependencies.

A few years ago, if you crashed your machine, lost it or simply ran out of power, it would have probably taken you a few days before you got a new machine back up and running with everything you need properly set up and configured the way it previously was.

With developer tools in the cloud, you can now switch from one laptop to another with minimal disruption. However, it doesn’t mean everything is rosy. Writing and debugging code in the cloud is still challenging; as developers, we know that having a local development environment, although more lightweight, is still very valuable.

And that’s exactly what I’ll try to show you in this blog post: how to easily integrate an AWS Lambda Node.js function with a MongoDB database hosted in MongoDB Atlas, the DBaaS (database as a service) for MongoDB. More specifically, we’ll write a simple Lambda function that creates a single document in a collection stored in a MongoDB Atlas database. I’ll guide you through this tutorial step-by-step, and you should be done with it in less than an hour.

Let’s start with the necessary requirements to get you up and running:

  1. An Amazon Web Services account available with a user having administrative access to the IAM and Lambda services. If you don’t have one yet, sign up for a free AWS account.
  2. A local machine with Node.js (I told you we wouldn’t get rid of local dev environments so easily…). We will use Mac OS X in the tutorial below but it should be relatively easy to perform the same tasks on Windows or Linux.
  3. A MongoDB Atlas cluster alive and kicking. If you don’t have one yet, sign up for a free MongoDB Atlas account and create a cluster in just a few clicks. You can even try our M0, free cluster tier, perfect for small-scale development projects!).

Now that you know about the requirements, let’s talk about the specific steps we’ll take to write, test and deploy our Lambda function:

  1. MongoDB Atlas is by default secure, but as application developers, there are steps we should take to ensure that our app complies with least privilege access best practices. Namely, we’ll fine-tune permissions by creating a MongoDB Atlas database user with only read/write access to our app database.
  2. We will set up a Node.js project on our local machine, and we’ll make sure we test our lambda code locally end-to-end before deploying it to Amazon Web Services.
  3. We will then create our AWS Lambda function and upload our Node.js project to initialize it.
  4. Last but not least, we will make some modifications to our Lambda function to encrypt some sensitive data (such as the MongoDB Atlas connection string) and decrypt it from the function code.

A Short Note About VPC Peering

Continue reading %Serverless development with Node.js, AWS Lambda and MongoDB Atlas%


Source: Sitepoint

Exploring New Worlds In March: The Smashing Creativity Challenge Winners

Everybody’s an artist. That was the idea behind the Smashing Creativity Challenge which we announced at the beginning of the month. We asked the community to get their creative ideas flowing, and design a desktop wallpaper for March 2018. The only requirement: The wallpaper had to somehow relate to the theme “Exploring New Worlds”. How? Well, only your imagination was the limit.
Today, we are happy to present the result of this creative experiment, and the lucky winner, too, of course.
Source: Smashing Magazine

A Gentle Introduction to Higher-Order Components in React: Best Practices

This is the third part of the series on Higher-Order Components. In the first tutorial, we started from ground zero. We learned the basics of ES6 syntax, higher-order functions, and higher-order components. 

The higher-order component pattern is useful for creating abstract components—you can use them to share data (state and behavior) with your existing components. In the second part of the series, I demonstrated practical examples of code using this pattern. This includes protected routes, creating a configurable generic container, attaching a loading indicator to a component, etc. 

In this tutorial, we will have a look at some best practices and dos and don’ts that you should look into while writing HOCs. 

Introduction

React previously had something called Mixins, which worked great with the React.createClass method. Mixins allowed developers to share code between components. However, they had some drawbacks, and the idea was dropped eventually. Mixins were not upgraded to support ES6 classes, and Dan Abramov even wrote an in-depth post on why Mixins are considered harmful.

Higher-order components emerged as an alternative to Mixins, and they supported ES6 classes. Moreover, HOCs don’t have to do anything with the React API and are a generic pattern that works well with React. However, HOCs have flaws too. Although the downsides of higher-order components might not be evident in smaller projects, you could have multiple higher-order components chained to a single component, just like below.

You shouldn’t let the chaining get to the point where you are asking yourself the question: “Where did that props come from?” This tutorial addresses some of the common issues with higher-order component patterns and the solutions to get them right. 

The Problems With HOC

Some of the common problems concerned with HOCs have less to do with HOCs themselves, but rather your implementation of them. 

As you already know, HOCs are great for code abstraction and creating reusable code. However, when you have multiple HOCs stacked up, and if something looks out of place or if some props are not showing up, it’s painful to debug because the React DevTools give you a very limited clue about what might have gone wrong. 

A Real-World HOC Problem

To understand the drawbacks of HOCs, I’ve created an example demo that nests some of the HOCs that we created in the previous tutorial. We have four higher-order functions wrapping that single ContactList component. If the code doesn’t make sense or if you haven’t followed my previous tutorial, here is a brief summary of how it works.

withRouter is a HOC that’s part of the react-router package. It provides you access to the history object’s properties and then passes them as a prop. 

withAuth looks for an authentication prop and, if authentication is true, it renders the WrappedComponent. If authentication is false, it pushes ‘/login‘ to the history object.

withGenericContainer accepts an object as an input in addition to the WrappedComponent. The GenericContainer makes API calls and stores the result in the state and then sends the data to the wrapped component as props.

withLoader is a HOC that attaches a loading indicator. The indicator spins until the fetched data reaches the state.

BestPracticeDemo.jsx

Now you can see for yourself some of the common pitfalls of higher-order components. Let’s discuss some of them in detail.

Basic Dos and Don’ts

Don’t Forget to Spread the Props in Your HOC

Assume that we have an authenticated = { this.state.authenticated } prop at the top of the composition hierarchy. We know that this is an important prop and that this should make it all the way to the presentational component. However, imagine that an intermediate HOC, such as withGenericContainer, decided to ignore all its props. 

This is a very common mistake that you should try to avoid while writing higher-order components. Someone who isn’t acquainted with HOCs might find it hard to figure out why all the props are missing because it would be hard to isolate the problem. So, always remember to spread the props in your HOC.

Don’t Pass Down Props That Have No Existence Beyond the Scope of the HOC

A HOC might introduce new props that the WrappedComponent might not have any use for. In such cases, it’s a good practice to pass down props that are only relevant to the composed components. 

A higher-order component can accept data in two ways: either as the function’s argument or as the component’s prop. For instance, authenticated = { this.state.authenticated } is an example of a prop, whereas in withGenericContainer(reqAPI)(ContactList), we are passing the data as arguments.  

Because withGenericContainer is a function, you can pass in as few or as many arguments as you like. In the example above, a config object is used to specify a component’s data dependency. However, the contract between an enhanced component and the wrapped component is strictly through props. 

So I recommend filling in the static-time data dependencies via the function parameters and passing dynamic data as props. The authenticated props are dynamic because a user can be either authenticated or not depending on whether they are logged in or not, but we can be sure that the contents of the reqAPI object are not going to change dynamically. 

Don’t Use HOCs Inside the Render Method

Here is an example that you should avoid at all cost.

Apart from the performance hitches, you will lose the state of the OriginalComponent and all of its children on each render. To solve this problem, move the HOC declaration outside the render method so that it is only created once, so that the render always returns the same EnhancedComponent.

Don’t Mutate the Wrapped Component

Mutating the Wrapped Component inside a HOC makes it impossible to use the Wrapped Component outside the HOC. If your HOC returns a WrappedComponent, you can almost always be sure that you’re doing it wrong. The example below demonstrates the difference between mutation and composition.

Composition is one of React’s fundamental characteristics. You can have a component wrapped inside another component in its render function, and that’s what you call composition. 

Moreover, if you mutate the WrappedComponent inside a HOC and then wrap the enhanced component using another HOC, the changes made by the first HOC will be overridden. To avoid such scenarios, you should stick to composing components rather than mutating them.

Namespace Generic Propnames

The importance of namespacing prop names is evident when you have multiple stacked up. A component might push a prop name into the WrappedComponent that’s already been used by another higher-order component. 

Both the withMouse and withCat are trying to push their own version of name prop. What if the EnhancedComponent too had to share some props with the same name?

Wouldn’t it be a source of confusion and misdirection for the end developer? The React Devtools don’t report any name conflicts, and you will have to look into the HOC implementation details to understand what went wrong. 

This can be solved by making HOC prop names scoped as a convention via the HOC that provides them. So you would have withCat_name and withMouse_name instead of a generic prop name. 

Another interesting thing to note here is that ordering your properties is important in React. When you have the same property multiple times, resulting in a name conflict, the last declaration will always survive. In the above example, the Cat wins since it’s placed after { ...this.props }

If you would prefer to resolve the name conflict some other way, you can reorder the properties and spread this.props last. This way, you can set sensible defaults that suit your project.

Make Debugging Easier Using a Meaningful Display Name

The components created by a HOC show up in the React Devtools as normal components. It’s hard to distinguish between the two. You can ease the debugging by providing a meaningful displayName for the higher-order component. Wouldn’t it be sensible to have something like this on React Devtools?

So what is displayName? Each component has a displayName property that you can use for debugging purposes. The most popular technique is to wrap the display name of the WrappedComponent. If withCat is the HOC, and NameComponent is the WrappedComponent, then the displayName will be withCat(NameComponent)

An Alternative to Higher-Order Components

Although Mixins are gone, it would be misleading to say higher-order components are the only pattern out there that allow code sharing and abstraction. Another alternative pattern has emerged, and I’ve heard some say it’s better than HOCs. It’s beyond the scope of this tutorial to touch on the concept in depth, but I will introduce you to render props and some basic examples that demonstrate why they are useful. 

Render props are referred to by a number of different names:

  • render prop
  • children prop
  • function as a child
  • render callback

Here is a quick example that should explain how a render prop works.

As you can see, we’ve got rid of the higher-order functions. We have a regular component called Mouse. Instead of rendering a wrapped component in its render method, we are going to render this.props.children() and pass in the state as an argument. So we are giving Mouse a render prop, and the render prop decides what should be rendered.

In other words, the Mouse components accept a function as the value for the children props. When Mouse renders, it returns the state of the Mouse, and the render prop function can use it however it pleases. 

There are a few things I like about this pattern:

  • From a readability perspective, it’s more evident where a prop is coming from.
  • This pattern is dynamic and flexible. HOCs are composed at static-time. Although I’ve never found that to be a limitation, render props are dynamically composed and are more flexible. 
  • Simplified component composition. You could say goodbye to nesting multiple HOCs.

Conclusion

Higher-order components are patterns that you can use to build robust, reusable components in React. If you’re going to use HOCs, there are a few ground rules that you should follow. This is so that you don’t regret the decision of using them later on. I’ve summarized most of the best practices in this tutorial. 

HOCs are not the only patterns that are popular today. Towards the end of the tutorial, I’ve introduced you to another pattern called render props that is gaining ground among React developers. 

I won’t judge a pattern and say that this one is better than another. As React grows, and the ecosystem that surrounds it matures, more and more patterns will emerge. In my opinion, you should learn them all and stick with the one that suits your style and that you’re comfortable with.

This also marks the end of the tutorial series on higher-order components. We’ve gone from ground zero to mastering an advanced technique called HOC. If I missed anything or if you have suggestions/thoughts, I would love to hear them. You can post them in the comments. 


Source: Nettuts Web Development

Challenge: Build a React Component

The best way to learn a new skill is by putting it into practice. So here’s a challenge for you.

In this video from my course, Modern Web Apps With React and Redux, you’ll be challenged to create a React Component for displaying a Twitter avatar. You can try solving it on your own (with a hint), or you can let me walk you through the solution.

Challenge: Build a React Component

 

The Challenge

In this challenge, you need to build a React component for displaying a Twitter avatar. As you can see from the CodePen below, it just takes props.handle and prints out a little URL in an image tag. Very simple. 

What we need to do is write a profile component that uses a Twitter avatar component to show the image and the name. You can see the ReactDOM.render call for some hints.

If you’d like to try this challenge on your own, go ahead! Otherwise, read on as I walk you through the solution.

The Solution

Start by forking the pen so that you can build our own component, and then rename it by adding “MY SOLUTION”. 

In our ReactDOM call, we have a Profile component that we’re calling, and we give it a name and a handle.

So this should be pretty straightforward. Let’s go ahead and create a profile. I’m going to do this as a stateless component, just using a JavaScript function. If you want, you can actually use React.createClass, or the class syntax itself. Do whatever you like. But I like using stateless functions as much as possible.

This is going to take one parameter, which is our props object, but it’s going to have name and handle properties. So let’s go ahead and destructure that.

Then let’s return a div. And inside this div, let’s return an h1 with the name for this specific account. And underneath this, we will have a TwitterAvatar, which requires a handle property. So we will pass it a handle, which will be equal to the handle we have. 

There we go. It should be that simple. So save this in CodePen, and you can see that we get ReactJS and we get the Twitter avatar. 

CodePen solution showing ReactJS and its Twitter avatar

Let’s go ahead and change the name to Tuts+ and the Twitter handle to tutsplus, and you can see that it updates.

CodePen solution showing Tutsplus and its Twitter avatar

So, as you can see, we can change this to different names and Twitter avatars, and we can see this in action. Good job! You have built a very basic React component. It’s a good place to start in seeing how you can create components and use their properties, and also how you can pass those properties on to other components, to do some of the work for you.

Here’s the final pen showing the solution in full:

Watch the Full Course

React is a JavaScript library for building user interfaces that has taken the web development world by storm, and Redux is a great way of managing application state. In the full course, Modern Web Apps With React and Redux, you’ll learn all about how React, Redux and other leading modules fit together for a complete picture of app development.

It’s a comprehensive, four-hour course with 35 video lessons, and I’ll take you through the process of using these two libraries to build a complete web application from scratch. You’ll start with the simplest possible architecture and slowly build up the app, feature by feature. By the end, you’ll have created a complete flashcards app for learning by spaced repetition.

You can take this course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 440,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.


Source: Nettuts Web Development

Game AI: The Bots Strike Back!

The following is a short extract taken from our new book, HTML5 Games: Novice to Ninja, written by Earle Castledine. Access to the book is included with SitePoint Premium membership, or you can grab a copy in stores worldwide. You can check out a free sample of the first chapter here.

We have all the tools at our disposal now to make fantastically detailed worlds to explore and inhabit. Unfortunately, our co-inhabitants haven’t proved themselves to be very worthy opponents. They’re dumb: they show no emotion, no thought, no anima. We can instill these characteristics via graphics, animation, and above all, artificial intelligence (AI).

Artificial intelligence is a huge and extremely complex field. Luckily, we can get impressive results even with a lot more artificial than intelligence. A couple of simple rules (combined with our old friend Math.random) can give a passable illusion of intention and thought. It doesn’t have to be overly realistic as long as it supports our game mechanics and is fun.

Like collision detection, AI is often best when it’s not too good. Computer opponents are superhuman. They have the gift of omniscience and can comprehend the entire state of the world at every point in time. The poor old human player is only able to see what’s visible on the screen. They’re generally no match against a computer.

But we don’t let them know that! They’d feel bad, question the future of humanity, and not want to play our games. As game designers, it’s our job to balance and dictate the flow of our games so that they’re always fair, challenging, and surprising to the player.

Intentional Movement

Choosing how sprites move around in the game is great fun. The update function is your blank canvas, and you get godlike control over your entities. What’s not to like about that!

The way an entity moves is determined by how much we alter its x and y position every frame (“move everything a tiny bit!”). So far, we’ve moved things mostly in straight lines with pos.x += speed * dt. Adding the speed (times the delta) causes the sprite to move to the right. Subtracting moves it to the left. Altering the y coordinate moves it up and down.

To make straight lines more fun, inject a bit of trigonometry. Using pos.y += Math.sin(t * 10) * 200 * dt, the sprite bobs up and down through a sine wave. t * 10 is the frequency of the wave. t is the time in seconds from our update system, so it’s always increasing linearly. Giving that to Math.sin produces a smooth sine wave. Changing the multiplier will alter the frequency: a lower number will oscillate faster. 200 is the amplitude of the waves.

You can combine waves to get even more interesting results. Say you added another sine wave to the y position: pos.y += Math.sin(t * 11) * 200 * dt. It’s almost exactly the same as the first, but the frequency is altered very slightly. Now, as the two waves reinforce and cancel each other out as they drift in and out of phase, the entity bobs up and down faster and slower. Shifting the frequency and amplitude a lot can give some interesting bouncing patterns. Alter the x position with Math.cos and you have circles.

The important aspect of this is that movements can be combined to make more complex-looking behaviors. They can move spasmodically, they can drift lazily. As we go through this chapter, they’ll be able to charge directly towards a player, or to run directly away. They’ll be able to traverse a maze. When you combine these skills (a bobbing motion used in conjunction with a charge-at-player), or sequence them (run away for two seconds, then bob up and down for one second) they can be sculpted into very lifelike beings.

Waypoints

We need to spice up these apathetic ghosts and bats, giving them something to live for. We’ll start with the concept of a “waypoint”. Waypoints are milestones or intermediate target locations that the entity will move towards. Once they arrive at the waypoint, they move on to the next, until they reach their destination. A carefully placed set of waypoints can provide the game character with a sense of purpose, and can be used to great effect in your level design.

The waypoint-following bombs of Franco Ponticelli’s FlyMaze

Continue reading %Game AI: The Bots Strike Back!%


Source: Sitepoint

The 5 Most Popular Front-end Frameworks Compared

There’s a deluge of CSS front-end frameworks available nowadays. But the number of really good ones can be narrowed down to just a few. In this article, I’ll compare what I think are the five best front-end frameworks available today.

Each framework has its own strengths and weaknesses, and specific areas of application, allowing you to choose based on the needs of a specific project. For example, if your project is simple, there’s no need to use a complex framework. Also, many of the options are modular, allowing you to use only the components you need, or even mix components from different front-end frameworks.

The front-end frameworks I’m going to explore are presented based on their GitHub popularity, beginning with the most popular, which is, of course, Bootstrap.

Note that some of the information below will go out of date in the coming weeks and months – such as GitHub stars and version numbers – so be aware of this if you’re reading this article long after the publication date. Also note that the framework sizes are the minified sizes of the necessary CSS and JavaScript files.

1. Bootstrap

Bootstrap is the undisputed leader among the available front-end frameworks today. Given its huge popularity, which is still growing every day, you can be sure that this wonderful toolkit won’t fail you, or leave you alone on your way to building successful websites.

Front-end framework 1: Bootstrap

  • Creators: Mark Otto and Jacob Thornton.
  • Released: 2011
  • Current version: 4.0
  • Popularity: 121,374 stars on GitHub
  • Description: “Sleek, intuitive, and powerful front-end framework for faster and easier web development.”
  • Core concepts/principles: RWD and mobile first.
  • Framework size: 578 KB (precompiled zip folder)
  • Preprocessor: Sass
  • Responsive: Yes
  • Modular: Yes
  • Starting templates/layouts: Yes
  • Icon set: Not included
  • Extras/Add-ons: None bundled, but many third-party plugins are available.
  • Unique components: Jumbotron, Card
  • Documentation: Excellent
  • Customization: Option for separate files for Grid system and Reboot, easy customization with Sass; no online customizer
  • Browser support: Latest releases of Firefox, Chrome, Safari, IE810-11-Microsoft Edge.
  • License: MIT

Notes on Bootstrap

The main strength of Bootstrap is its huge popularity. Technically, it’s not necessarily better than the others in the list, but it offers many more resources (articles and tutorials, third-party plugins and extensions, theme builders, and so on) than the other four front-end frameworks combined. In short, Bootstrap is everywhere. And this is the main reason people continue to choose it.

Note: By saying “unique components”, I mean that they’re unique compared only to the front-end frameworks mentioned in this list.

2. Foundation by ZURB

Foundation is the second big player in this front-end framework comparison. With a solid company like ZURB backing it, this framework has a truly strong … well … foundation. After all, Foundation is used on many big websites including Facebook, Mozilla, Ebay, Yahoo! and National Geographic, to name a few.

Front-end framework 2: ZURB Foundation

  • Creators: ZURB
  • Released: 2011
  • Current version:6
  • Popularity: 26,956 stars on GitHub
  • Description: “The most advanced responsive front-end framework in the world”
  • Core concepts/principles: RWD, mobile first, semantic
  • Framework size: 197.5 KB
  • Preprocessors: Sass
  • Responsive: Yes
  • Modular: Yes
  • Starting templates/layouts: Yes
  • Icon set: Foundation Icon Fonts
  • Extras/Add-ons: Yes
  • Unique components: Icon Bar, Clearing Lightbox, Flex Video, Keystrokes, Joyride, Pricing Tables
  • Documentation: Good, with many additional resources available.
  • Customization: Basic GUI customizer
  • Browser support: Chrome, Firefox, Safari, IE9+; iOS, Android, Windows Phone 7+
  • License: MIT

Notes on Foundation

Foundation is a truly professional front-end framework with business support, training, and consulting offered. It also provides many resources to help you learn and use the framework faster and easier.

3. Semantic UI

Semantic UI is an ongoing effort to make building websites much more semantic. It utilizes natural language principles, thus making the code much more readable and understandable.

Front-end framework 3: Semantic UI

  • Creator: Jack Lukic
  • Released: 2013
  • Current version: 2.2
  • Popularity: 39,364 stars on GitHub
  • Description: “A UI component framework based around useful principles from natural language”
  • Core concepts/principles: Semantic, tag ambivalence, responsive
  • Framework size: 806 KB
  • Preprocessors: Less
  • Responsive: Yes
  • Modular: Yes
  • Starting templates/layouts: Yes, some basic starter templates are offered
  • Icon set: Font Awesome
  • Extras/Add-ons: No
  • Unique components: Divider, Flag, Rail, Reveal, Step, Advertisement, Card, Feed, Item, Statistic, Dimmer, Rating, Shape
  • Documentation: Very good, offering very well-organized documentation, plus a separate website that offers guides for getting started, customizing and creating themes
  • Customization: No GUI customizer, only manual customization
  • Browser support: Firefox, Chrome, Safari, IE10+ (IE9 with browser prefix only), Android 4, Blackberry 10
  • License: MIT

Notes on Semantic UI

Semantic is the most innovative and full-featured front-end framework among those discussed here. The overall structure of the framework and the naming conventions, in terms of clear logic and semantics of its classes, also surpasses the others.

Continue reading %The 5 Most Popular Front-end Frameworks Compared%


Source: Sitepoint

Smashing Newsletter #200: The Things We Learned

When we share our lessons learned, we can’t predict who is going to read them, but it can make all the difference in the world. I still vividly remember that day when I received an email from a school teacher in Johannesburg, South Africa, five or six years ago. Back then, they didn’t have any teaching materials available at their school, and interaction design was often taught on paper with a few outdated books from the 90s.
Source: Smashing Magazine

Eloquent Mutators and Accessors in Laravel

In this article, we’ll go through mutators and accessors of the Eloquent ORM in the Laravel web framework. After the introduction, we’ll go through a handful of examples to understand these concepts.

In Laravel, mutators and accessors allow you to alter data before it’s saved to and fetched from a database. To be specific, the mutator allows you to alter data before it’s saved to a database. On the other hand, the accessor allows you to alter data after it’s fetched from a database.

In fact, the Laravel model is the central place where you can create mutator and accessor methods. And of course, it’s nice to have all your modifications in a single place rather than scattered over different places.

Create Accessors and Mutators in a Model Class

As you’re familiar with the basic concept of mutators and accessors now, we’ll go ahead and develop a real-world example to demonstrate it.

I assume that you’re aware of the Eloquent model in Laravel, and we’ll use the Post model as a starting point of our example. If you haven’t created the Post model yet, let’s use the artisan command to create it.

That should create a model file at app/Post.php as shown below.

Let’s replace the contents of that file with the following.

As we’ve used the --migration option, it should also create an associated database migration. Just in case you are not aware, you can run the following command so that it actually creates a table in the database.

In order to run examples in this article, you need to create name and published_at columns in the post table. Anyway, we won’t go into the details of the migration topic, as it’s out of the scope of this article. So we’ll get back to methods that we are interested in.

Firstly, let’s go through the mutator method.

As we discussed earlier, the mutators are used to alter data before it’s saved to a database. As you can see, the syntax of the mutator method is set{attribute-name}Attribute. Of course, you need to replace {attribute-name} with an actual attribute name.

The setNameAttribute method is called before the value of the name attribute is saved in the database. To keep things simple, we’ve just used the strtolower function that converts the post title to lowercase before it’s saved to the database.

In this way, you could create mutator methods on all columns of your table. Next, let’s go through the accessor method.

If mutators are used to alter data before it’s saved to a database, the accessor method is used to alter data after it’s fetched from a database. The syntax of the accessor method is the same as that of the mutator except that it begins with the get keyword instead of the set keyword.

Let’s go through the accessor method getNameAttribute.

The getNameAttribute method will be called after the value of the name attribute is fetched from the database. In our case, we’ve just used the ucfirst method to alter the post title.

And that’s the way you are supposed to use accessors in your models. So far, we’ve just created mutator and accessor methods, and we’ll test those in the upcoming section.

Mutators in Action

Let’s create a controller at app/Http/Controllers/MutatorController.php so that we can test the mutator method that we created in the earlier section.

Also, you need to create an associated route in the routes/web.php file to access it.

In the index method, we’re creating a new post using the Post model. It should set the value of the name column to post title as we’ve used the strtolower function in the setNameAttribute mutator method.

Date Mutators

In addition to the mutator we discussed earlier, the Eloquent model provides a couple of special mutators that allow you to alter data. For example, the Eloquent model in Laravel comes with a special $dates property that allows you to automatically convert the desired columns to a Carbon date instance.

In the beginning of this article, we created the Post model, and the following code was part of that class.

As you probably know, Laravel always creates two date-related fields, created_at and updated_at, with each database migration. And it converts those values to a Carbon date instance as well.

Let’s assume that you have a couple of fields in a table that you would like to treat as date fields. In that case, you just need to add column names in the $dates array.

As you can see in the above code, we’ve added the published_at column in the $dates array, and it makes sure that the value of that column will be converted to a Carbon date instance.

Accessors in Action

To see accessors in action, let’s go ahead and create a controller file app/Http/Controllers/AccessorController.php with the following contents.

Also, let’s create an associated route in the routes/web.php file to access it.

In the index method, we’ve used the Post model to load an example post in the first place.

Next, we’re inspecting the value of the name column, and it should start with an uppercase letter as we’ve already defined the accessor method getNameAttribute for that column.

Moving further, we’ve inspected the value of the published_at column, and that should be treated as a date. Due to that, Laravel converts it to a Carbon instance so that you can use all the utility methods provided by that library. In our case, we’ve used the getTimestamp method to convert the date into a timestamp.

And that brings us to the end of this article!

Conclusion

Today, we’ve explored the concepts of mutators and accessors of the Eloquent ORM in Laravel. It provides a nice way to alter data before it’s saved to and fetched from a database.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Don’t hesitate to share your thoughts using the feed below!


Source: Nettuts Web Development

A Gentle Introduction to HOC in React: Learn by Example

This is the second part of the series on Higher-Order Components (HOCs). Today, I will cover different higher-order component patterns that are useful and implementable. With HOCs, you can abstract redundant code into a layer of higher order. However, like any other patterns out there, it will take some time to get used to HOCs. This tutorial will help you bridge that gap. 

Prerequisite

I recommend that you follow the first part of the series if you haven’t already. In the first part, we talked about HOC syntax basics and everything you need to get started with higher-order components.

In this tutorial, we will be building on top of the concepts that we’ve already covered in part one. I’ve created several sample HOCs which are practically useful, and you can incorporate these ideas into your project. Code snippets are provided in each section, and a working demo of all the practical HOCs discussed in this tutorial is provided at the end of the tutorial.

You can also fork the code from my GitHub repo.

Practical Higher-Order Components

Since HOCs create a new abstract container component, here is the list of things that you can normally do with them:

  • Wrap an element or component around a component.
  • State abstraction.
  • Manipulate props, e.g. adding new props and modifying or removing existing props.
  • Props validation to create.
  • Use refs to access instance methods.

Let’s talk about these one by one. 

HOC as a Wrapper Component

If you recall, the final example in my previous tutorial demonstrated how a HOC wraps the InputComponent with other components and elements. This is useful for styling and for reusing logic wherever possible. For instance, you can use this technique to create a reusable loader indicator or an animated transition effect that should be triggered by certain events. 

A Loading Indicator HOC

The first example is a loading indicator built using HOC. It checks whether a particular prop is empty, and the loading indicator is displayed until the data is fetched and returned.

LoadIndicator/LoadIndicatorHOC.jsx

LoadIndicator/LoadIndicatorDemo.jsx

This is also the first time that we’ve used the second parameter as input to the HOC. The second parameter, which I’ve named ‘loadingProp’, is used here to tell the HOC that it needs to check whether that particular prop is fetched and available. In the example, the isEmpty function checks whether the loadingProp is empty, and an indicator is displayed until the props are updated.

You have two options for passing down data to the HOC, either as a prop (which is the usual way) or as a parameter to the HOC.

Here is how I choose between the two. If the data doesn’t have any scope beyond that of the HOC and if the data is static, then pass them as parameters. If the props are relevant to the HOC and also to the wrapped component, pass them as usual props. I’ve covered more about this in my third tutorial.

State Abstraction and Prop Manipulation

State abstraction means generalizing the state to a higher-order component. All the state management of the WrappedComponent will be handled by the higher-order component. The HOC adds new state, and then the state is passed down as props to the WrappedComponent

A Higher-Order Generic Container

If you noticed, the loader example above had a component that made a GET request using the fetch API. After retrieving the data, it was stored in the state. Making an API request when a component mounts is a common scenario, and we could make a HOC that perfectly fits into this role.

GenericContainer/GenericContainerHOC.jsx

GenericContainer/GenericContainerDemo.jsx

The state has been generalized, and the value of the state is being passed down as props. We’ve made the component configurable too.

It accepts a configuration object as an input that gives more information about the API URL, the method, and the name of the state key where the result is stored. The logic used in componentWillMount() demonstrates using a dynamic key name with this.setState.

A Higher-Order Form

Here is another example that uses the state abstraction to create a useful higher-order form component. 

CustomForm/CustomFormDemo.jsx

CustomForm/CustomFormHOC.jsx

The example demonstrates how the state abstraction can be used along with a presentational component to make form creation easier. Here, the form is a presentational component and is an input to the HOC. The initial state of the form and the name of the state items are also passed as parameters. 

However, note that if there are multiple props with the same name, ordering is important, and the last declaration of a prop will always win. In this case, if another component pushes a prop named contact or contactList, that will result in a name conflict. So you should either namespace your HOC props so that they don’t conflict with the existing props or order them in such a way that the props that should have the highest priority are declared first. This will be covered in depth in the third tutorial.

Prop Manipulation Using HOC

Prop manipulation involves adding new props, modifying existing props, or ignoring them entirely. In the CustomForm example above, the HOC passed down some new props.

Similarly, you can decide to disregard props entirely. The example below demonstrates this scenario.

You can also do some validation/filtering props using this technique. The higher-order component decides whether a child component should receive certain props, or route the user to a different component if certain conditions are not met. 

A Higher-Order Component for Protecting Routes

 Here is an example of protecting routes by wrapping the relevant component with a withAuth higher-order component.

ProtectedRoutes/ProtectedRoutesHOC.jsx

ProtectedRoutes/ProtectedRoutesDemo.jsx

withAuth checks if the user is authenticated, and if not, redirects the user to /login. We’ve used withRouter, which is a react-router entity. Interestingly, withRouter is also a higher-order component that is used to pass the updated match, location, and history props to the wrapped component every time it renders. 

For instance, it pushes the history object as props so that we can access that instance of the object as follows:

You can read more about withRouter in the official react-router documentation.

Accessing the Instance via Refs

React has a special attribute that you can attach to a component or an element. The ref attribute (ref stands for reference) can be a callback function attached to a component declaration.

The callback gets invoked after the component is mounted, and you get an instance of the referenced component as the callback’s parameter. If you are not sure about how refs work, the official documentation on Refs and the DOM talks about it in depth.

In our HOC, the benefit of using ref is that you can get an instance of the WrappedComponent and call its methods from the higher-order component. This is not part of the typical React dataflow because React prefers communication via props. However, there are many places where you might find this approach beneficial. 

RefsDemo/RefsHOC.jsx

RefsDemo/RefsDemo.jsx

The ref callback attribute saves a reference to the WrappedComponent.

this.instance has a reference to the WrappedComponent. You can now call the instance’s method to communicate data between components. However, use this sparingly and only if necessary. 

Final Demo

I’ve incorporated all the examples in this tutorial into a single demo that you can use below. 

Summary

This is the end of the second tutorial on higher-order components. We learned a lot today about different HOC patterns and techniques, and went through practical examples that demonstrated how we could use them in our projects.

In the third part of the tutorial, you can look forward to some best practices and HOC alternatives that you should know of. Stay tuned until then. Share your thoughts in the comment box.


Source: Nettuts Web Development

How GDPR Will Change The Way You Develop

Europe’s imminent privacy overhaul means that we all have to become more diligent about what data we collect, how we collect it, and what we do with it. In our turbulent times, these privacy obligations are about ethics as well as law.
Web developers have a major role to play here. After all, healthy data protection practice is as much about the development side — code, data, and security — as it is about the business side of process, information, and strategy.
Source: Smashing Magazine