Eric L. Barnes

Single Page Laravel Application

Michael Calkins asked me on Twitter the following question:

I would love to see the processes and techniques you use when designing a SPA. UI/UX, API considerations, and those things.

I thought it was an interesting question and the answer could be a benefit to the community so I’m going to do my best to answer it by outlining how I setup a brand new single page Laravel application. My last two projects have been with BackBone but I’m not going to focus on the actual framework, more so, just the setup and techniques.

Directory Structure

First I setup my directory structure by putting all my files that need to be processed inside app/assets. Then sub folders for each major area such as javascript, styles (less/sass), vendor (bower or manually copied components), etc.

From here I used Grunt, Gulp, or whatever is the new hotness and setup all the processing tasks. This will output to the public directory and I recommend spending the time on setting up source maps from the beginning. This is something I wasn’t doing and it would be so nice to have now.

First Changes

I always use Blade templates and in my master layout.blade.php I set the following meta tags:

<meta name="env" content="{{ App::environment() }}">
<meta name="token" content="{{ Session::token() }}">

I use the environment as a flag for any features that should only be in production or for testing only in development. I typically use this for things like analytics tracking or in weird cases.

The token is used for CSRF when posting from your JavaScript. Here is an example app/javascripts/plugins/ajax.js:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  var token;
  if (!options.crossDomain) {
    token = $('meta[name="token"]').attr('content');
    if (token) {
      return jqXHR.setRequestHeader('X-CSRF-Token', token);
    }
  }
});

As you can see this just pulls in the token and is always included on any ajax requests.

API Considerations

For both Snappy and Wardrobe I put all my controllers in the app/controllers/api folder and these are only used for javascript communication. I do recommend keeping these very thin so you can easily reuse code in the future when you need a mobile app. :)

A side benefit of putting them all in their own folder is the ability to utilize Laravel’s routing and request filters:

Request::is('api/*')
Route::when('api/*’)

Here is an example of one of my controller edit methods:

public function putEdit($id)
{
  $response = $this->post->update(Auth::user(), Input::all());

  return $this->handleJsonResponse($response, ‘Your post has been saved’);
}

Then handleJsonResponse() is defined in the BaseController and simply finds out the type of response and returns based on this:

protected function handleJsonResponse($response, $success = 'It worked!')
{
  if ($response instanceof \Illuminate\Support\MessageBag)
  {
    return Response::json($response, 400);
  }

  return Response::json(['msg' => $success]);
}

This keeps everything really DRY and easy to maintain. Also by returning the validator it gets converted to JSON and is easily consumed in your JavaScript.

JavaScript

This area really depends on the framework you have chosen on how you set it up. I only have the following two tips:

  1. Pre-seed all your primary JSON.
  2. Abstract plugins

By pre-seeding all your primary models/collections this will save you on that initial load time of fetching all the records and getting the app up and running.

Plugins are a necessary evil. I recommend always wrapping them in your own code with a simple api that way it’s easier to replace out later.

In BackBone a common pattern is to use views for this and just instantiate it when you need it. Here is a good presentation that goes more in depth on this.

CSS

I’ve struggled writing good clean CSS. If I’m being completely honest a lot of times I end up with a mess on big projects. It starts off great but then a new feature here, a new feature there, and wham! a mess. :)

If I was starting a new app today I would follow an existing style guide such as the one GitHub published or Smacss.

Since I’m not a CSS wizard I do not want to steer anyone in the wrong direction. However, I do have one tip to share and that is use slightly obtrusive javascript. What this recommends is adding a js- class to all elements your JavaScript interacts with:

<a href=“#” class=“js-edit edit”>Edit</a>

On small apps this is over kill but if you plan on maintaining this for years to come this is very helpful for refactoring and noticing when selectors are used elsewhere.

UI/UX

I could be off base with this, but I feel the terms UI/UX are a little open for interpretation. If I ask 5 engineers to define it off the hip, they all would give me different answers.

To me this is the most important area of any application and I feel UI/UX is what drives emotion and leads people to an action. Most engineers are generally weak in this area. If thats you then your goal should be to get everything related to the design uniform and plan from the beginning for adjustments. This area is rarely static.

The design and usability is so important in any app. No matter if it’s open source or commercial this is where users spend 100% of their time. Users do not care about your code and all your fancy design patterns. They have a goal in mind and need the simplest and easiest way to achieve it. This is what makes or breaks a product. It’s also the hardest to get right.

The closer you are to the development of a feature the harder it is to notice little nuances. I’m no different. Anytime I complete a new feature I always ask for feedback before deploying. 9 times out of 10 the reviewer will spot something that I totally missed.

To reiterate, if you are week in this area get everything uniform and bring an expert in. If you don’t have the means of getting an expert then plan on spending lots of time thinking and getting feedback.

Is it really different?

I do not believe it’s that much different from building a “traditional app”. Instead of one you now have two, a backend for api endpoints and auth then the front-end or client for the end user.

Over a thousand words later I hope I’ve answered Michael’s question without opening up many more. :) Nevertheless if you do have questions don’t hesitate to get in touch.

Alyssa Mazzina writes:

Sleep is generally the first thing we sacrifice when we start to get busy. Eight hours of sleep is a full third of my valuable time! Come on! Ain’t nobody got time for that!

This post is a great reminder not only to founders but also developers. I struggle with getting enough sleep and I’ve been in this vicious cycle of staying up late during the week and then Friday night sleeping like 9 or 10 hours. I need an app that totally locks me out of my computer after 9pm. :-) When you first install the app it has my wife set the unlock code so you could access in case of emergency. But be honest how many emergencies are there between 9pm and the time you wake up. :)

In the end change is hard!

Ian just made a post sharing 9 tips for working remote with kids. I thought it was a great list and the tip for making exceptions reminded of a great memory I got to share with my youngest daughter a few months ago

I couldn’t fit everything in the tweet but she came running into my office with a princess dress on and batting her eye lashes telling me I was cordially invited to a royal ball. It was unforgettable for me and a memory I will cherish forever.

These are the quick moments that I wouldn’t get to experience first hand if I didn’t work remote. While my kids are small I can’t imagine working in an office. They grow up to fast and then it’s gone. No turning back the clock on what you should have done.

Switching to PhpStorm

A few months back I retired Sublime Text from my day to day coding and have since switched to using PhpStorm as my go to editor. I do keep Sublime around for quick editing, writing blog posts, but I haven’t missed it otherwise. PhpStorm has a lot of nice features that you don’t realize sublime is missing until you switch. Here is my mini review on what I’ve found in the few months of using PhpStorm.

Git and Github

I have found the git and github integration brilliant. I really like opening issues right in the ide and it creating a new branch/workplace. At UserScape we do a lot with Trello and only use GitHub Issues for bugs so I don’t get to use this as much I would like. Maybe one day some one will integrate Trello. :)

Committing is also something I really like doing without having to leave my editor. It has this integrated via command + k. Or if you are old school you can just open the terminal tab. My personal preference is to visually commit so I only use the terminal when I have small changes.

Find Anything

Another huge feature is the search everywhere. I have this mapped to “command + t” to match Sublime but the original is a Double-Shift. This is way more powerful than Sublime though. You can find files, classes, actions and preferences. I really like the actions searching because I have a mental block and can never remember them. This is probably why I don’t enjoy VIM or anything else that requires me to learn key maps. As an example I like splitting the window so I just “command + t” type vertical and BAM the action shows and it splits. Maybe I want to diff the file, again command + t type annotate. These are huge time savers for me.

Terminal

The terminal integrated is brilliant. We use grunt for all our js and css and have a simple watch/reload task. So when I start editing I just open terminal run grunt watch and then open a new terminal tab for anything else I may need. Deploying, artisan, composer, etc.

Code Complete

PHP code completion is very nice but believe it or not I find the code complete in html and less way more beneficial. It works just as nice as the php auto complete and does a very good job filtering css classes to find the one you want without having to hunt it down. It also has great support for CoffeeScript (The ONLY way to write JS). :)

Themes and Interface

This is one area I do find frustrating at times. The default theme is Darcula and it is a huge improvement over previous versions and you can find a ton of themes at PhpStorm-Themes or my recent favorite Spacegrey. What frustrates me is the font adjustment and line-heights. Fonts typically look good at bigger sizes but when you set the size to 10 or 11 they just don’t feel crisp like Sublime. The line height is also crazy. You set it to 2.0 and then you get a monstrous cursor.

Tips

If you are currently using Sublime and want to try PhpStorm here are some tips I have. I would hide all the panels and just move in slowly. I started with just as a code editor and then slowly experimented with features until I found my ideal workflow. It has a huge number of features that I don’t understand and/or haven’t cared to fully investigate.

Expect it to be slower than Sublime. A lot goes on under the hood for finding things, auto completing, etc and it’s always going to be slower than sublime. I only really notice this at times but that first launch you will.

Laravel is my framework of choice and the code completion doesn’t work great with the facades. A work around is to add this composer package

"require-dev": {
    "barryvdh/laravel-ide-helper": "1.*"
},

Next go and watch some videos and read some posts that highlight features and show you tips you would otherwise miss.

All in all so far the features out weigh the annoyances I have so I am going to stick to using it for the foreseeable future. Big IDE’s aren’t for everyone but I encourage you to give a PhpStorm a chance. I think you might just like it.

The best1 help desk app Snappy is currently running a promotion that has the following prizes:

  • 2 Tickets to Laracon in NYC
  • 10 Laravel books, choose any one you like from Leanpub!

If you are interested in Laravel you should go sign up!


  1. Yes I’m biased. :)