Mirror mobile device screen to your computer

I needed to perform a demo of a tool where I would utilize my mobile device (phone) to perform an action, and it caused a reaction on my laptop.  However, part of the “WOW” factor is to mirror my mobile device screen onto my laptop so the viewer can see both the mobile device and the web browser.

Thanks to Apple’s AirPlay this is relatively easy for the iPhone with the purchase of 3rd part software like Air Squirrels Reflector, but I don’t have an iPhone. (I can never figure out how to switch between apps, or how to go back if the app developer didn’t include a back button in the app.  But I digress.)  Instead I have an Android device, which has a much larger user base, and I really didn’t want to switch.  Unfortunately nobody has created a 3rd party application that utilizes the Cast Screen functionality of Android in the same manner as the AirPlay.

In searching I found many solutions that required the user to “root” their mobile device.  This really wasn’t an option for me.  I have a Google Nexus device, so I’m not really held back by mobile vendor limitations, lock downs, or pre-installed software.  No need to “root” my device.  I’ve rooted/unlocked other mobile devices in the past, and since I’m not a mobile developer, I feel no need to tinker with what works for me.

I did manage to find a couple other solutions (one with the help of my co-workers) that did work without altering my device software, or installing applications on my laptop.  Well, that is not entirely true.  Both of the solutions I’m about to share did require the Java runtime environment to be installed, but I consider that a mute point since most computers these days already have it installed for one reason or another. (Most developer IDE’s already require it, so I already had it.)

Step 1 – Ensure you have JRE

As I said, for this to work you will need to have the Java Runtime Environment of some sort installed on your system.  If you don’t already have the JRE installed you can do it at http://java.com.

Step 2 – Connect with USB

You must connect your Android device to your PC via USB connection for this to work.  As of this writing I have not found a way to make this wireless.

Step 3 – Enable Developer Mode

By default Android devices do not come with Developer Mode enabled.  This mode is needed so we can take advantage of debugging via USB tether.

On Android devices prior to 4.2 you could set USB Debugging from the settings…easy-peasy.

To enable this on Android 4.2+ go into Settings->AboutPhone and tap the Build Number 7 times.  The device will inform you that Developer Mode is now enabled.  Click back to hit the previous screen and you will now see Developer Options available.  Check the box for USB Debugging and you’re done.

Step 4 – Download the Android developer tools

For simplicity sake I only downloaded the standalone Android SDK Tools Only. (I had no use for the Studio.) I did this at the URL http://developer.android.com/sdk/index.html#Other, then unzipped the file to a place of my liking.

After making the file ‘/tools/android’ executable I ran it on the system.  This opens the Android SDK Manager window.  The purpose for this is to download and install the needed packages to allow us to “develop” Android apps.  I didn’t change a thing and simply clicked the button that said “Install n packages”. (Note: n will be some sort of number.)

It took awhile for the manager to do the update/download, but after it was completed I simply closed it.  This would have downloaded a bunch of things, but the most important for us is ‘/platform-tools/adb’ which is required to mirror our device screen to the PC. (Make sure this file is executable as well.)

Step 5 – Add locations to the PATH

For this screen sharing to work you will need to add two folders of the Android SDK to your PATH: ‘/platform-tools’ and ‘/tools’.  I did this by editing my .bashrc file as follows:

export PATH=$PATH:/home/aculp/android-sdk-linux/platform-tools:/home/aculp/android-sdk-linux/tools

Step 6 – Download Apps

There are two possible apps to use to do this:

Both carry the same sorts of functionality, however Droid @ Screen is a bit more mature and makes additional options a little easier.  One thing I didn’t like was the need to have an extra window open for the settings.  Due to my being a fan of simplicity I have been using Android-Screen-Monitor.

Both apps are a simple matter of executing the jar file using java and they just work.

Step 7 – Launch it!

Now it is simply a matter of launching either the Android-Screen-Monitor or Droid@Screen application. I did this via CLI like so:

$ java -jar asm.jar

NOTE: This command assumes we changed directory to where we downloaded the Android-Screen-Monitor jar file.

Conclusion

If you have questions or comments please post them.  I will return to this post and tweak it a bit more to become really easy to use, but for now this is mostly what I did.

Clone Hard Drive to External USB Drive via CLI

Thumb and USB drives

No matter what OS you’re cloning, using “dd” via command line will still work.  I personally tested while cloning a 1TB Ubuntu hard drive to a fancy new 1TB SSD.

Backstory: I purchased a new Dell 7737 laptop with a 1TB hybrid drive, which turned out to be slower than watching paint dry compared to the old SSD I’d been using for a few years.  Otherwise it is a kickass laptop.  So I purchased a 1TB SSD after finding they are roughly 50 cents per GB these days…very affordable.

First I put the new SSD into USB caddy I had laying around for backup purposes.

Next I created a bootable USB stick with an Ubuntu ISO image following the instructions at:

Windows = http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows
Ubuntu = http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-ubuntu
MAC = http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-mac-osx

With the USB stick created I booted the system to Ubuntu using the USB LiveCD disk image.  It may require a BIOS change to enable the PC/Laptop to boot from USB device.  Doing this will not make any changes to your current hard drive as long as “Install Ubuntu” is not chosen.

Once booted up I was able to use Gparted, which is a standard app on the LiveCD, to create a new partition table on the new drive in the external USB caddy.

I then used fdisk via command line to find all disks and gain their identifiers needed.

fdisk -l

With the new partition and the identifier of the USB drive I was now ready to initiate the copy.  I used the following command to do that:

dd if=/dev/sdc of=/dev/sdb mb=8M && sync

NOTE: ‘if’ = read from and ‘of’ = write to.

It takes a very long time for this to finish up, especially with larger drives, but the end result was a working drive with my data on it.

After completion I simply switched out the SSD from the caddy with the internal HD in the laptop and all worked well.

Good luck!

Create global .gitignore for user settings

ignored

When it comes to ignoring files in a git repository I do something I think many others have done.  I’ve added user level settings files to my .gitignore because I don’t want them included in my git repository.  You know, the files created by an IDE, operating system, or other applications.  Such as ‘.project’ created by Zend Studio or ‘.idea’ created by PHPStorm, and there are many others.

While it may be acceptable to add them to the .gitignore file in a private repo, should they be ignored in a publicly shared repository?  To answer this let me explain that I believe in “freedom”, and think everyone is entitled to do what they want, as long as it doesn’t hinder someone else’s freedom.  This is important when it comes to code.  Therefore, these files should NOT be ignored in the .gitignore of a public repo because someone creating a clone of the repo may desire to do something different.  So marking these files to be ignored, or not, should totally be a personal decision made by the user.

However, there is a way to have our cake, and eat it too.  We can inform our local instance of git to have a system global .gitignore file.  Therefore while the individual repository has a clean .gitignore file, with only references specific to the project, we can still have our user level ignores in place.  Here is how to do it.

From command line issue the following command: (command is non-Windows because of the file location, I’m not sure what it would be on a Windows machine, so perhaps someone can comment with a Windows friendly command)

$ git config --global core.excludesfile ~/.gitignore_global

This command creates a global setting in our systems git configuration informing git of an excludes file containing additional files to ignore globally.  The file name will be called ‘.gitignore_global’ and will be located in the users home directory.

Adding this –global config setting to git does not create the file for us, so we will still need to create this file in the location we specified. (The home directory in this case.)  Here is what mine looks like:

.idea
.buildpath
.project
.settings
.vagrant
.DS_Store
nbproject
.thumbs

Meanwhile my project level .gitignore might look like:

/vendor
local.config.php

For more on this topic, and perhaps a better explanation, please see https://help.github.com/articles/ignoring-files.

Developer pool sustainability

Developer hunting

Over the past couple years I’ve noticed a rise of good companies no longer outsource offshore to save money, instead they outsource because they can’t find developers here.  Notice, I said “good companies” because there are still poorly managed companies who believe the hype of offshore developers saving them money.  Since the poorly managed companies will eventually join the ranks of failures with their next social “thing”, we’ll stay focused on good companies here.

I’m sad to see the dwindling number of developers available to fill a growing number of jobs in South Florida.  Local colleges and universities don’t seem to be helping, with outdated course material and terrible intern programs that aren’t helping prepare grads for “real” jobs after graduation.  Couple this with most companies and recruiters simply drain the pool without giving back, and governments sinking more and more of our hard earned taxes into already flooded non-tech related fields.  The end result is higher unemployment, folks with a degree who can’t find work, and the vicious cycle continues on and on.

South Florida is a pretty large tech hub but we are losing developers at an alarming rate without filling tomorrow’s developer pool.  Where are developers going?

  • Good students are picked up from companies outside of South Florida.
  • Other students tend to work in unrelated fields because local companies are unwilling to hire entry level and train. (myth of getting to market faster)
  • Experienced developers move to other areas with higher salaries and better culture.
  • Those developers who stick it out in South Florida often burn out after a few years because local companies didn’t treat them well.

If we continually cut down trees in the forest we eventually find there are no more to cut down, leading to an environment where companies and recruiters head hunt among themselves to stay afloat.  Hint: This doesn’t help developers, it doesn’t help the community, and it doesn’t help companies (higher acquisition, training, and retention costs).

Companies removing developers from the market, but not contributing so other developers can be created is a fairly large problem.  It is not sustainable, and we need to make companies aware of this, to prevent a very dismal tomorrow.  The folks over at Tech.Nottingham wrote a great blog post about this, so go check it out for more details on how you and your company can start contributing for a better tomorrow. http://www.technottingham.com/news/2014/7/29/tech-companies-are-you-contributing-or-just-consuming

For companies or techs in South Florida who doubt this, look no farther than the nearest event happening in your own back yard.  Now look down…at the companies sponsoring the event.  Are they local companies?  Are they companies that are interested in growing the local community?  Is it your company?  I’ll close with that thought.

Categorized under: productivity

Schedule for a productive day

Thanks to a friends tweet I found a handy post on “The Week” which highlighted schedules of successful people and productivity tips around optimized daily appointments.  Much of it rang true with me, so to prevent me from losing sight of it I decided to reiterate it here.

  • Early morning

    • Wake early, to get things going prior to insanity starting. Before goals have competition.
    • Many stick to a morning ritual.
    • Set concrete goals for the day.
  • First things

    • Tackle important things early/first.  The first couple hours of the day are our most productive, don’t waste them on email and/or meetings.
    • Escape to a quiet place, distractions make us stupid.  Avoid “drive-by” meetings, they will leech your most productive time.
    • We’re more disciplined in the morning, so take advantage of it.
    • Energy is high – do creative and challenging work.
    • Having troubles working on what is needed?  Get in earlier.
  • Slowdown blahs = regroup time

    • Take a break, get a snack, take a power nap.  Often a power nap is like a reset button.
    • Re-enact the morning ritual to get going again.
    • Review goals of the day.
    • Focus on successes from earlier in the day.
  • Afternoon lull

    • Energy is low – do busy work.
    • Best time for meetings.
    • Good time for a run. (personal note about me)
    • Distractions can be a benefit when we can’t focus.
  • Evening

    • Before dinner write down goals for following day.
    • Do some relaxing activities.
      • TV, video games, eating are not relaxing. #mindtricks
      • Instead meet with friends, talk, play with hobbies. #truth
    • Get to bed at a good time, lack of sleep makes us stupid.

Adam Culp OSCON 2014 Interview

While at OSCON 2014 speaking about refactoring I gave an interview.  Here it is:

Fun with Travis CI and PHP projects

I know I should have done this a long time ago, but I finally got my hands dirty with Travis CI.  I wanted to set up a php project on github to use Travis CI to monitor the status, in case I forgot to run the tests prior to pushing.  Unfortunately it was not as easy as it’s made out to be.  But now that I’ve done it once, it’ll be easier next time.  So, here is how I tackled it.

First, creating an account and getting started was easy.  I simply clicked the “sign in” link on the Travis CI site and entered my github credentials which authorized Travis CI to connect to my account. (the site informs you exactly what Travis CI will have access to)  Once that’s done Travis gets all my repos, so I can then activate them for Travis CI.  If that doesn’t happen automatically there is a handy “sync now” button to coax Travis CI.

NOTE: To connect public repos you would use https://travis-ci.org, while for private repos you would use https://travis-ci.com.  While pubic repos are free private ones cost money, though you do get 100 pushes free to get you started.

Second, it’s now time to click the + and add a new repo to be tracked by Travis CI.  After clicking you will be presented with a list of your repos to choose from.  It is simply a matter of turning the repo ON by clicking the switch.  I also clicked the wrench to select the option to “Built only if .travis.yml is present”.

Travis CI add repo

The structure of the app I added looks like this: (including all files needed for travis and unit testing) https://github.com/adamculp/api-consumer

Application structure

Third, I needed to create the .travis.yml file with the directives needed to make it all work.  Here is what my file looked like.

travis.yml file

Pretty simple.  Here is what it all means: I specified what language to use (php), and what versions of the language to test with (5.3, 5.4, and 5.5), I also instructed to have Composer install prior to any other scripts run (needed to ensure there was an autoloader, created by Composer), and finally I add the phpunit command and tell it where to find the phpunit.xml file (in this case it was in the tests directory).

Fourth, ensure that PHPUnit runs as expected locally.  Yes, you will need unit tests on your code.  That’s like one of the main reasons to do this in the first place.  Here is what my phpunit.xml and bootstrap.php look like:

phpunit.xml file

The phpunit.xml file is fairly simple.  It informs where PHPUnit can find the bootstrap.php file (same directory as a the phpunit.xml), and sets a whitelist of directory where code can be found (some use a blacklist and specify not to use the /vendor directory), and what directory to find tests in (the current directory).

phpunit bootstrap.php file

The bootstrap.php file specified by the phpunit.xml file is even simpler, as it only specifies where to find the autoload.php file created by the Composer install.

Fifth, take a quick peek at the settings for the repo on github and you will notice that Travis CI should be already set up and ready for something to be pushed.

github settings

Final, that’s it!  That is everything needed for Travis CI.  Of course this example is very simplistic, since the repo and tests are only on a single wrapper class I created.  But it’s good enough for a start, and if you need more the documentation is pretty good.  With these files created, all that remains is for me to commit changes to git, then do a push to origin at github.  Once the push to origin happens a Travis CI trigger at github fires and informs Travis CI to create a new build on a VM (virtual machine) then run the tests on the newest code.  After Travis CI finishes it lets you know with an email, and through the site. (green = good)

Travis CI feedback

One last thing you may want to do is add the Travis CI image to your README.md at github.  This will allow you and others to see whether the current master branch had a successful build, or if it failed.

[![Build Status](https://travis-ci.org/adamculp/api-consumer.svg?branch=master)](https://travis-ci.org/adamculp/api-consumer)

Travis CI build status indicator

Enjoy!

Developer Anxiety, we’re not alone

Yesterday I was approached by a developer, apprentice, friend, and sometimes mentor, who was having some personal issues.  I consider this person to be very strong, and capable of great things.  I’ve watched over some years, and I’m really impressed with their progress personally as well as professionally.  However, these facts only increased the shock of what they revealed to me, and must have been very difficult for them to share.

During the conversation it was revealed how they’re experiencing HUGE anxiety, complete with panic attacks, and are even consulting a physician who prescribed medication for it.  As this person spoke I could see the anxiety levels grow within through their body language , and witnessed the “deer caught in headlights” look as they wrestled on the precipice of going into another panic attack.  Though I had someplace I needed to be, I knew I couldn’t leave this person alone to struggle as I had so often in the past.  So I lingered, and we talked until the ebb had calmed.

My heart went out to my friend because I’ve dealt with the same feelings and problems, and had always done it alone. (Except for a few trips to the ER in past years to ensure it wasn’t really a heart attack.)  Oh, how well I can recall the feelings of fear and doubt.  Not knowing when my body will randomly boost my adrenalin to extreme levels that push me over the edge, fighting for my next breath until my chest loosens again.

Yes, I know I “seem” different in person as I talking loudly and laughing at conferences.  It has taken me many years to get to that point.  And yes, inside I’m constantly forcing down the roiling anxiety that never truly subsides.  So don’t get caught up in the stereotypical idea that someone with anxiety is this lonely person crying while huddled in a ball in the corner.  That is not me.  My stress and anxiety doesn’t come from being around people (unless they’re stupid), or from public speaking and such things.  I’m fairly social, but stress by other things such as deadlines, lack of requirements, distractions, fear of failure, and bad code, can be just as damaging.

Another common misconception is that anxiety is caused by the stress of the moment, which is simply not true.  A doctor I consulted with in the past informed me that anxiety can be caused by stresses from as long as six month ago.  So moving to a new home may seem OK at the time, but up to 6 months from now we suffer from the effects of the stress.  So, by the time we have an anxiety attack it’s too late to fix it.  All we can do is deal with the anxiety and push through it somehow.

For each of us the cause is slightly different, because we each struggle with our own problems and/or OCDs.  For my friend it was developer related stresses that many of us deal with:

  • Working on a development team and not kept busy enough, so we internalizing the many things that weigh on our shoulders in such situations.  Will we be downsized because someone realizes we’re not busy?  What should we do with our time?  Is the company failing due to lack of feature requests?  Is it fair to collect a paycheck for filling time?  Am I not good enough?  And the list goes on.
  • Working on a codebase that really needs a major refactor, but nobody will give the OK to do it.
  • Witnessing a company rewriting an application, and realizing it’s as bad as the original.
  • Wanting to contribute, but not knowing how to start.  Sure, it’s easy to say, “Just pick a project and start.”  But in reality it’s not that easy internally.
  • Impossibly tight deadlines.
  • Lack of requirements for a project.
  • Relocating.
  • Can’t seem to keep pace with new technologies.
  • Open work spaces.
  • Noises, motion, or cube drive-by ending in a meeting.
  • Having questions, but not wanting to bother others by asking.
  • Feel like an imposter. (see imposter syndrome)
  • Feeling you’re alone, or perhaps you’re some “weirdo” because nobody else speaks about these things.

Some advice I gave, based on how I handle things:

  • Tension Tamer tea by Celestial Seasons.
  • Licorice root capsules twice a day when stress is high. (but as one commenter added, can cause side-effects)
  • Learning how to say “no” to tight deadlines.
  • Take a walk during lunch time.
  • Read a book.  Not a technical one.  Something not related to work. Maybe something inspirational, or a fiction.
  • Learned how to gather requirements for projects, and do proper time estimates.
  • Running, or some other physical activity to get the heart rate up 20 minutes or more a day.
  • Talk with others, even though we would rather be alone. (maybe even professional listeners)
  • Join, or create, a user group to pull others like me together.
  • Teach others how to create better code, so I don’t need to see bad code as often. (never ending)
  • Work from home.
  • Get a new job. Not a new profession. (extreme, but sometimes it’s the only way)
  • Get an annual checkup, so I know I’m healthy and not having a heart attack when anxiety kicks in.

I don’t really have the answers, nobody does.  But felt I should create this post and put it out there.  Perhaps others will read it and realize they’re not alone.  And sometimes just knowing that can help lessen the stress levels.

How do you handle the stress?

NOTE: I received permission from my friend to share this story, so it wouldn’t cause any more stress and anxiety by sharing it without their knowing.

Categorized under: linux, php, Sendmail, Ubuntu, Zend Server

Zend Server and Sendmail failure bug

While trying to test the sendmail feature of Zend Server 6.3, on Ubuntu and CentOS, there was a bug.  I discovered that utilizing the Mail Preferences area of the Adminitration->Settings page and sending a test email to myself with the Sendmail option ended in an “Unknown error”.

The error returned by Zend Framework 2, which is used by Zend Server 6 was a generic error (Unknown error) if Sendmail returned an error status, but an empty error message.  Not much help, or was it?

Since the error appeared to be caused by Sendmail not returning a proper error the search for the issue led there.  See where my logic was going? My next step was to test sending an email with the PHP mail() function, and see if that shed any light on the issue.  Unfortunately it worked, which meant the issue was elsewhere.  But if the error wasn’t with PHP, Apache, Sendmail, Zend Server, or Zend Framework, where could it be?

At this point I enlisted one of my coworkers, Roman Basayev, who nailed it down.

Of course!  Zend Server on Linux installs Lighttpd for the Zend Server gui, and there must be a setting there for using Sendmail.  Sure enough in the file ‘/usr/local/zend/gui/lighttpd/etc/php-fcgi.ini’ there is a setting for ‘sendmail_path’ and it was empty.  So PHP running on Lighttpd was not able to find Sendmail, and therefore was not getting a decent error message.

The fix:

In the file ‘/usr/local/zend/gui/lighttpd/etc/php-fcgi.ini’ update the ‘sendmail_path’ to be ‘/usr/sbin/sendmail -ti’.  These are the paths on Ubuntu and CentOS, others may vary.

sendmail_path = "/usr/sbin/sendmail -ti"

After restarting Zend Server, all should be good  to go now.

Simple reminder to keep it simple

This morning a tweet caught my attention prompting me to read this post by Gary Hockin also known as @GeeH. (There’s just something about that voice.[inside joke])  In the post he talks of his experiences while attempting to simplify code in a project, and in the process uncovers hidden dependencies that increased the codebase significantly in order to gain the benefit of a mere 100 lines of code.  He also highlights that in today’s mainstream PHP development, where many are using Composer to blindly include packages into applications, we may not fully understand code being pulled in with the consequence of accepting responsibility to maintain those additional packages as well.

I’ll wait a second while that sinks in…

Yes, that’s right.  If you include additional packages and libraries into your application you’re accepting the responsibility to maintain them.  No, I’m not saying you are responsible for contributing to the software package…unless you care to.  What I’m saying is you are now in charge of updating the software within your application, which now includes additional packages created by others.  As security holes get fixed, or new versions come out fixing bugs, it is up to you to ensure you update these packages in your applications which include them.

You’ve been living in a dream world Neo

Ha, didn’t think about that, did you?  If you did, Bravo, you’re behaving like a professional.  For the rest, welcome to reality.  Now go update the applications you’ve neglected.  But first a side note.

I’m not saying Composer is bad.  Actually I think the opposite.  Composer is awesome, and you should be using it if you’re not already.  As in the post by Gary above I’m simply saying it’s our professional duty to know what we’re asking Composer to do on our behalf.  Use it responsibly and do a bit of research so you’re not blindly including potential issues, bugs, security holes, and nightmares to maintain in the future.  Then if you’re satisfied with what you see, go ahead and “require” away.

But wait!  Don’t just look at the packages you’re including into your codebase.  Also take a look at their dependencies as well, because you are also accepting them in the process.  Know what you’re saying “yes” to.

Past knowledge

None of what I’m saying is new stuff.  A while back, in the beginning of 2012 (I thought it was earlier for some reason), Ed Finkler @funkatron wrote the original MicroPHP Manifesto to voice his concern over many frameworks starting to grow in size. (NOTE: Later there was a separate domain dedicated to housing the MicroPHP Manifesto, but I like the original better because the blog post associated with it helps highlight why it’s a concern.)  I encourage you to check it out and consider the meaning, and how it relates to your projects.

Again, nobody is saying large full frameworks are evil or other libraries should not be used.  The idea behind all of this is to caution, so you go in with your eyes open and “know” what you’re including in the codebase.  Know the responsibilities accepted by including other libraries.

Happy coding!

Zend Framework 2 XML Sitemap

While tweaking the SunshinePHP site to be a bit more SEO friendly I realized we had neglected to create a sitemap for search engines to find.  I was pleasantly surprised to see the Navigation component of Zend Framework 2 includes a bunch of view helpers, including a Sitemap helper.  So now I have an xml sitemap created by Zend Framework 2 that works hand in hand with the site navigation.  However, the documentation was not complete as of this writing and caused me to do a bit of trial and error debugging to get it working.  Below I will post how I got it working, in hopes it will help others. (If the ZF2 folks like this post I will go in an update the documentation later.)  As with most things in Zend Framework 2 there may be more than one way to do things, but this is how I did it. (Until someone informs me of a better way.)

Module Config

In the Application module.config.php I created a factories node in the service_manager container where I pulled in the DefaultNavigationFactory.

factory

Then I also added a navigation container where I specified the sitemap for the site.

NOTE: To add navigation specific for each module you would simply create this container in the specific module.config.php.

navigation

Next I added a route for the future sitemap to be viewed.  Notice how I simply added a sitemapAction to the Application IndexController.  You can add it wherever you desire if you want to create a separate controller or whatever, I just left it there.

route

Layout

Because I just want the xml produced by the helper, I created a blank layout xml.phtml that does nothing more than output the content of the view.

layout

View

The sitemap.phtml view is also pretty simple and outputs the xml sitemap created by the helper.

view

Controller

In my controller I specified the layout to use, nothing more was needed.

controller

Verify

By navigation to the URL specified in the route we should now be able to view the XML output.

sitemap

Future

In this example someone would need to navigate to /sitemap to view the sitemap, but some automated tools would try to go to /sitemap.xml which would fail with this setup.  I will come back at some point in the future and enable the file extension to be ignored (after I figure out how).

Conclusion

The entire process is really pretty simple once the pieces are all in place, and the output was accepted by the various search engine webmaster tools…SCORE!

PHPUnit, Composer, PHPStorm, Oh my!

Installing PHPUnit within a project via Composer, then running tests through PHPStorm is not an intuitive process. However, with the right steps it’s actually pretty simple. Here is my story:

To launch the call for papers for the SunshinePHP Developer Conference it was a pleasure to use the OpenCFP project as a starting point rather than creating the entire thing from scratch.  While the project is still a “beta” with a few wrinkles to get ironed out, it’s still a pretty nice effort. (I have a pull requests pending, and another to submit.  Love open source!)

For my CFP I wanted a few more fields of information than the “out of the box” setup, so I quickly added them to the app.  However, doing this meant the included unit tests would fail.  But wait, I hadn’t run the unit tests yet!  I realized immediately how spoiled I had become with today’s modern frameworks with a testing method built in.  This little project did not have that luxury, so I would need to run the tests the old fashioned way, or let an IDE do it for me.  I decided to configure PHPStorm do it. (I’ll do the same for Zend Studio in another post later.)

The way OpenCFP was set up, using Composer, meant that PHPUnit was already placed in the /vendor directory as a requirement in the composer.json.  So rather than taking the lazy way out and using the PHPUnit already installed globally on my system, I wanted to use the latest PHPUnit within the project.  This requires 2 setup steps in PHPStorm.

Step 1

To start I needed to inform the IDE where to find the Composer autoload file and leverage the awesome PSR-0 goodness to autoload PHPUnit in the /vendor directory.  To do this I open the Settings via the icon on the toolbar, or by using the File->Settings menu item, or hitting the Ctrl+Alt+S keyboard shortcut.  Then in the Project Settings (top section) I expanded PHP to get the PHPUnit dialog.

PHPUnit setup in PHPStorm

Step 2

Now I had to add a Run/Debug Configuration for the project.  I did this by clicking on the toolbar dropdown and selecting Edit Configurations.

Edit Configuration

Once the dialog opened I clicked the “+” to add a run configuration, and select the PHPUnit type.

Choose configuration type

Now it was just a matter of adding the directory where the tests reside. (Name the configuration to your taste.)

Location of tests

All done!!!  Now I was able to run the tests simply by selecting the new run configuration defined in the dropdown, and clicking the Run button in the toolbar.

Good luck, and happy testing!

Categorized under: Quick Tips, VirtualBox

Copy and paste from virtual machines to host

With the growth of using virtual machines as development environments, thanks to great projects like Vagrant and Puphpet.com, I have been using virtual environments for most of my development these days.  On some occasions, because I use Ubuntu as my primary operating system on my development laptop, I have the need for a Windows environment in order to work with certain clients. (Sad, I know.)

Well, while using these Windows environments it is a royal pain if I cannot copy and paste back and forth between the host and virtual machine.  So I have always resorted to installing the Guest Additions (I use VirtualBox) to make this possible.  However, recently this stopped working for some reason.  I honestly didn’t have the time to investigate so just overlooked it and kept going. (I honestly don’t use a gui very often within a vm.)

Today I finally got tired of looking the other way and investigated why I couldn’t copy/paste between host and vm.

The Fix

Turns out there is a very easy solution.  I guess at some point the copy/paste functionality setting is turned off by default.  So I simply needed to click on the VirtualBox “Devices” menu drill into the “Shared Clipboard” submenu and then select the option I desired.

Now things are working as I expected.

Categorized under: php, profiling, programming, Quick Tips

XHProf PHP Profiling

Today I set up my development environment so I can use XHProf to profile PHP scripts when needed, and it was pretty easy.

For starters, I use Ubuntu as the operating system for my desktop environment. So while the information below may be helpful, I will not cover any other OS in my descriptions.

XHProf is a PECL package, and can be easily installed by using standard PECL commands.  However, XHProf is still beta and the default settings of PECL will only install stable packages.  Don’t fear, there is a way within PECL to handle this by appending “-beta” to the end of the module name: (also note how I am using sudo to act as the admin user on Ubuntu)

sudo pecl install xhprof-beta

After issuing the command PECL will do its job of installing the PHP module but will not add it to the php.ini, so that must be done manually.  The default location of the php.ini in Ubuntu is at ‘/etc/php5/apache2/php.ini’, so we edit it there:

sudo vi /etc/php5/apache2/php.ini

We add a single line to the end of the php.ini to activate the module:

extension=xhprof.so

Then we restart Apache for the new setting to take affect:

sudo service apache2 restart

At this point we now have the XHProf module in PHP for Apache related calls to PHP.  If we add ‘phpinfo();’ to a PHP file and view it in a browser we see XHProf is now available for use.

NOTE: This does not make XHProf available for CLI activity. (command line run PHP scripts)  We also need to add the extension to the ‘/etc/php5/cli/php.ini’ file as well to make it available via command line PHP.

Now that XHProf is ready to be used I added it to the PHP script I wanted to profile.  Basically this is just a command to kick off the profiling at the beginning of the script, and some commands to save the results at the end of the script.

In the beginning add the following to start recording at the beginning, and adds CPU and memory info to the output:

xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);

Then at the end add the following to halt profiling and then using XHProf utilities create the output:

$xhprof_data = xhprof_disable();
$appNamespace = 'some_namespace_here';
include_once '/usr/share/php/xhprof_lib/utils/xhprof_lib.php';
include_once '/usr/share/php/xhprof_lib/utils/xhprof_runs.php';
 
$xhprof_runs = new XHProfRuns_Default();
$xhprof_runs->save_run($xhprof_data, $appNamespace);

NOTE: XHProf will dump the results in the ‘/tmp’ location on the system named something like {run_id}.{app_namespace}.xhprof (Ex.- 51f384b8cb9f2.some_namespace_here.xhprof), but the contents are not truly human readable.  I recommend using the tools provided by XHProf to help make them viewable in HTML.

How I made XHProf files pretty

I am Lazy a HUGE fan of doing things simple, so to make the XHProf output readable and easier to use I simply created 3 files in my document root of Apache like so:

index.php

include_once '/usr/share/php/xhprof_html/index.php';

callgraph.php

include_once '/usr/share/php/xhprof_html/callgraph.php';

typeahead.php

include_once '/usr/share/php/xhprof_html/typeahead.php';

No sense in reinventing the wheel.  These 3 files simply included the files already existing in the XHProf module, which call the output files directly from the ‘/tmp’ location on my system.

By calling to http://localhost/index.php I am now greeted with a list of links representing the different files output from XHProf to the ‘/tmp’ location as I executed the PHP scripts calling to XHProf. (shown below)

xhprof_files

Now when I click on the individual links I can view the output from XHProf in a friendly HTML format, like below:

xhprof_details

So, there we go.  Enjoy!

Developer advice

As the organizer of the SoFloPHP User Group I am often approached by entry to mid-level developers asking what they can do to advance in their career or become better developers.  Of course I am nowhere near perfect but have been around long enough to get a few bumps and bruises along the way, so below is what I usually share as some pointers:

Note: While some of these items are kind of PHP specific, others may find useful items as well.

  • No self-respecting person should be up at 4:05am sending emails.  Get some sleep. :)  It is OK to stay up late once in awhile, but force yourself to get to bed at a decent time (10) each day.  And try to get up early each day also (6 or 7), which will help you get much more out of your days. ;)
    • The myths about developers working all night on caffeine are false.  Yes, it happens sometimes, but it is rare.  Well rested developers learn more, write better code, and get more work done…period!
  • Track your time, and get in the habit of knowing what you did with each hour.  I personally use Hamster religiously, and find that I get much more done each day as a result. (I have it set to nag me every 15 minutes if I have not set an activity.)  If you are not using Linux as your desktop environment I am sure there are time trackers for the other operating systems, find one.
  • Certifications will not actually carry much value on your resume, so I would not make them a main focus.  Sure they do carry some value, but perhaps not in the way you desire.  Achieving a certification is a great personal accomplishment and will make you feel better about yourself, as well as give you bragging rights among developers.  (Most developers tell you they don’t care about certifications, but deep inside they are simply envious.)  While many certifications are not a true gauge of actual knowledge, they do represent a certain amount of skills.  However, I have found that most employers do not even notice certifications.  I am not saying don’t get them. What I am saying is to be aware the actual accomplishment may be different than you perceive.  When I started getting certifications it reinforced, in my own mind, that I knew what I was doing.  That gave me more confidence overall in my jobs, and was still a big “win”.  But do them in your spare time, not as a focus item.
  • Pick an IDE to use and learn it FULLY. I will not recommend one in this post, so explore and find one that fits how you want to work.  Then learn it COMPLETELY, and use it ALWAYS.
    • If an IDE causes you pain, don’t use it any more.  Pick another one.  This tool will be where you spend most of your day, so you should not be forced to spend your time debugging and fixing your IDE.  It should not crash regularly.  You should not dread opening it, instead you should look forward to launching it.
    • Use all parts of your chosen IDE. (FTP, version control, testing, coding, debugging, issue tracking, etc.)
    • Learn the keyboard shortcuts, they will save you time.
    • Just because an IDE is free does not mean it is good.  You should base purchases on value provided, not $$$.
  • Pick a plain text editor, and learn it well.  There are times you just need to do a quick edit, and opening an IDE, creating a project, etc. is just overkill for this.  Again, there are many of these available so I will not recommend a certain one.  Pick what you like best.
    • The best ones come with syntax highlighting.
    • There are some free ones, but don’t be afraid to pay a few bucks for a good one.
  • Pick a pet “full stack” PHP framework to learn, FULLY.  I recommend either Zend Framework 2, Symfony2, or CakePHP 2.* since these 3 are the most common.  But as with an IDE you should learn one COMPLETELY, and use it most of the time.  Each framework has its strengths and weaknesses, so choose one that works best for you.
    • Good frameworks have mechanisms in place where you can add plugins, modules, or helpers in case the framework does not fully support what your trying to do.  But stick to the framework as much as possible.
    • Feel free to write your own framework, but ignore the urge to use it for employers.  As professional developers we owe it to our employers to use more widely available frameworks.  It is just smart business.  It means businesses can find other developers easier, onboard them faster, and train the group more.
  • Always strive to make yourself replaceable.  If you are replaceable you are also promotable, and you can go on vacation pain free.
  • Learn to use GIT for source control, and use it for EVERY project you do no matter how small.  Sure there are other source control products out there, but currently GIT is the way to go.  All it takes is the command ‘git init’ in a directory and you are of and running.  No excuses!
  • Do things publicly so others can see.  Such as github, BitBucket, etc.  I recommend having code in some sort of public place for others to see how you code.  Don’t be shy.  I’ve had other developers provide feedback on code I posted on github, in a constructive way, and it helped me advance my skills.
  • Your LinkedIn profile is your best career tool as a developer.  Tweak it, adjust it, get everyone you can to contribute to it.  Add projects to it, etc. (See “Build your brand” below.)  Don’t connect with everyone who pops up, and be stingy with what recruiters you allow to connect with you.  If someone is not going to help your career in some way, they do not belong in your connections on LinkedIn.
  • Pick up small projects here and there that are NOT urgent, and you can take your time on.  These little projects will afford you a way to learn new things.
  • Get active in the PHP community.  I mean really active.  Sure, it’s OK to be a member of other communities as well, but the PHP community (world-wide as well as local) is what will really “do it” for you. (If you are going to make a career doing PHP.)
  • Give talks at local user groups, blog about your experiences, follow other blogs of good people (phpdeveloper.org is a good place to see activity of PHP community members blogs. Chris Cornutt does a great job at filtering out relevant posts and adds the best of them on this site.)
  • Get somewhat active on Twitter, join IRC channels, travel to a couple of conferences each year and get to know people “doing things”.  Then eventually start submitting talks to the conferences so you can go talk, and have your expenses covered to go to it.
  • Build your “brand”.  By this I mean to say YOU are the product.  Everything you say and do is your offering.  Your name is your “brand”.  Build the reputation carefully, and before you do anything ask yourself, “Will my customers like/buy this?”  If the answer is “yes”, then go for it.  If the answer is “no” re-evaluate.
  • If you are a woman, be careful.  While women are becoming a larger part of the tech community there are still many men who are not used to it yet.  They are jerks, and your feelings will get hurt sometimes in the process.  Learn to ignore them and focus on the good parts as you grow.  KNOW you are going to do great things, and work toward that progress.
  • Learn Linux via command line.  No need to go crazy with this one, but since most web servers are on Linux it is a good idea to have some knowledge in this area.  You should at very least know:
    • Basic vim commands to edit files on the server.
    • Be able to navigate the OS files and directories.
    • Be able to manipulate files on the server. (cut, copy, paste)
  • Spend some time each day on Stackoverflow.  Try to pick a problem someone posted and help them.  “Doing” is the best way to learn, and there are plenty of problems posted to Stackoverflow daily.  This is addictive, so manage your time and limit yourself.  But do it!

Of course there are many more tips, but I wanted to hit on some key items without writing a book on this blog post.  I hope you find this information helpful, and if you can think of some other hints and tips please feel free to share in the comments.

Good luck!!!

RSSSubscribe to my feed now.

About Me

Adam Culp (GeekyBoy)
Adam Culp (GeekyBoy) I am a South Florida PHP developer passionate about technology and post things here I find interesting, mostly so I remember, but also to help others. I'm a PHP 5.3 certified engineer and serve on the Zend Certification Advisory Board, and currently work as a Senior Professional Services Consultant with Zend Technologies. I am very active in the global and local PHP community, and organize the South Florida PHP Users Group (SoFloPHP) as well as the SunshinePHP Developer Conference in Miami. Read More >>
Zend PHP 5.3 Certified Zend Certification Advisory Board
profile for Adam Culp at Stack Overflow, Q&A for professional and enthusiast programmers