Setting up Gulp, Bower, Bootstrap Sass, & FontAwesome

Let’s face it. Managing front end dependencies is still a headache. As developers, we have a plethora of options for building dependencies. Some of the tools off the top of my head are Grunt, Gulp, Broccoli, Component, NPM, and probably 5 more have been released since I started writing this post. In this tutorial, I am going to focus on Gulp but I’m sure it can be modified to work with any of the others. Continue reading “Setting up Gulp, Bower, Bootstrap Sass, & FontAwesome”

The Wardrobe Diaries

I have been working on building a new version of Wardrobe, my little blogging app, and development has stalled as I’ve been swamped with other things. I have thought about it for a few months now and I’ve decided I’m going to do a complete rewrite. Lots of new features have been added to Laravel and with 4.3 on the horizon I think now would be a good time to revisit some of my original goals, and also add new features. Instead of just building it and releasing the finished product I want to do something a little different. I’m going to journal the entire process on this site – from blank screen until completion. Continue reading “The Wardrobe Diaries”

Pluck The Weeds In Your Code

Back in the spring, as I was walking back from the mailbox I noticed a tiny little green weed inside a purple bush. The bush hadn’t bloomed yet and was still bare from the winter. I briefly thought about going and pulling the weed, but I kept thinking:

  • I have 10,000 other things I need to do
  • It will still be their tomorrow
  • When the bush blooms it will block out the sun, and without sun it will die.

The third thought was partially right. The bush bloomed and the weed seemed to miraculously be gone. Out of sight, out of mind, they say.

Fast forward to the fall and I’m making my same trip to the mailbox and this time I see a huge green leaf coming out of the top of the bush. The little weed that would have taken 30 seconds to pull has now turned into a massive tree like structure.

I tug and I tug, it’s impossible to remove, the roots from both are all intertwined.

Now pretend that weed is a piece of nasty weird code that you come across in your app. Don’t be lazy, go improve it before it grows out of control.

This post is an excerpt from my Laravel News digest. A weekly email about the Laravel framework.

Building a jQuery Plugin with Gulp

With the current design of this site I wanted to have images in the content that stretch out beyond the container. I’ve seen this pattern used quite a bit recently and I think it gives a nice little visual “pop”. Implementation wise this is a pretty easy problem to solve by using negative margins. I decided I would use this as an opportunity to put together a little centerImg jQuery plugin and document my steps along the way. Continue reading “Building a jQuery Plugin with Gulp”

Open Source Marketing Tips

It’s 1 am, I’m unable to sleep and have all these crazy ideas running through my head. As I start to doze, I have a spark of genius. I think to myself this would be an awesome open source package. I guarantee others would love this. It’s so useful why hasn’t anyone else thought of it.

Over the next two weeks I spend hours and hours thinking, building, refactoring, and creating this package. I think it’s going to be the best ever. Seriously it has to be, it’s so useful.

I’m finally ready to release it. I spend at least an hour crafting the best tweet I can. Secretly wishing it will go viral, hoping others will love it, and just from one single tweet Hacker News will have it featured all day. It’s time! I hit “tweet”, sit back, and watch in great anticipation.

After the first five minutes nothing happens. Sure, some friends retweet it but it’s not gaining momentum. So now I think I’ll just wait till tomorrow when more people have seen it. But still nothing.

Where did I go wrong? Was this a dumb idea? Why doesn’t anyone like it? Is the code horrible and no one told me?

As software developers we tend to look at things from our own perspective. Assuming everyone else will see it the same way. I’ve spent all this time developing but I didn’t take those extra few minutes to really polish the marketing text. This is the big mistake. I know you are thinking it’s open source, do I really need marketing? Without a doubt yes you do!

Your readme is the first page people see when they find your package. It’s important to clearly define what the package does. List out benefits not features. Features are important but only after you’ve sold me. I need a quick overview of why your package is going to make my life easier.

The fact is you have very little time to sell someone and people do not read. They glance. If nothing stands out, they move along faster than a cheetah chasing a gazelle.

I’ve seen it time and time again where I find something that sounds cool only to have this be their main section of the readme:

  • Includes awesome package
  • Uses x design pattern
  • BDD, DDD, TDD
  • And on and on.

What does that tell me? Nothing. I really don’t care about this. Instead show me the benefits. Show or tell me why my coding life is horrible without your package.

Here are a few packages I found that I believe excel with this:

Intervention Image

Look at the demo code which is the first thing you see:

// open an image file
$img = Image::make('public/foo.jpg');

// now you are able to resize the instance
$img->resize(320, 240);

// and insert a watermark for example
$img->insert('public/watermark.png');

// finally we save the image as a new image
$img->save('public/bar.jpg');

I think to myself. WOW. That’s all it takes to upload and resize an image? I’m using this!

Carbon

Both Carbon and Intervention use the same style by letting the code speak for itself. Here is a portion of their main page:

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));  
$tomorrow = Carbon::now()->addDay();

Dispatcher

Dispatcher is a package for scheduling tasks inside Laravel:

dispatcher

Notice how these packages explain and demonstrate why I would want to use them. It’s really that simple!

Take the extra 30 minutes and ensure your readme is clear, precise, and tells me why I should care. Be specific. Sell the benefits. Take a screen shot. Wow me.

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 IlluminateSupportMessageBag)
  {
    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.

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 outweigh 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.

Care and Feeding of a Robot

 

I had the honor and privilege to speak at the first ever Laravel conference. After my talk, I had a few people ask me about my slides so I wanted to share those and give little insight into how I created them.

First off, I was doing my presentation on an actual product. So I wanted to be sure that it wasn’t presented as a sales pitch. Instead, I wanted to just share some good tips and some of the things we had learned throughout the process of building it. So for that I wanted to step away from all the branding that we currently use for Snappy.

For the design, I based everything around two fonts. Veneer as the primary and Thirsty Script as a secondary font. Once I locked in my fonts I decided on using the color scheme that Yellow Design had in the font screenshots. I knew it would compliment the fonts nicely and look professional. From here I just made everything match and be super big.

Slides

Video

Presentation Design for Developers

I am excited that I will get to speak at the first ever Laravel conference next month. I am in the process of building my presentation and I wanted to share a lot of tips, tricks and resources that I have found along the way. With the goal it will help you if you are ever presenting and just need a quick start.

Presentation Planning

The first step is plan your presentation. I use pen and paper for this. Stepping away from the computer allows me to gather my thoughts better and not get sucked into just doing research and browsing. I found this really helps.

Next I take my brainstorming notes and opened up a markdown app. From here I actually write out everything in story form. From what I have read presentations are better if they tell a story so this helps me get all my thoughts together. Almost like I am writing a blog post.

Presentation Design

This is the hard part for me. I am not a strong designer but I feel like I have a good grasp of what good design is. In other words I know it when I see it. The problem is everything I create I never see it being any good. So I am sticking with the classic big font and single color background.

For the color scheme I like to stay away from common white or black backgrounds. I found a lot of great color schemes from kuler, colourlovers, and even dribble. Of course there are many more sites that offer color schemes. Just pick something that has good contrast so your words will “pop”.

Fonts are a real struggle for me. There are millions of fonts and I have wasted about 5 nights just this past week looking and searching for the perfect one. I personally only like at most two fonts and I usually go with two that have a big contrast. Something like a sans-serif for big bold titles and handwriting for subtitles. A good site for finding free fonts is fontsquirrel.

I save images to the very end because I am constantly changing things as I go. Since I am not really to this point I wanted to share a great site for finding creative commons images on Flickr. The site is CompFight. If you do want to go with a commercial offering istockphoto seems to be fairly inexpensive.

In the end visit SpeakerDeck and browse their Featured Presentations. Most of those look great and will give you great ideas.

Keynote Tips

I am far from a keynote expert but here is a few tips I have picked up while doing my design.

First open the color picker box and get the color you want. Next drag this color down into the little swatches box. By doing this you can get all the colors you are going to use and have quick access to them. Here is an example:

keynote-colorpicker

I have found working with fonts a chore. I choose the generic white template as a base and it always reverted to Gil Sans. So any text box I add I then had to go and change the font manually. To change the font for all new text boxes all you have to do is first create a new text element. Pick your font, and finally go to format -> Advanced -> Define Text for all Masters.

I was honestly about to throw keynote out the window until I discovered this.

See it Live

Designing a presentation is only half the battle. The actual speaking part is what most fear. I have seen surveys where people say they would rather die than speak in front of a room full of people. I think that is a little extreme but everyone has their quirks. On a positive note if the talk bombs you can always share your beautiful slides and people will think you did an awesome job. 🙂

If you want to see my finished presentation there is only one way. Attend the first ever laracon. It should be loads of fun and nice to finally get to meet a lot of the Laravel community. I want to give big props to UserScape for getting the ball rolling on this.

Statamic Email Form Plugin

This is a plugin for Statamic that is designed to allow you to quickly and easily create email forms. Currently it is pretty basic but flexible so it should be a great starting point. I hope to get feedback on this release and then make improvements over time.

Installation

Copy the “email” folder to your _add-ons directory.

Example Form Template

Here is a full example to get you going. Please see the parameters section
for more field options:

{{ noparse }}{{ email:form subject="Contact Form" to="eric@ericlbarnes.com" required="name" }}
    {{ if error}}
        <h1>Error</h1>
        <ul>
        {{ errors }}
            <li>{{error}}</li>
        {{ /errors }}
        </ul>
    {{ endif }}

    {{ if success }}
        <h1>IT WORKED!</h1>
    {{ else }}
        <p>
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" value="Bill">
        </p>
        <p>
            <label for="from">Email:</label>
            <input type="text" name="from" id="from" value="test@test.com">
        </p>
        <p><input type="submit"></p>
    {{ endif }}
{{ /email:form }}{{ /noparse }}

Parameters

The {{ noparse }}{{ email:form }}{{ /noparse }} tag accepts the following paramaters:

  • subject: The subject of the email.
  • to: The form recipient’s email address.
  • cc: A cc email address.
  • bcc: A bcc email address.
  • required: A pipe seperated list of required fields. Example: “name|address|city”. Currently this only does simple validation to check if it is an empty value.

Issues / Gotchas

The name field is hard coded as the reply name in the plugin so it is recommended you use this field in your form.

Contribute

Keep in mind this is the first release so if you see any issues or have ideas for improvements pull requests are gladly
accepted. 😉

Download

You can clone the repo by running the code below:

$ git clone git@github.com:ericbarnes/Statamic-email-form.git

Or visit the GitHub Repo.

Statamic Sitemap

This is just a few simple template files to generate a sitemap of your site for submitting to Google webmaster tools. It follows the sitemap protocol.

Installation

Copy the contents of all the directories and move them into your Statamic site.

Download

You can clone the repo by running the code below:

$ git clone git://github.com/ericbarnes/statamic-sitemap.git

Or visit the GitHub Repo.

CodeIgniter Security Basics

By default CodeIgniter is a very secure framework and it also does a lot behind the scenes to help you out. I was recently contracted to look over a CodeIgniter application that was constantly getting hacked. So in light of what I seen I want to share some common pitfalls you need to avoid.

  1. Use Active Record! You should “almost” never write your queries manually.
  2. If you must write a query without active record be sure everything is escaped properly. $this->db->escape()
  3. Validate user input! CI has $this->input->post(), $this->input->get_post() and you should use those.
  4. Validate file uploads and use the upload library.
  5. Use the framework tools. It comes with tons of libraries and helpers that are designed to help you with common tasks. There is no reason to write
    your own if already accomplishes what you need.

Yes I know every php developer should know about these but some people still just haven’t gotten the memo. So spread the word, write secure apps, and make the world a better place.

Atlanta PHP Meetup

I had the pleasure of attending the Atlanta PHP’s meetup on Thursday at StrongBox West where Ben Edmunds gave a talk about the Laravel framework.

Doug Grubba and I decided to carpool down since Atlanta1 is about 4 hours from Charlotte. I will be totally honest I really didn’t have high hopes on how the meetup would go. I have been to some local meetups and I was just not that impressed. Low turnout, weird locations, etc. But Chris Spruck and the ATL guys are top notch. They had a lot of great sponsors, food provided, free prizes, and above all a nice turn out. (I estimated about 50 people).

After the meeting a few of us went over to local pizza shop and talked about all sorts of web topics and where our next stop in hotlanta should be.2

I had a wonderful time and wished I lived closer so I could attend more of their meetups. They get two thumbs up from me and hopefully I will get to visit again.


  1. Photo by tableatny 
  2. Ended up going back to the hotel and watching some gator hunting. But hey my wife is happy about that. :) 

Laravel Blade

Blade is the simple template/theme system built into Laravel and up until this point it has been very basic. It supported most of the simple things such as variables {{ $var }}, @if @else, @section, and finally a thing called @yield.

Because of the simplicity of it on a new project I thought we would need something more advanced and went with Twig. Twig had more features and was more powerful but it also didn’t really fit into my workflow. The biggest problem was working with Eloquent results and twig doesn’t like calling results like this:

foreach (Book::with('author')->get() as $book)
{
    echo $book->author->name;
}

I asked Taylor about it and he did a few changes to get that working but then I had troubles with other calls. So it just felt like it was more of a fight than what it was worth. After discussing this, last week Taylor and Shawn McCool really made Blade awesome. First Shawn recommended a “render_each” method. Which is an excellent feature in my opinion. It works my including a looped view:

<ul>
    {{ render_each('categories.list', $categories, 'cat') }}
</ul>

// categories/list.blade.php
<li>{{ $cat->name }}</li>

As you can see that is a big time saver. But it doesn’t stop there. Now Blade can have layouts inheritance and several other really useful goodies:

@layout('layouts.common')

@section('content')

    <p>My content</p>

@endsection

Then inside layouts.common:

<html>
<head>
    <title>Test</title>
</head>
<body>
    @yield('content')
</body>
</html>

This is just some of the basics of the new features and it does a lot more. Although I don’t consider it a full replacement for Twig it has 90% or more of the features I wanted to use. The biggest missing feature (depending on your needs) is that Blade still just parses as php. So it can call things that are not assigned and doesn’t prevent you from using php code in your views. Personally I like that feature but if you are really wanting to limit what people can do in the views then this may not be ideal. So use what is best for the task at hand.

For a video overview of what is coming please watch this:

http://www.screenr.com/embed/ft28

Laravel Bundle Assets

The past few weeks I have been building a few Laravel bundles and one of the features of bundles is the ability to have assets that are moved to your public folder during install. This is great when your bundle has css, js, images, etc..

The downside to this though is that while building the actual bundle it is a pain to keep having to run the following command each time you change a file:

php artisan bundle:publish

I have came up with a few different options to make this easier for developers. The first method which I believe would be supported across every os is to symlink the assets to public/bundles/folder/. However the down side to this is you have to add new symlinks when you add new files. So not ideal for the way I typically develop.

The second option is specific to mac but it works wonderfully. What I have done is purchase live reload and use it to run the bundle publish command. The reason I originally purchased the app was because I am using less for my css and I liked the fact that it would compile the css and also refresh your browser so you can see changes instantly.

The bigger benefit is live reload allows you to run terminal commands after you save and before it refreshes your browser. So all you have to do is add in your artisan command and not have to worry about it again. Here is a screenshot showing this:

livereload

Hopefully this will help you if you are building bundles with public assets. If you have any other tips please post them in the comments.

Laravel Log Viewer

A simple Laravel bundle to display your log files via the browser.

Installation

php artisan bundle:install logviewer

Publish assets

php artisan bundle:publish logviewer

Then edit your application/bundles.php file and add:

return array(
    'logviewer' => array(
        'location' => 'logviewer',
        'handles' => 'logviewer'
    )
);

Download

You can clone the repo by running the code below:

$ git clone git://github.com/ericbarnes/Laravel-Log-Viewer

Or visit the GitHub Repo.