Netbeans Code Completion and your Zend_View

Oh, look at me, blogging again! I definitely have a lot to blog about as I get the time, I’m coming off of a really involved project and learned a lot of tips I’d like to share about the Zend Framework. In the mean time I thought I’d share something I had a helluva time figuring out.

If you’re using Zend Framework and NetBeans, you may be like me and bemoaning the lack of code completion in your Zend Views. As you may know, essentially what Zend_View does is includes your view within a method that belongs to a Zend_View object. This gives your view some nice variable encapsulation as well as access to the $this object (which is how Zend_View provides access to all the ViewHelpers and other functions).

Unfortunately NetBeans can’t figures this out (such is the problem with static analysis on a dynamic language) without help. If you’ve been using NetBeans and its code completion you’ll have already noticed that the PHPDocumentor syntax for @var or @return is how NetBeans figures out much of its code completion information, but that syntax doesn’t work in a view script.

Thanks to Mystic at tiplite.com I now know that to have code completion in your Zend_View scripts in NetBeans, add the following to the top of your view script:

<?php
/* @var $this Zend_View */
?>

Obviously if you’re using custom Zend_View objects you can pass in their class name instead.

Python PHPSerialize Posted To Googlecode

A while back I posted a Python snippet that I noticed could be used in a few other side projects. I have since posted it to Google Code so more than just myself will know it exists: http://code.google.com/p/phpserialize/.

Doctrine Migrations Proper

I was talking with someone (I will edit this post when I find her card and remember her name) here at ZendCon and discovered that they were having trouble with migrations in Doctrine. Having gone through the same issues of Doctrine seemingly not being able to figure out your changes and generate migration classes, I thought I’d post the solution here for future reference.

Assuming you have access to the Doctrine CLI tool, the sequence you need is:

  1. Make the changes to your YAML schema files
  2. Run $ doctrine generate-migrations-diff to generate the migration deltas
  3. Run $ doctrine migrate to determine if your migration deltas are working (a concern if you’re using SQL Server)
  4. Run $ doctrine generate-models-yaml to update your models to reflect the status of your database

The reasoning behind this, and if I’m wrong someone can correct me, is the “generate-migrations-diff” task compares the differences between your YAML schema files and your current models. If you have updated your models before generating the diff, obviously Doctrine will find no difference and generate no migration delta.

Make The Most Of ZendCon

I felt like I should take a break from finishing up my multi-part javascript series to rehash some points being made recently by Keith Casey and Chris Cornutt about making the most of your N-th conference (and in particular, ZendCon).

My first ever professional conference (ignoring BarCamps) was last year’s ZendCon. I showed up in Santa Clara not knowing anyone except for a few brief appearances on #phpc (freenode).

What made ZendCon absolutely enjoyable was indeed what everyone is suggesting to you: the hallway track.

I could have easily attended sessions then hid in my room until the next day, yet I chose to go out to the social events and thanks to that decision, ZendCon ‘08 remains currently one of my fondest memories.

It’s one thing to sit down and listen to talks from famous PHP developers, those that I read about all the time (or read their books in many cases). It’s a whole other beast to find yourself sharing a beer with them in some random “English Pub” while getting your ass kicked at trivia (I still have the beer glasses that were given to me by the real winners).

And these events didn’t happen because I’m some modest uber-genius (I am by no means modest), I’m famous, or even particularly well respected (“He’s not stupid” is as gracious as a comment as I could want in a programming community).

They happened because someone yelled “Pub Crawl!” and, dammit, I was there.

They happened because I struck up conversations with random people.

They happened because I got in religious flame wars with random people. (Ask me about the time, thought not at ZendCon, where I launched into a tirade against CakePHP with who I later found out was the founder of CakePHP)

As it has been reiterated time and time again, this conference is not really about the sessions (it’s a success if there’s just 1 talk that you go to). It’s about the people you meet and the friendships you foster.

In summation, I have a list of goals for you, my loyal readers that are attending ZendCon:

  1. Start a conversation with a random person in a hallway
  2. Find and say hi to an author of one your PHP books. Tell them how awesome the book has been
  3. Attend at least 1 UnCon session
  4. Attend at least 1 post-session social (keep track on Twitter and ask your fellow attendees for info)
  5. Find me and introduce yourself

Solve A Sliding Puzzle With JavaScript And Your AI Course: Part 1

In all my years of web development and formal computer science training, you know I never really got around to truly sitting down and learning JavaScript.

Sure I knew the syntax (C based, not terribly hard), understood closures (LISP will do that to you), understood the prototype approach to Object Orientation (oddly enough playing with Python caused it to finally click).

Well around a month ago The Daily WTF posted one of their weekly programming puzzles.

Lo and behold, it’s the classic “Eight Puzzle” that I had to solve in LISP using several different algorithms!

Feeling particular motivated I decided to finally get around to really learning JavaScript (by learning I mean really knowing the language inside and out, like I know PHP and to a lesser extent Python).

The first thing I had to tackle was: Which algorithm would I choose? There are several to choose from, DFS (depth-first search), BFS (breadth-first search), Greedy, what have you. Well, a testament to my schooling, I do remember the most optimal I could remember was the A* algorithm.

The A* not terribly complex once you look at it properly. Most examples discuss the A*, like most navigation algorithms, as a tree structure which, while academically correct, never actually touches a tree data structure.

The A* algorithm works by examining the current node, the possible exit directions, and how much closer the new states after exit bring you to your goal. It arranges these new nodes in a priority queue and recurses on all the new nodes until such time that the current node is the goal node.

In simpler terms: examine the paths that bring you closer to the goal first.

The Eight-Puzzle is an excellent situation in which to first play with this algorithm as all the pieces we need for the algorithm are easy to conceptualize. It’s just a very simple navigation puzzle: How do we move the blank spot to it’s final destination (and making sure the other pieces are set too).

By pieces we need for the A* algorithm, I mean:

  • Heuristic (or “weight” of a current path, how far are we from the goal, etc.)
  • Expansion Function (from our current node, what are the paths we can take?)

The Expansion function is easy. It’s literally which way can you move the blank spot. If you’re in the exact center of the board, the expansion function will return UP, RIGHT, DOWN, LEFT. If you’re in the top left hand corner, the expansion function will return RIGHT, DOWN.

The Heuristic is a little trickier. If we knew the exact distance (number of moves) a certain state in the puzzle is to the finish, we would need a searching algorithm. Instead we estimate (hence this value being called a heuristic).

2 decent estimations would be counting the number of tiles that are not in their final position as well as calculating the manhattan distance between the blank space and it’s final spot. The manhattan distance is the actual “walking” distance as opposed to the straight line distance. Think of the grid street system that is famously used in New York City. While drawing a line from point A to point B may be 2.5ish miles, in reality you walk maybe 4 miles as you must walk north about 2 miles and east about 2 miles.

Even better is combining the two values. As excellent as manhattan distance sounds for an estimation, you run into inconsistencies like an unsolved board where the blank spot is in the correct position being given more weight in searching than a board 1 step away from being solved with the blank spot only 1 block away from the correct (and final) position.

In Part 2 I will step away from the algorithm and step into JavaScript to build our basic utility function (namely creating and managing a board).

Development Environment Help! Setting Up PHP mail() On Windows, Or: Where Is My Windows sendmail.exe?

Lately at work I’ve been having the worst of trouble getting PHP on my workstation to send mail. Previously it was a simple trek to a website to download a Windows build of sendmail.exe, but for some reason I cannot get access to it, so I have to go another route.

Enter hMailServer, a free, full-featured SMTP/POP/IMAP server for Windows with a pretty, shiny GUI configuration interface. All I really want to do is setup SMTP for localhost only but one could easily use hMailServer as a production mail server.

To start things off, lets make sure our php.ini directives are setup correctly. By correct, I mean PHP needs to be looking for our SMTP server on my local machine (localhost) at the default SMTP port (25), and, just in case, set a default from address:

[mail function]
; For Win32 only.
smtp = localhost
smtp_port = 25

; For Win32 only.
sendmail_from = user@domain.tld

Looks good. Second step is to download and install hMailServer. This tutorial is working from version 5.2 build 356, but you should be able to use the latest stable or unstable version that you might desire.

Once you’re installed and configured, run the administrative application. If you click over to status you will notice a message to the effect of “You haven’t specified the public host name for this computer in the SMTP settings.” That means we have some more configuration to do!

hMailServer Screenshot 1

Now mosey on over to Settings » Protocols » SMTP, navigate to the “Delivery of e-mail” tab. We set our “Local host name” to “localhost” and click “Save”.

hMailServer Screenshot 2

Next, for securities sake (as well as to ensure we don’t have to waste time configuring account as this is only a dev machine), go to Settings » Advanced » IP Ranges » My Computer. Un-check the POP3 and IMAP checkboxes under the “Allow Connections” as we don’t intend to receive mail, nor use the IMAP protocol. Then, un-check everything under “Requires SMTP authentication” as we want our PHP applications to have full reign. Finally, click “Save”. Remember, this is a dev box.

hMailServer Screenshot 3

UNDER NO CIRCUMSTANCES SHOULD YOU USE THESE SETTINGS ON A BOX THAT WILL BE EXPOSING ITSELF TO THE INTERNET OR ON A PRODUCTION SERVER! However, since our local machine will obviously have internet connectivity, lets remove all access from outsiders!

Navigate to Settings » Advanced » IP Ranges » Internet. Un-check EVERYTHING from “Allow connections” to deny outsiders any services, and, just in case, check EVERYTHING under “Require SMTP authentication” and click “Save”.

hMailServer Screenshot 4

And voilà! We have a fully functioning SMTP server that our local PHP environment can use to send test email messages.

The nice thing about our administrative interface is if we go to Status, navigate to the “Logging” tab, and click “Start,” we can capture the dialogue between hMailServer and your PHP app when sending an email address (very useful for debugging).

Good News Everyone!

Naturally it’s been over a month since I’ve updated and rather than posting something techincal I feel I should be a little selfish and announce that:

I’M GOING TO BE SPEAKING AT ZENDCON 09!

I will be giving my talk on automated deployment techniques with Phing.

To say that I’m excited is quite an understatement. Nervous now probably tops excitement as now I have to make sure I give a damned good talk and not make Eli White look like a fool for having picked me for a slot.

Time to go bury my nose in Power Point and research!

Logitech MX Revolution revoco in Ubuntu 9.04 Jaunty: Click-to-Click even after a resume/wakeup

It’s been a LOONG time since I’ve posted eh?

Well I finally solved my issues I’ve been having with revoco in the later version of Ubuntu. For those of you who don’t know, when you buy a Logitech MX Revolution mouse (or its ilk), the middle button can alternatively work in “click-to-click” mode (where you feel “clicking” when you spin the wheel) or “free spin” mode where the wheel spins free of resistance. By default the mouse maps the middle click to alternate in between these modes (by default I mean every time it loses connection with the PC, e.g. in the event of a shut down). This has the unfortunate habit of also laying the smack down on a normal middle button event (like middle clicking a link in Firefox to open it up in a new tab) sent to the PC (plus I hate free spin).

For a while btnx solved my problems as it had the ability to send revoco signals to supported mice, but recent changes in Xorg have rendered this useless.

However an enterprising individual named Edgar Toernig wrote a command line utility called revoco that lets you set the modes.

So to get the mouse to always work in click-to-click mode (as you would expect it) you would first need to get a copy of revoco from here. Alternatively, if the site goes down you can download revoco version 0.5 from me.

Next you’ll need to compile it (just run make in the extracted directory).

Once it’s all compiled, I like to use sudo to move the file to /usr/local/bin/.

Next I create an init.d script to set the mouse to click-to-click on boot. Save the following to the text file /etc/init.d/revoco:

#!/bin/bash
/usr/local/bin/revoco click

Finally run a chmod +x /etc/init.d/revoco to allow the code to execute.

All this is well and good but you’ll notice that on a resume from hibernate/sleep, your mouse will be back to its old shenanigans. To fix this we want to create a script in /etc/pm/sleep.d/. So in this folder lets edit a text file 10revoco:

#!/bin/bash
case "$1" in
        hibernate|suspend)
                /usr/local/bin/revoco click
                ;;
        thaw|resume)
                /usr/local/bin/revoco click
                ;;
        *) exit $NA
                ;;
esac

Again lets run a chmod +x /etc/pm/sleep.d/10revoco to allow us to execute

Now if you give it a try, you’ll notice that even on wakeup/resume from hibernation/suspend your mouse will stay in click to click mode!

tamulink-wpa and Ubuntu (For my aggie linux readers)

Finally, I no longer have the pain of not being able to connect to the wireless network on campus (without having wicd installed).

I got it working using the network-manager applet in Gnome that comes installed by default (cause I like it and it makes my life easier). I’ve had people poke fun at me because I don’t feel like traversing the console and running wpa_supplicant manually, I have better things to do, like expecting things to work with the least hassle. But that’s a rant for another time.

Sadly CIS or whoever is responsible for the wireless networks has decided that Ubuntu, Fedora, or any other flavor of Linux won’t be supported. Thanks to one enterprising Maurice Rahe, I had enough information to get started. Since I was working with Ubuntu 9.10 (Jaunty Jackelope) Alpha 6, I needed to update the instructions a bit and turns out we didn’t need to do the manual wpa_supplicant.conf at all. Simply attempt to connect to tamulink-wpa and when it asks for the connection details:

Security
WPA & WPA 2 Enterprise
Authentication
Protected EAP (PEAP)
Anonymous Identity
Leave Blank
CA Certificate
/usr/share/ca-certificates/mozilla/ValiCert_Class_2_VA.crt
PEAP Version
Version 0
Inner Authentication
MSCHAPv2
User Name
NETID
Password
NETID Password

VOILA, it works! Reconnections kinda suck, but what’ll you do.

Calculating Daylight Savings Time Boundary In PHP

I had an issue recently where I needed to calculate the Unix timestamp for the daylight savings time boundaries. According to the United States Naval Observatory, daylight savings time begins the Second Sunday of March and ends on the First Sunday of November.

Awkward date calculations if you don’t have the magical strtotime() function in PHP. strtotime() is able to do relativistic time conversions from the common “+1 hours” to the more complex (and more relevant) “Second Sunday March 0″.

Why do we do the ‘March 0′ in the above string to calculate the start boundary? Doing some tests with strtotime() reveals some behavior you should be aware of.

strtotime("March"); doesn’t actually give you the first of March, it gives you the current day in the month specified (date('D, F j, Y, g:i a', strtotime("March")); returns Tue, March 10, 2009, 12:00 am at the time of this post). Doing a similar test but substituting April for March results in the 10th of April (at 12 am).

Now in most cases doing a strtotime("March 1") will suffice (date('D, F j, Y, g:i a', strtotime("March 1")); results in Sun, March 1, 2009, 12:00 am). However, as you can tell, this month is going to be awkward because the first day of the month is a Sunday. strtotime(), when calculating the fuzzy “Second Sunday,” doesn’t include the current day. So calculating date('D, F j, Y, g:i a', strtotime("Second Sunday March 1")); will actually return the 3rd Sunday (Sun, March 15, 2009, 12:00 am).

So our solution is actually to take a step back and return the PREVIOUS day to the first day of March and then calculate the Second Sunday from there (since we know that starting from the next day will account for the first). Normally, dealing with the last day in February is a headache, BUT again thanks to PHP magic we don’t have to figure out if it’s February 28th or 29th, we merely do a “March 0″ which steps us back a month (date('D, F j, Y, g:i a', strtotime("March 0")); returns Sat, February 28, 2009, 12:00 am). From there we can calculate the Second Sunday with ease and eventually determine that the second sunday is March 8th, which is confirmed by the above USNO website.

Applying these lessons to calculating the first Sunday in November we come up with the following snippit:

<?php
$remove_hour = strtotime("Second Sunday March 0");
$add_hour = strtotime("First Sunday November 0");

$time  = time();

if( $time >= $remove_hour && $time < $add_hour )
{
    var_dump("Lost an hour");
}
else
{
    var_dump("Gained an hour");
}

Cheers!