How to install and configure PHPUnit on Linux

PHPUnit is the canonical unit testing framework for PHP. Even for simple projects and learning exercises, unit testing pays big dividends. This article provides a way to install and configure PHPUnit on Linux. This article assumes you’ve installed Composer, the popular PHP dependency manager. I used the following two lines to install Composer:

Step 1. Add src and tests directories to your project’s root. These aren’t absolute directory names required, but you’ll see these directory names referenced in following steps. If you change these names be sure to change the corresponding names in subsequent steps.

Step 2. Add the following Composer file, named composer.json in your project’s root.

Set the name, description, and license keys with your project’s info. The autoload key uses the psr-0 standard to autoload PHP class files located in the specified directory.

Then run composer from your project’s root to install PHPUnit and its dependencies. To ensure PHPUnit installed correctly, run this command from the command line:

(Note: If you’d rather not use Composer to install PHPUnit, there are alternative installation instructions on the PHPUnit site.)

If the PHPUnit version is correctly reported you’re ready for Step 3.

Step 3. Add a phpunit.xml file to your project’s root. This XML file provides configuration info to PHPUnit. There are many other configuration settings than what’s shown below available–this step keeps the configuration simple. Check PHPUnit’s documentation for the other configuration options available.

The bootstrap key identifies the autload file that causes your classes (the ones that you are testing) to be loaded. The colors key tells PHPUnit to show command line test results in color (ie, green for pass, red for fail).

The testsuites key identifies groups of tests (“test suites”) and the directory where the PHP tests files are located. When you run phpunit on the command line without any arguments all of the test suites identified here are performed. You can use PHPUnit’s --testsuite flag to run a single test suite. For example, if you had a test suite named Controller tests the following command line would run that test suite only:

The name you provide for test suites is case-sensitive. When a test suite is performed, the tests in its top-level directory, as well as any in any child directory are performed.

Learning how to use PHPUnit is central to learning PHP well, and, as you can see, getting it up and running is easy.

Core Git command line reference

Inspired by John Nickell and Jeffrey Way I am making a renewed commitment to use Git primarily from the command line. While the command line may seem like many steps backwards from using a rich graphical interface, I am finding that it makes me much more aware of exactly what each step of Git is doing and it provides infinitely more quick repeatability of Git tasks.

This is list of Git commands I find myself using over and over. Be sure to familiarize yourself with Git aliases; they go a long way towards making the command concise and effective.

The easy way to put Git on a Windows box is to install Github for Windows and then use its Git shell. The added bonus here is you have good GUI available for basic Git operations as well.

Initialize a local repository

git init 

Stage all file changes to the index

git add .

Stage all file changes, including deletes, to the index

git add -A

Commit changes

git commit -m 'commit message here'
or
git commit -a -m 'commit message here'
which automatically stages modified and deleted files before the commit. However, new files you have not explicitly added to Git with ‘git add’ are not affected.

Discard changes

To remove unstaged changes from a specific file:

git checkout path/to/file/to/revert

To delete all unstaged changes:
git checkout -- .

Remove a file from the repository

git rm <file name>

Discard all changes since last commit

git reset --hard HEAD
See this link for more info.

Show the repository’s current status

git status

Show all commits in an abbreviated form

git log --pretty=oneline --abbrev-commit

Show the SHA1 for the current commit

git rev-parse HEAD

Change to another commit and then make it a branch

git checkout nnnnnn
where nnnnnn is the first six characters of the desired commit’s SHA1. This puts the repo in a detached HEAD state. Now make a branch out of the commit you just checked out:
git checkout -b new_branch_name
That new branch is made the current branch. You can now switch among branches.

Show all branches

git branch -v

Create a branch

git branch new_branch_name

Create a branch and immediately switch to it

git checkout -b new_branch_name

Switch to a different branch

git checkout new_branch_name

Delete a branch

git branch -d branch_name

Rename current branch

git branch -m <newname>

Rename a branch that isn’t the current branch

git branch -m <oldname> <newname>

Show all modified files

git ls-files -m

Show all files

git ls-files

Use Sublime Text as Git’s editor on Windows

git config --global core.editor "'c:/program files/sublime text 2/sublime_text.exe' -w"

Use Sublime Text as Git’s editor on a Mac

git config --global core.editor 'sublime -n -w'
Where ‘sublime’ is a symlink in the $PATH. This Stack Overflow entry was helpful for this.

Show all aliases

git config --get-regex alias

Add a Git command alias

git config --global alias.nn 'xxxx'
where nn is the name of the alias and ‘xxxx’ is the Git command and its arguments. For example:
git config --global alias.rplog 'log --pretty=oneline --abbrev-commit'
Call this alias with this command line:
git rplog

Delete a Git command alias

git config --global --unset alias.nn

Clone a repo

git clone <uri>
From a command line, go to the parent folder where you want the repo located. Cloning the repo will create a child folder under the parent folder you selected.

List remote repos

git remote -v

Show a remote repo

git remote show origin

Remove remote repo location

git remote rm origin

Set remote repo location

git remote add origin <uri>

Update remote repo location

git remote set-url origin <uri>

Update a remote repo

git push -u origin --all or git push -u origin master

Update a remote repo with current tags

git push -u origin --tags

A sad Thunderbird hiding in the Texas hill country

For as brown and boring as much of southern Texas can be, there are many great motorcycle rides to be had down here. There isn’t anything that rivals the beauty and challenge of the Blue Ridge Parkway (for me, at least), but there is definitely motorcycle fun to be had down here. I took Glodean (my white 2012 Victory Cross Country Tour) out last Sunday to see what I could find. I live near the northern intersection of 281 and 1604 in San Antonio. This was the starting point of my latest Sunday ride (shown in the map below).

tbird

I headed west on 1604 to SH 16. I much prefer two lanes to four so I was anxious to get on 16 (16 does start out from 1604 as having four lanes, but it pretty quickly turns into two lanes). 16 is a nice ride, with minimal traffic most of the time. I rode it into Bandera (near point #2 on the map above), which considers itself the “cowboy capital of Texas.” And, indeed, it doesn’t take much imagination to see this little town the way the cowboys used to. Basically a single intersection town, on any given Sunday its Main Street is lined with motorcycles, sports cars, and the occasional street rod. I didn’t stop very long in Bandera today, but if you are so inclined there are several biker-friendly saloons that offer a variety of cool refreshments.

willysbandera-bikes

ratbob

On today’s trip through Bandera, I saw a sweet Willys Jeep Wagon and a Goldwing bobber rat. I’ve got a 93 Goldwing taking up space in my garage that I think I oughta bob one of these days. I’m thinking rat bobber bagger. We’ll see. Daydreaming about making that bobber I headed north out of Bandera on US 16. About five miles out of Bandera I took FM 470 west through Tarpley and continued heading west to SH 87 (point #3 three on the map). I left my house at about 9:30 AM and it wasn’t too hot yet. With the XM radio broadcasting a Kasey Kasem American Top 40 rebroadcast from 1974 and the comfortable morning air, choogling down 470 on Glodean felt pretty good.

One of the reasons I really like riding is that you can ride for miles and then realize that for the last 20 minutes you haven’t thought about a goddamned thing! Your head empties and you can’t be emailed, texted, called, meeting invited, conferenced in, cajoled for input, or asked to “do” lunch. Kasey’s long distance dedication (“Dear Kasey, I’ve been in Germany in the Army for the last two years and I really miss my girlfriend. Would you please play Redbone’s Come and Get Your Love for her…”) might drift in one ear and out the other, but otherwise you are untouchable. As a card-carrying introvert, I nearly always feel that the quality of the company I am in is inversely proportionate to the number of people around me. Heading west on FM 470, with no one in front of me and no one behind me, the quality of my company on this morning was as good as it gets!

470West

Morehill

Before heading out on FM 470, don’t leave Bandera with a low tank of gas. There is gas to be had in the hill country, but those chances don’t happen very often. Like many of the hill country highways in Texas, FM 470 is refreshingly devoid of any signs of commerce (except for the occasional real estate “for sale” sign). Fast food places, malls, and other civilization lard are no where to be found. You do see the occasional high-dollar gated entrance to what is surely a beautiful home tucked away in the hills, but mostly FM 470 is you, your bike, and the countryside. For what it lacks in challenging twisties and ups and downs, FM 470 makes up for with gently rolling hills and beautiful hill country vistas.

Texas two-lane secondary highways are designated RM or FM, for Ranch-to-Market and Farm-to-Market. Generally RM highways are west of SH (State Highway) 281 and FM highways are east of SH 281. “Generally” is key here because I’ve been on several FM roads west of 281 (FM 470, for example). I’m a corn fed Hoosier and a Texas RM/FM road is what we’d call a good county road in Indiana. The amazing thing about Texan RM/FM roads is that in Indiana, and may other states, this type of highway almost universally has a 55 MPH or so maximum speed limit. Not in Texas. RM/FM roads can have 70+MPH speed limits. I’ve learned, the hard way, that there are two things to watch out for on RM/FM roads: 1) if you see, in the distance, a newer model Ford pickup parked on the opposing side of the road facing you, usually under the shade of a big tree, slow the hell down. It’s a constable and he’ll getcha if you’re speeding (On RM 337, between Medina and Leakey, give Constable Phillip Tobin a wave as  you go by. He’s a nice motorcycle guy); 2) when you are on a 70 MPH RM/FM road, cruising along nicely, as you approach the occasional little town, you also need to watch your speed. The otherwise crazy-ass fast speed limit can change quickly to 40 MPH and invariably there will be a constable lurking.

HIll

As you approach SH 87 heading west on FM 470, the landscape gets a little more hilly and the road gets a few more turns. There isn’t anything breathtaking or technically challenging here, but the fun factor does twist up a notch or two. Once on SH 87, I went north heading towards RM 337–which is also a very good road to ride. I was really torn when I got to RM 337. Going west on it for about 20 minutes would drop me right into Leakey, the anchor town of the Three Twisted Sisters–a legendary Texas hill country ride. I’ve done the Sisters many times and I would have really liked riding them today, but today I just didn’t have that much time. I stopped at the rustic Lost Maples Store (about halfway between points #3 and #4 on the map) for a bottle of water. I also had a quick chat with the grizzly old Texan running the store (who was trying to watching Ice Road Truckers on TV between customers. I continued north heading up to US 39 damned glad I wasn’t in a truck and on ice.

Three miles or so north of the FM 337 intersection on US 187 is the Lone Star Motorcycle Museum. I have been there many times so I motored on past today, but if you’ve never been there you need to go! The owner, Allan Johncock is a little old Australian expatriate and a motorcycle nut of the highest order. Allan’s got more cool old bikes (some exquisitely restored, others proudly wearing the patina of age and use) in his museum than you’re otherwise ever likely to see in one place. The museum also has a little cafe with a pretty average cheeseburger (no beer, though). I have read on a few forums that the cafe may close this fall–check before you count on eating at the museum. (I love Allan’s museum but if you get this close to Leakey and are hungry, get your ass on over to the Bent Rim Grill in Leakey.)

I rode on up SH 187 to SH 39, taking it east towards Kerrville. SH 39 is a pretty average ride until you get about 15 miles east of Kerrville. There 39 hooks up with the Guadalupe River and a few turns and a few hills. That last 15 miles into Kerrville on 39 is a great ride. It was also, for me this morning, the part of the ride with the most traffic. I don’t ride like a crotchrocket hot dog, but I also don’t dawdle along like a nun in a Model T. More than once I got stuck behind three or four really slow-moving Sunday drivers.

I stopped in Kerrville for a couple of bean and cheese chalupas in a nondescript mom and pop restaurant. It wasn’t anything to brag about but it was also only $4.50 for everything. After lunch, I took Highway 27 south out of  Kerrville and took it east back to I10 to Comfort, Texas. At Comfort, I jumped on RM 473 for a nice little ride on over to US 281.

tbird in sisterdale

I really like old cars and am always on the lookout for vintage tin as I ride through the Texas countryside. On this ride, east of I10 on RM 473, I came across this sad, old 58 or 59 Thunderbird. Its license plate was dated 1975, so I’m assuming this poor old Bird has been sitting in the weeds for nearly 40 years. Despite that, its condition made it more likely a project car than a parts car. A determined builder with some mad skillz and enough time on his hands could turn this old weed steed into something very interesting.

For about 30 minutes I had RM 473 and its occasional twists and turns all to myself before being dumped back into civilization on SH 281 with all the Oldsmobiles and Ford F-250 pickups. By now it was mid-afternoon and the comfortable morning had transitioned into a very hot afternoon. It was hovering at about 100 degrees by 2pm. I was still glad that I wasn’t in a truck but a little of that ice would have been welcome about right now. My ride lasted about five and a half hours and took me just under 230 miles. Once again, Glodean took very good care of me. I got a little sun and was hot and thirsty when I got home, but damn, I can’t wait to do it again!

Hot and Sour Beef Noodle Soup

hot-sour-beef-noodle-soupI’m a big fan of Chinese hot and sour soup and make it every once and while. Learning to make hot and sour soup taught me that the two key ingredients that contribute the most to its flavor profile are finely crushed white pepper (the hot) and Chinese black vinegar (the sour). You can get the Chinese black vinegar in any Asian grocery store, a well-stocked big-box grocer, or at Amazon. It is expensive on Amazon–I pay less than $4 for a bottle locally. Any mom and pop Asian grocer will have it. Beware there isn’t a rational substitute. Search this ingredient out, it is important!

This quick, one-serving recipe isn’t hot and sour soup in the most conventional sense, but if you are hungry for hot and sour soup and want something quick and delicious, this soup is great. I frequently cook with Asian ingredients, so I always have sambalwoodear mushrooms, and Chinese egg noodles on hand (in a pinch the noodles from a package of ramen noodles works fine-but don’t use the seasoning package). The mushrooms and noodles keep nearly forever in the freezer. If you don’t have an ingredient recommended here (except for the black vinegar) use something else! Part of the point of this soup is that it should be quick and easy to make. Oh, and very tasty.

In this variant, I use beef and beef broth (but another possibility is chicken broth and pork or chicken). For a recipe such as this I use “Better Than Bouillon” beef base. This isn’t a product I would normally have ever considered using for anything. However, an article in Cook’s magazine recommended it and I’m glad it did. For basic recipes, the beef and chicken versions of this product provide my go-to quick broth. It seems a little expensive, but it really isn’t compared to canned or boxed broths. The recommended usage is one tablespoon for a cup of water (but as the Cook’s article pointed out) one tablespoon for two cups of water works just fine (and is less salty and makes the base go farther).

For the beef in this recipe I generally rely on leftovers. Flank steak, NY strip, or rib eye works fine–but pretty much anything works. I use about 12-15 thin strips of beef (about four ounces) per two cups of broth. If the meat isn’t cooked, give it a quick flash in the pot before starting the soup. Don’t overdo cooking it. It will finish cooking in the hot soup.

Start the mushrooms soaking first thing and you can be eating this delicious soup in less than 15 minutes!

Hot and Sour Beef Noodle Soup
Author: 
Recipe type: soup
Cuisine: Chinese-inspired white guy
Prep time: 
Cook time: 
Total time: 

Serves: 1
 

A quick ramen-like soup with the flavor profile and full body of hot and sour soup.
Ingredients
  • 2 cups of beef broth (see text)
  • I portion of Asian egg noodles
  • 12 thin strips of beef
  • ½ cup of woodear mushrooms (or shitakes in a pinch)
  • ½ finely-diced carrot (it’s not going to cook very long so no big chunks here!)
  • 1 tablespoon of Chinese black vinegar
  • ½ teaspoon of finely crushed white pepper
  • 1 tablespoon of soy sauce
  • 1 tablespoon of sambal chili paste
  • a couple of sprinkles of red chili flakes
  • several scallions for garnish
  • a couple of sprigs of cilantro for garnish

Instructions
  1. If you are using dried mushrooms, put them in a bowl and pour boiling water over them and let them sit until rehydrated (about 15 minutes)
  2. Slice beef into thin strips. If the meat isn’t cooked, give it a quick flash in the pot before you start the soup.
  3. Bring broth to a boil in a small pot
  4. Add noodles, diced carrots, sambal, soy sauce and chili flakes
  5. Add the mushrooms, cut into thin strips, when fully rehydrated
  6. When the broth comes to a boil, add the noodles and cook until the noodles are al dente
  7. Remove the pot from heat and add the meat
  8. Serve garnished with thinly sliced scallions and a couple of sprigs of cilantro

 

Laravel’s Eloquent ORM versus Query Builder

Laravel offers two ways to work with your database:

  • Eloquent ORM. Eloquent provides an active record-based ORM. It provides a fluent interface with built-in relational capabilities.
  • Query Builder. The Query Builder provides a flexible, and also fluent, way to create SQL queries. It provides an intuitive way to create SQL queries with nearly all of the flexibility of using SQL direct.

Making my way through learning Laravel, most of the videos and articles I read focused on using Eloquent for database access. However, I found that using Eloquent for generating JSON, at least for some tasks, limited the control I had over how result set JSON was generated. This article shows how I turned to the Query Builder for generating the result sets to be expressed as JSON.

As I make my way further into Laravel, I am sure there will tasks for which Eloquent is superbly suited. However, I learned this weekend that there are also tasks for which the Query Builder is superbly suited.

Using Eloquent ORM

This Eloquent code (assuming the corresponding Laravel relations have been established)

produces this JSON:

Notice how the data from the related tables is placed into seperate JSON nodes (ie, the category, state, and type nodes). Unless you use the $hidden array in a model definition, there isn’t a way to limit the columns returned from related tables. The $hidden array can’t be changed at runtime so it must be specified in the model. Thus you either need special-cased models or learn to live with all of the columns being returned for related tables.

Laravel’s Query Builder to the rescue

Using Laravel’s Query Builder, you can get much less verbose JSON. The following query

produces this JSON. The Query Builder provides a greater level of control over what is included in the query. For example, note how you can use the ‘as’ clause in the select() method to alias result columns.

 

Kung Pao sauce

I really like to make Kung Pao dishes. But I have never found a bottled Kung Pao sauce that suits me. When you get a Kung Pao dish from a great Chinese restaurant (and “great Chinese restaurant” can be a pretty grim looking, from the outside, mom and pop shop) it has the perfect combination of zing, flavor, and body. None of the bottled sauces I’ve ever tried provide that–in fact, most are just plain bad. So I spent a couple of months zeroing in on a Kung Pao sauce recipe that suits me. This one isn’t quite there yet, but it’s very close. I want to try grating a little fresh ginger into it. I think that might help round it out a bit.

I don’t like to add garlic to this sauce–and I put garlic in everything! I prefer to add the garlic to the primary contents of the meal. That way, when I am making a meal that uses this sauce, I can add as much garlic as I want knowing that this sauce won’t push the garlic needle too far into the red zone!

I make this sauce in advance and keep it in the freezer. It never fully freezes but lasts for a long time in its “nearly frozen” state. Having it readily available makes it much quicker to whip a Kung Pao-based meal together.

Kung Pao sauce
Author: 
Recipe type: Sauce
Cuisine: Asian
Cook time: 
Total time: 

 

This Kung Pao sauce is easy to make and vastly better than any bottled variety.
Ingredients
  • 2 cups chicken broth
  • ⅔ cup soy sauce (or maybe a little more–but watch the saltiness)
  • ⅓ cup rice wine vinegar
  • ⅓ cup light brown sugar
  • 1 tablespoon hoisin sauce
  • 1 tablespoon chili paste
  • 1 teaspoon red pepper flakes
  • 1 tablespoon cornstarch
  • 3 tablespoons of water

Instructions
  1. Add all ingredients except cornstarch and water to a sauce pan over medium-high heat.
  2. Bring to a boil, stirring frequently with a whisk. When the sauce starts to boil, reduce heat to bring to a simmer. Let simmer for 15 or 20 minutes.
  3. Mix the cornstarch and water in a small bowl. After 20 minutes or so, bring the sauce back to a boil. After the sauce starts boiling, and add the cornstarch/water mix.
  4. Stir vigorously with a whisk until the sauce thickens. When the sauce covers the back of a spoon (the sauce will continue to thicken a bit as it cools), remove from heat and use immediately or freeze for use later. No matter how hard I try, I almost get a few few pasty clumps from the cornstarch, so I usually strain the sauce as I poor it from the pan.

Notes
This recipe makes enough for two or three dishes. It freezes well.

 

Filtering XML with LINQ to XML

Filtering an XML document with LINQ to XML is very easy.

Here is the C# to use LINQ to XML.