How to Configure Redis to Automatically Start when Mac OSX Boots

I don’t like to remember to do stuff, because I invariably forget. I’ve recently started using Redis for a couple of projects and so I had to install it on my Mac for development. Here’s what I did to make Redis start on boot.

I didn’t use homebrew to install Redis, I compiled version 3.2.0 from the source. It’s actually super easy. It’s just “make,” “make test” and then “sudo make install.” Doing so installs Redis in /usr/local/bin.

Compiling from source doesn’t get you a redis.conf file, but I just used the default example I found on Redis.io. I saved it in /usr/local/etc. If you’ve installed things in a different location, adjust the following instructions to match your Redis setup.

To make Redis automagically startup on boot, I’m using launchd.

Create a simple xml document in /Library/LaunchDaemons.

sudo vim /Library/LaunchDaemons/redis-server.plist

In redis-server.plist put this.

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>redis-server</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/redis-server</string>
        <string>/usr/local/etc/redis.conf</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

To repeat, if you don’t have redis-server installed in /usr/local/bin, you need to change your path in the xml file. Also, if you don’t use a redis.conf, or it’s not installed in /usr/local/etc, update accordingly. If you don’t have a redis.conf, you can just remove it from this xml file.

Now load the redis.server.plist into launchd.

sudo launchctl load /Library/LaunchDaemons/redis-server.plist

You only have to do this once, now you should have control of your redis server via launchd.

Fire up Redis with this command.

sudo launchctl start redis-server

If you did it correctly, crank up the redis-cli client and type “ping.” You should connect and receive a “PONG” response. If you didn’t, go to /usr/local/bin and try running “sudo ./redis-server.” It should start up. If it doesn’t, fix whatever error is being generated. If it did work, now try it with the redis.conf file: “sudo ./redis-server ../etc/redis.conf.” If this doesn’t start Redis, fix any errors reported. If it does start, run redis-cli again and try the “ping” test.

How to Make a SOAP Request with Node.js using raw XML

There are libraries out there that you can use to make SOAP requests from Node.js. But I really just wanted to throw raw XML at my SOAP service. None of the libraries seemed to be able to do that, so I’m using the Node.js http implementation.

var http = require('http');
var http_options = {
  hostname: 'localhost',
  port: 80,
  path: '/LocationOfSOAPServer/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': xml.length
  }
}

var req = http.request(http_options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });

  res.on('end', () => {
    console.log('No more data in response.')
  })
});

req.on('error', (e) => {
  console.log(`problem with request: ${e.message}`);
});

// write data to request body
req.write(xml); // xml would have been set somewhere to a complete xml document in the form of a string
req.end();

This code is almost exactly what’s in the Node.js documentation. Obviously you can send any sort of POST data to any web server, or submit GET requests. Node.js uses this http implementation rather than what Javascript uses, which is XMLHttpRequest.

Debugging SOAP Service and WSDL with SOAP UI

Screen Shot 2016-05-18 at 3.10.31 PM If you’re like me and you spend a lot of time noodling around with SOAP web services, here’s tip for newbies. Veteran SOAP service developers already know this, but if you don’t, here’s a tip for debugging your SOAP calls and corresponding wsdl.

Download SOAP UI and install it.

Load your SOAP service and wsdl in SOAP UI. If you don’t know how to do this, read the SOAP UI documentation.

Turn on request and response validation by going to Preferences -> Editor Settings and check “Always validate request messages before they are sent” and “Always validate response messages.”

Now when you run requests against your SOAP service, you’ll get to see all of the stuff you messed up. I don’t know how anyone develops a SOAP service without doing this.

Symfony Doctrine Event Listener Silently Fails on instanceof

If you’ve ever done this in a Symfony doctrine event listener

if ($entity instanceof User) {
  // Do something for this particular entity
}

you might have run across this annoyance.

If you forgot to add a “use” statement for your “User” entity in your event listener class, this check will silently fail. I think PHP would essentially be asking, is $entity an instance of NameofyourBundle/EventListener/User rather than NameofyourBundle/Entity/User. Since $entity is not a NameofyourBundle/EventListener/User, the conditional fails. PHP doesn’t check if NameofyourBundle/EventListener/User exists, so no error is generated. That’s my theory, anyway.

How to Install Redis on Ubuntu

logo-130358959041456944If you’re running Ubuntu, there’s a good chance the version of Redis available in the repo is pretty old. Here’s how you can install the latest version of Redis on your Ubuntu or Debian box – these instructions should work on any Linux server.

On Debian or Ubuntu, make sure you have the ability to compile source code.

sudo apt-get install make gcc g++

Create a directory where you want to download and compile Redis. I usually go with a tmp directory in my home directory.

In the directory (e.g. ~/tmp/redis), run this.

wget http://download.redis.io/releases/redis-stable.tar.gz

Extract the tarball.

tar xvzf redis-stable.tar.gz

Compile the source.

cd redis-stable
make

Run the tests to make sure everything is good.

make test

Install Redis.

sudo make install

Create a redis user.

sudo useradd -s /bin/false -d /var/lib/redis -M redis

Create Redis pid, config and log directories. If you already installed Redis at some point, you might not need to do the following, but you can figure that out for yourself.

sudo mkdir /var/run/redis/ -p; sudo chown redis:redis /var/run/redis
sudo mkdir /etc/redis; sudo chown redis:redis /etc/redis -Rf
sudo mkdir /var/log/redis/ -p; sudo chown redis:redis /var/log/redis/ -Rf
sudo mkdir /etc/redis;
sudo cp redis.conf /etc/redis/redis.conf; sudo chown redis:redis /etc/redis/redis.conf

Create /etc/redis/redis.conf that looks like this.

daemonize yes
pidfile /var/run/redis/redis.pid
loglevel warning
logfile /var/log/redis/redis.log
port 6379
bind 127.0.0.1
dir /var/lib/redis

Create an init Upstart script that looks like this. Obviously, you don’t have to use Upstart, it’s actually being phased out in favor systemd, but you can decide how you want to fire up Redis on your server, here’s one option.

#!upstart
description "Redis server"
start on runlevel [2345]
stop on runlevel [!2345]
expect fork
respawn
respawn limit 10 5
exec sudo -u redis /usr/local/bin/redis-server /etc/redis/redis.conf

Fire it up.

sudo service redis start

Make sure it’s working.

redis-cli ping

If you don’t get a PONG, verify you did all of the steps correctly, if you did, head over to Google and start searching.

Based on the Upstart script, Redis should start on boot and restart on crash.

(h/t) I got a lot of information from this blog.

Get Rid of “Other” Data on Your Iphone Every Time You Backup

Screen Shot 2016-05-01 at 12.05.53 AM If you’re like me and you have a iPhone 5 with 8 gigs of data, you know what I’m talking about, fucking thing fills up with data quickly.

What a lot of the “data” is, is something calling “other” data.

Here’s how you can avoid never having to say, “My shit’s fully, I can’t take a photo.”

I make no guarantees that the following steps will not destroy your phone. I can’t see how they would harm your phone, but I have only performed these specific steps on my personal iPhone and have found them to work well – use at your own risk.

In a nutshell, what you’re going to do is backup your phone, wipe your phone data and then restore your phone from the backup you just made.

  1. Plug in your Iphone to your computer
  2. Open iTunes, if it’s not already open
  3. Backup phone with iTunes
  4. On your iPhone, wipe the data by going to Settings, General, Reset On fon go to settings -> general -> reset -> Erase all Content and Setting
  5. Now go back to iTunes and restore your Iphone from the back you just made.

Before you do the restore, the iPhone will ask you a bunch of setup questions, don’t worry about them, as long as you can see your iPhone in iTunes, you’re all set to restore your phone.

Eclipse Broken Arrow Bug in WSDL Editor

I almost spent a bunch of time on an non-issue.

Eclipse is my IDE. I’m currently building a new SOAP service. While messing around with the WSDL, in the WSDL editor graphical mode, I kept seeing a “broken arrow” rather than what I expect. It should look like this.

Screen Shot 2016-04-20 at 1.59.39 PM

When the arrows aren’t broken, I can click on one and drill down through the document. But when it shows up as broken, I can’t do that. I assumed I messed up something in the WSDL. I revalidated it. I reexamined all of my latest changes. Everything looked fine, then I found this post.

All I had to do was restart Eclipse and my broken arrow was no more. That’s a bug in Eclipse that goes all the way back to at least 2007. And I’m running the latest version of Eclipse – version: Mars.1 Release (4.5.1) Build id: 20150924-1200.

So if you run into the broken arrow syndrome with Eclipse’s WSDL editor, try restarting first.

Symfony Error: Call to a member function format() on string

Screen Shot 2015-11-27 at 11.53.37 AMThis Symfony error tripped me up for a few minutes today, it’s not particularly obvious what it’s referring to.

Error: Call to a member function format() on string

In my case, I was setting a Doctrine entity field to a string when it should have been a DateTime object. In my entity class I defined a member variable like this.

/**
 * @ORM\Column(type="date")
 */
protected $date;

But when I was calling setDate() I was using a string rather than a DateTime() object and so I got this error. So if you see this error, check how you’re building out your entity. The error won’t come up when you’re calling setDate(), but rather when you’re trying to persist the entity to your database.

PHP: To Type Hint or Not

Apparently some people think type hinting with PHP is stupid.

I don’t agree. I’ve been writing PHP since PHP version 3 and I think one of the greatest clunk factors in PHP has been that it’s loosely typed. You can never be sure that a string is a string, or is it an integer this time? Most of the time it doesn’t matter and PHP figures it out all and we go about our merry way.

But when it doesn’t work, it can lead to some ugly code needed to cast or convert or type check a variable to make sure it doesn’t throw errors or fail entirely. That, and a few other reasons are why I like type hinting with PHP.

I like to be able to write a method that will only accept a particular object. I think that sort of method contract makes the code cleaner, makes the code more readable, makes generating documentation more useful and easy, and there’s really no reason to not do it.

public function sum(Number $un, Number $deux)
{
}

That to me is more clear and descriptive than this.

public function sum($un, $deux)
{
}

If I didn’t write that method, I might have to look at the source to see what the method is expecting. Does it want numbers or does it want a Number object. Documentation could clear that up for me, but if it’s not readily available, I’ll have to examine the source code.

If programmers need to look at your source code to understand how to work with your application or library, that’s a fail.

Build Unit Tests or Functional Tests?

1972 Honda CB350

1972 Honda CB350

The headline is a trick – you do both.

It’s 2016, if you’re still out there writing code with no unit tests or functional tests, you’re not doing your job correctly.

Every time I write a method, I write a unit test. The unit test checks that the method does what I think it should be doing.

public function add($num1, $num2)
{
   if (!is_numeric($num1) || !is_numeric($num2) {
       throw new MathNotNumericException();
   }
   return $num1 + $num2;
}

For this method I would write two tests. One would test that the math works. If I call $this->add(1, 1) I should get 2. Another test will check that my numeric validation works as expected – I should get a MathNotNumericException if I call something like this $this->add(‘Stop’, ‘That’).

I also create functional tests for slices of the application’s functionality. For instance, if I had built a new user registration system, I would create a test that sets up a bunch of dummy data and calls the necessary methods to register a new user. The functional test could access dozens of methods and processes.

Unit tests give the developer confidence that an individual chunk of code works. Functional tests make sure that when all of the methods are used together, that they’re doing what is expected as part of the entire application.

To use a motorcycle example, checking tire pressure would be akin to a unit test. Hopping on the bike and seeing how the entire bike rides, or functions, would be a functional test. You need them both. I can’t count the number of bugs my tests have caught before rolling out code to production.


Buy my Symfony Getting Started eBook on Amazon.

Buy my new book Symfony Getting Started

Buy my new book Symfony Getting Started