What’s New This Week At CodeReviewVideos (2nd December 2016)

This week there have been three new videos.

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/login-part-2

Firstly, we continue with the Login Journey throughout the React / Redux / Redux Saga app we are building. In this video we cover a fundamental part of the stack – the Action. As we finish up this video, you will have dispatched your first Action.

Ok, but you may be wondering: why should that thrill me?

Because it’s at the heart of how our application will change its state. And that ultimately leads to applications that are many, many times more fun to work with than spaghetti slop.

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/login-part-3

Secondly, we go from dispatching this Action to handling that Action inside the world of Redux Saga.

This is the sort of stuff that’s absolutely MASSIVE in the jobs market right now. It’s popular for a reason. This will contribute greatly not only to your CV, but to making applications that you are highly more likely to enjoy working on.

https://codereviewvideos.com/course/php-7-1/video/nullable-types

And then the final video for the week covers probably the best thing about PHP 7.1 (released today btw):

Nullable types.

This is a major usability fix to a really nice, but largely unusable PHP 7.0 zero : Return types.

It also fixes scalar type declarations (int, string, bool, etc).

In other words, these will now become much more common as more and more migrate their codebases to PHP7.x, and with all these reported speed boosts, why wouldn’t you?

See you all next week 🙂

Chris

Symfony 3 Tutorials List

I’ve been asked a few times now if there is a Symfony 3 track available yet at Code Review Videos?

The answer is: yes!

It’s a work-in-progress, but there are already plenty of videos available.

Did you know? There are over 250 videos over 38 courses available right now.

I have been meaning to put together a more formally structured list, so here we go:

Symfony 3 Tutorials List

I’ll keep this list updated as new courses become available.

1. Introduction to Symfony 3

This is a beginner friendly Symfony 3 tutorial series.

I figured the best way to learn a new topic – something which can be quite boring and dry if you just learn the theory stuff – would be to immediately build something cool.

This course covers a lot of the fundamentals by building a reproduction of your GitHub profile.

By the end of this series you will have hands-on experience with:

  • Symfony 3
  • Routing
  • Twig Templates
  • Bootstrap 3
  • Symfony Services
  • Guzzle / RESTful API interactivity with GitHub

You don’t need a GitHub profile to take part in this course. You can use anyone’s profile. No excuses! Get learning, and welcome to Symfony 3 🙂

https://www.codereviewvideos.com/course/beginner-friendly-hands-on-symfony-3-tutorial

2. Doctrine

Doctrine allows you to create, read, update, and delete records from your database.

This is pretty much essential knowledge for any developer who needs to get things done.

Doctrine has a ton of unusual terms like hydration, persistence, fixtures, migrations, annotations… and without much context, it can be really confusing at first to figure out what they all mean.

We’ll go through an example of scraping Reddit’s PHP subreddit to explain a large number of these terms, and also in the process start relating entities together, and optimising our queries.

We also cover Doctrine’s Query Builder, and Doctrine Query Language (DQL), and discuss when might be appropriate to use one or the other.

This beginner friendly short course is all about demystifying Doctrine, and getting your started – quickly – with some hands on exercises to cover the basics of working with your database in Symfony 3.

https://www.codereviewvideos.com/course/doctrine-databasics

3. Forms

Symfony’s form component is incredibly versatile.

However, initially it can be a source of confusion.

In this course we cover the fundamentals of using the form – concepts which if you do not know or understand will make life much more difficult for you when you get to the more complex form types that Symfony can offer.

We start with a basic contact form, and then move on to adding and editing records in our database using Doctrine entities.

From there we will cover:

  • form styling – particularly integration with Bootstrap 3
  • form customisation
  • form fragments
  • data validation

And then on to a selection of examples which cover how to use Symfony’s form in a number of more realistic / real world ways.

https://codereviewvideos.com/course/beginner-s-guide-to-symfony-3-forms

Symfony 3 Intermediate Tutorials List

These tutorials are aimed at Symfony developers who are comfortable with the basics of a Symfony project.

It doesn’t matter whether that is Symfony 2, or Symfony 3. The syntax differences between Symfony2 and Symfony3 are not too difficult to figure out for any developer with a project or two under their belt.

If you are new to Symfony, I’d advise not starting with projects in this list to begin with. Make a simpler site, get a feel for the framework, then tackle these bigger projects without losing all your hair in the process.

Symfony 3 RESTful API

Probably the most important topic currently facing back-end Symfony developers is – how do I present my code via a RESTful API?

In Symfony there are a number of ways to solve this problem. In this series I show you one way using:

  • FOSRESTBundle
  • Testing using Behat 3 and PHPSpec 2
  • File Uploading using Flysystem
  • User management with FOSUserBundle
  • Handling login with LexikJWTBundle

This allows your front end developer(s) to interact with your Symfony 3 application using React, Ember, AngularJS, or any other technology your project needs.

https://codereviewvideos.com/course/symfony-3-rest-tutorial

New Courses

I have a long list of forthcoming courses, plenty to keep me going for the foreseeable future.

As a site member, you are more than welcome to submit course ideas and suggestions, and ask questions about video content.

What might not be immediately obvious is that all the previous courses on Symfony 2 topics here at Code Review Videos are in the most part, directly transferable to Symfony 3. There really wasn’t that huge of a change between Symfony 2 and Symfony 3. Not like when we went from Symfony 1 to Symfony 2 anyway.

I really hope you find these courses, and the rest of the content here to be extremely useful.

Don’t struggle learning all this stuff on your own. Let me help you learn Symfony faster and easier.

Site membership is $24.97 a month, or $49.97 a month for a team.

Why I Find JavaScript’s ES6 Destructuring So Fascinating

I spend a lot of time in PHP land.

PHP is a very useful and competent language, but I feel it’s fair to say it lacks somewhat in syntactical grace.

JavaScript’s ES6 on the other hand, is very elegant (to my eyes). This is a snippet from a React tutorial I have been following recently.

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit] || {
    isFetching: true,
    items: []
  };

There’s so much going on here.

As a recent migrant to ES6, I find this as intriguing as I do confusing.

The primary concept at work here is ES6 Destructuring. This is a really interesting technique to pull multiple pieces of data from arrays or objects in one go.

I found the concept initially confusing. I read this as a const  that is an object but has no variable name? Not quite.

It’s somewhat easier to understand this statement if we break it down one step further:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit];

I still feel this is complicated for someone, like me, who is new to Destructuring.

Let’s take an even simpler example:

const {a} = {a: 1, b: 2};

This looks a bit easier, a bit more understandable, I feel.

Here we have a regular JavaScript object: {a: 1, b: 2}

We want to create ourselves a constant containing the value of a from this object. A test might illustrate this a little better than words:

it('is possible to grab "a" from our object', () => {
  const ourObject = {a: 1, b: 2};
  let a = ourObject.a; 
  assert.equal(a, 1);
});

Destructuring gives us a short hand notation for this same concept:

it('is possible to grab "a" from our object in a more concise way', () => {
  const {a} = {a: 1, b: 2};
  assert.equal(a, 1);
});

By using the same key name inside the {} ‘s as that which exists on the object, ES6 will go ahead and create us a constant, called a with the value of 1. It essentially pulls out the value from the object and creates a variable / constant for us. Two steps, combined into one. This is one of those things I have immediately started to miss the most when working in PHP.

But what if we don’t want the new constant to be called a, but we do want it to still contain the value of a. Of course, ES6 has you covered here too:

it('is possible to rename "a"', () => {
  const {a: somethingElse} = {a: 1, b: 2};
  assert.equal(somethingElse, 1);
});

Seems a little back to front, but it does make sense. Pull out a as we’ve already covered, and re-name it to somethingElse.

You can see this in action in the React tutorial snippet:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit];

Here, items exists in the original data, and whilst we do want to use the value of items, we want to use a different reference for it – posts.

There are other things we could do with destructuring assignment, it really is quite an awesome concept.

Now we know about these two concepts, let’s take another look at the example:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit];

So we can see both of the above (pulling out by name, and pull-out-and-rename) happening in one statement here.

I found the postsBySubreddit name really confused me. If you can, disregard the name, and simply think of it as an object:

someObject[dynamicKey]

Then for me, it becomes a little easier to reason about:

  it('is possible to use a dynamic key', () => {
    
    let dynamicKey = 'key2';

    const someObject = {
      key1: 'a',
      key2: 'b',
      key3: 'c'
    };
    
    assert.equal(someObject[dynamicKey], 'b');
  });

postsBySubreddit is simply an object with potentially multiple keys.Each key will be the name of a subreddit: ‘php’, ‘reactjs’, ‘programming’ and so on.

We aren’t hard-coding the value of the key we need. We are instead asking for a key using the variable named selectedSubreddit, or dynamicKey in my example.

Don’t just take my word for this though, do look at the code. Unfortunately, I can’t link directly to the line(s) in question, but a quick ctrl+f on the linked page for ‘postsBySubreddit’ will get you to where you need to be.

selectedSubreddit will be one of these keys / subreddits. And all subreddit data will be an array, called items. But because we know that destructuring can rename a property for us, we can take advantage of this to rename items to posts .

isFetching and lastUpdated are both straightforward (in as much as any of this is straightforward), in that they are keys we want to create constants for.

Phew, that’s a lot happening in one statement.

But, remember, we actually broke this line down even further:

  const {
    isFetching,
    lastUpdated,
    items: posts
    } = postsBySubreddit[selectedSubreddit] 
  || {
    isFetching: true,
    items: []
  };

At this stage, we are really only concerned with the bit we haven’t yet covered, so I’ve reformatted it slightly to make it more obvious.

So we’ve done all this destructuring… OR (||) if we are unable to access postsBySubreddit[selectedSubreddit]  then create two constants:

isFetching: true,
items: []

Which would leave lastUpdated as undefined.

But don’t just take my word for it. Have a play around with this code and get a feel for what it is doing. Destructuring is definitely something you will start using more and more, but it’s initially confusing for sure.

JavaScript is moving fast (although I have heard some say that this is slowing down) and if you’re still finding your feet with PHP (or any other language) then I’d advise not to dig to deeply into ES6 just yet.

I’d argue that the transition to ES6 is going to be so challenging for some developers that we may possibly end up in a Python 2 / 3 situation in JavaScript land in the next few years. Which is why I believe the current form of JavaScript will be around for years to come.

Whichever form of JavaScript you choose to use, take the time to dig into the more functional concepts of JavaScript. It will truly help your programming – including your PHP – skills grow.

Notifications with React and Redux

Update 14/03/2017 – better implementation

After recently completing the excellent Reddit API tutorial from the official Redux documentation, I got to implementing a very similar set up in my own application.

One thing pointed out – but not really covered in the tutorial – is that sometimes (more often than I would like to believe, no doubt), communication between the front end and the back end will break.

Now, this sucks for many reasons. But from a user’s perspective, my reasoning is they won’t be as bothered if a little notification / pop up helpfully pops up and says: “heads up, that didn’t work… try again!”

Ok, so they try again and it doesn’t work again. Bad times. Maybe I need to work on my helpful error messages. Or better yet, fix the damn system.

But, message content and flaky systems aside, I decided I wanted to keep track of my notifications via Redux / the application state.

I figured this would be a solved problem. And it is. Kind of.

I found quite a few libraries that already solve this problem, in one way or another:

  • React Toolbox – Snackbar component
  • Igor Prado’s React Notification System
  • Patrick Burtchaell’s React Notifications

And there were others.

I also found a lot of not-React-ified code:

  • Toastr
  • Growler
  • Alertify JS

There’s probably a ton more. It seems like a common problem, with a variety of solutions.

But none of them were Redux-ready, right out of the box. At least, not that I could see.

Being new to Redux, I found this a little worrying (ack, how to do this myself?!) but also an interesting challenge (ack, with what I know so far, can I even do this myself?)

It’s worth noting that the React Toolbox Snackbar component does everything I need. Only, it has a material design theme to it, which I didn’t want. I also didn’t want to have to start styling it. If material design is your thing, that one is a solution.

Then there’s Alertify JS, which is a lightweight, snazzy little bit of code that nails the alerting / notification requirement perfectly. Only there’s a problem.

Alertify JS is an immediately-invoked function function expression (IIFE), which is cool in so much as it “just works”. But it’s not so cool in that I need to hook this up using Redux and I couldn’t figure out a way to make it work how I wanted.

The situation I have is that I want to dispatch a new action every time I need to display a notification. The action would hit the reducer, which would update the state. The state would flow down into my notification component and render a nice notification.

Alertify did not play well with this. As an IIFE, where could I put the alertify.log(‘some message’); method in a way that makes sense to be powered by props? If anywhere, it made most sense to put the call in the reducer switch statement. But that’s not redux.

So that was enough to have ruled out both React Toolbox, and Alertify JS. Onwards.

It boiled down to either React Notifications, or the React Notification System. Neither are pre-configured for Redux. Both fit the component / props requirement though.

Ultimately, I went with the React Notification System, simply as the styling looked like what I wanted. And I very much dislike doing any styling if I really can avoid it.

Ok, so some code.

import React, { PropTypes } from 'react';
import SomeOtherComponent from '../containers/SomeOtherComponent';
import NotificationContainer from '../containers/Notification';

const App = (props) => {
  return (
      <div className="body">
        <SomeOtherComponent props/>
        <NotificationContainer props/>
      </div>
  );
};

export default App;

First thing, add the Notification container on the top level component.

export const ADD_NOTIFICATION = 'ADD_NOTIFICATION';

The action type / constant that matches this action.

import { ADD_NOTIFICATION } from '../constants/ActionTypes';

export function addNotification(message, level) {
  return {
    type: ADD_NOTIFICATION,
    message,
    level
  };
}

Declaring the add notification action function is really straightforward. Just like any other redux action, a simple function containing a payload of data.

import {
  ADD_NOTIFICATION
} from '../constants/ActionTypes';

export default function notification(state = {}, action) {
  switch (action.type) {
    case ADD_NOTIFICATION:
      return Object.assign({}, state, {
        message: action.message,
        level: action.level
      });

    default:
      console.debug('notification reducer :: hit default', action.type);
      return state;
  }
}

The reducer is also very straightforward. As mentioned, I want a component that receives some props (that can change by way of a redux managed state update), and then display a new notification accordingly.

Also, don’t forget to enable this reducer by adding it to the rootReducer :

import { combineReducers } from 'redux';
import {routerReducer} from 'react-router-redux';
import otherReducer from './otherReducer';
import notification from './notificationReducer';

const rootReducer = combineReducers({
  routing: routerReducer,
  otherReducer,
  notification
});

export default rootReducer;

At this stage, I am not concerned with different types of notifications, or doing anything particularly fancy at all. Just some text, and a level, which is React Notification System’s terminology for success, info, warning, etc.

Notice also, the console.debug  statement on the default switch  case? That’s because of this.

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNotification } from '../actions/notificationActions';
import NotificationSystem from 'react-notification-system';

class NotificationContainer extends Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.notificationSystem = this.refs.notificationSystem;
  }

  componentWillReceiveProps(newProps) {
    const { message, level } = newProps.notification;
    this.notificationSystem.addNotification({
      message,
      level
    });
  }

  render() {
    return (
      <NotificationSystem ref="notificationSystem" />
    );
  }
}

function mapStateToProps(state) {
  return {
    notification: state.notification
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({
      addNotification
    }, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(NotificationContainer);

The real hard work of actually rendering a notification is given to React Notification System. I just need a way of adding a new notification whenever this component receives some new props.

Anyway, it all works really nicely so far.

I have a variety of actions that make use of fetch, and I’m doing this (simplified to show the dispatching):

return fetch('https://api.some-site.com/whatever.json', { method: 'POST' })
  .then(res => {
    dispatch(addedSomethingElse(somethingElse, res));
    dispatch(addNotification('happy days', 'success'));
  })
  .catch(err => {
    dispatch(failedAddingSomethingElse(somethingElse, err));
    dispatch(addNotification('it went horribly wrong', 'error'));
  });

I’m incredibly new to ES6, React, Redux, and most other parts of the ecosystem, so:

  • if I used any terminology incorrectly;
  • could improve my practices in any way;
  • or did this all wrong!

Then please do leave a comment and let me know 🙂