State Pattern in PHP

Written by Tully on December 4, 2011 Categories: PHP

The state pattern is a behavioural software design pattern. It is used to allow an object to changes it’s behaviour when it’s internal state changes. Below is an example of the state pattern in PHP. I have taken a stop watch with 2 buttons and implemented the code using the state pattern. The first button will be the start/stop for the timer. The second button will reset the timer back to 0. Each time you hit stop, the code will output the time since it started in milliseconds.

interface State {
    function press(StopWatchContext $context);
}

class StopState implements State {
    public function press(StopWatchContext $context) {
        $time = (microtime(TRUE) * 1000) - $context->getStartTime();
        printf("The stop watch is stopped. [Time] %d MS ", $time);;
        $context->setState($context->getStartState());
    }
}

class StartState implements State {
    public function press(StopWatchContext $context) {
        echo "The stop watch is running..";
        $context->setState($context->getStopState());
    }
}

class ResetState implements State {
    public function press(StopWatchContext $context) {
        echo "The stop watch is reset. ";
        $context->setStartTime(microtime(TRUE) * 1000);
        $context->setState($context->getStartState());
    }
}

class StopWatchContext {
    private $state;
    private $startTime;

    private $startState;
    private $stopState;
    private $resetState;

    public function __construct() {
        $this->setStartTime();
        $this->startState = new StartState();
        $this->stopState = new StopState();
        $this->resetState = new ResetState();
        $this->state = $this->startState;
    }

    public function setState(State $state) {
        $this->state = $state;
    }

    public function pressButton() {
        $this->state->press($this);
    }

    public function resetButton() {
        $this->setState(new ResetState());
        $this->pressButton();
    }

    public function getStartTime() {
        return $this->startTime;
    }

    public function setStartTime() {
        $this->startTime = microtime(TRUE) * 1000;
    }

    public function getStartState() {
        return $this->startState;
    }

    public function getStopState() {
        return $this->stopState;
    }

    public function getResetState() {
        return $this->resetState;
    }
}

$timer = new StopWatchContext();
$timer->pressButton(); //started
usleep(1200 * 1000); // sleeping 1.2 seconds
$timer->pressButton(); //stopped

$timer->pressButton(); //started
usleep(2000 * 1000); //sleeping 1.7 seconds (3200 MS)
$timer->pressButton();//stopped

$timer->resetButton(); //reset
$timer->pressButton();//started
sleep(2);//sleeping 2 seconds
$timer->pressButton(); //stopped
?>

:: Output: :
The stop watch is running..
The stop watch is stopped. [Time] 1200 MS
The stop watch is running..
The stop watch is stopped. [Time] 3200 MS
The stop watch is reset.
The stop watch is running..
The stop watch is stopped. [Time] 2000 MS

No Comments

Java RSS Reader Example

Written by Tully on November 7, 2011 Categories: JAVA

Today I was working with the DOM in Java and decided to write a simple RSS reader. The code below is an example of a Java RSS Reader. You just give it an instance of URL through the setURL assessor. Then call the writeFeed() method which outputs the title/description/link of each item in the feed.

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RSSReader {

   private static RSSReader instance = null;

   private URL rssURL;

   private RSSReader() {}

   public static RSSReader getInstance() {
      if (instance == null)
         instance = new RSSReader();
      return instance;
   }

   public void setURL(URL url) {
      rssURL = url;
   }

   public void writeFeed() {
      try {
         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = builder.parse(rssURL.openStream());

         NodeList items = doc.getElementsByTagName("item");

         for (int i = 0; i < items.getLength(); i++) {
            Element item = (Element)items.item(i);
            System.out.println(getValue(item, "title"));
            System.out.println(getValue(item, "description"));
            System.out.println(getValue(item, "link"));
            System.out.println();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public String getValue(Element parent, String nodeName) {
      return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
   }

   public static void main(String[] args) {
      try {
         RSSReader reader = RSSReader.getInstance();
         reader.setURL(new URL("http://www.tullyrankin.com/feed/rss"));
         reader.writeFeed();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
No Comments

PHPDOC For Vim

Written by Tully on October 19, 2011 Categories: General, Linux

My editor of choice for development has always been Vim. When I’m coding, I always leave PHPDOC comments for all classes, properties, and methods. I have been using a macro to include the basic PHPDOC comment header. This has worked fine for me so far. However, today I stumbled upon PHPDOC.vim plug-in. The plugin automatically creates the PHPDOC comment for you the second it sees you creating a class, method, or adding a class property.

To install just download the plugin from the following link:
http://markus.fischer.name/vim/phpdoc/phpdoc.vim

Place the file in your plug in directory for vim.
This can be found at ~/.vim/plugin

Once the plug in is installed, just open a PHP document and start creating a class, method, or property.

No Comments

Google Keywords API PHP

Written by Tully on May 10, 2011 Categories: PHP

I wrote a PHP script that connects to Google Ananlytics API and retreives your top keywords. Google Analytics has a scheduler that can send you emails of your keywords, but this script can be used to return various formats and then be sent to another program or logged for further processing.

The first couple lines have to do with the start-date and end-date of the statistics to return. Currently it’s set-up to run on a cron on the first of every month and send me a report of the last months keywords. This can easily be changed by modifying the startDate and endDate variables.

The Table ID which is the ID of your site in analytics, is set to retrieve it’s value as the first param given on the command line. So if your table id was 123456, you would call the script as “php googleAnalyticsFeed ga:123456″.

define("GoogleNameSpace", "http://schemas.google.com/analytics/2009");
define("GoogleClientLoginURL", "https://www.google.com/accounts/ClientLogin");
define("GoogleUserEmail", "YOUR_EMAIL_HERE");
define("GoogleUserPass", "YOUR_PASSWORD_HERE");
define("GoogleFeedURL", "https://www.google.com/analytics/feeds/data");

#(First/Last day of previous month)
$lastDayOfMonth = date('Y-m-d', strtotime("-1 second ".date('m').'/01/'.date('Y')));
$firstDayOfMonth = date('Y-m-01', strtotime("-1 second ".date('m').'/01/'.date('Y')));

$table = $argv[1];              # Table ID for Site
$startDate = $firstDayOfMonth;  #Start Date to Search
$endDate = $lastDayOfMonth;     # End Date to Search
$max = 100;                     # Max-results to display

#Auth String
$auth = googleAuth(GoogleUserEmail, GoogleUserPass);

#Get XML Keyword Data
$xml = getKeywords($auth, $table, $startDate, $endDate, $max);

#Loop Through Results and Display (Count - Keyword)
$dom = new DomDocument();
$dom->loadXML($xml);
$entries = $dom->getElementsByTagName('entry');

foreach ($entries as $entry) {
    $keyword = $entry->getElementsByTagNameNS(GoogleNameSpace, 'dimension')->item(0)->getAttribute('value');
    $total = $entry->getElementsByTagNameNS(GoogleNameSpace, 'metric')->item(0)->getAttribute('value');
    printf("%5d - %s\n", $total, $keyword);
}

#Get Google Auth
function googleAuth($email, $pass) {
    $ch = curl_init(GoogleClientLoginURL);
    $postParams = array(
                    "Email"         =>  $email,
                    "Passwd"        =>  $pass,
                    "accountType"   =>  "GOOGLE",
                    "source"        =>  "curl-dataFeed-v2",
                    "service"       =>  "analytics");
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postParams));
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    preg_match('/Auth=.*/', $data, $auth);
    return $auth[0];
}

#Get Google Keywords
function getKeywords($auth, $table, $startDate, $endDate, $max) {
    $getParams = array(
                    "ids"           =>  $table,
                    "start-date"    =>  $startDate,
                    "end-date"      =>  $endDate,
                    "dimensions"    =>  "ga:keyword",
                    "metrics"       =>  "ga:visits",
                    "sort"          =>  "-ga:visits",
                    "max-results"   =>  $max,
                    "prettyprint"   =>  "false");
    $ch = curl_init(GoogleFeedURL.'?'.http_build_query($getParams));
    $header[0] = "Authorization: GoogleLogin $auth";
    $header[1] = "GData-Version: 2";

    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    return $data;
}
No Comments

keywords from apache logs

Written by Tully on March 4, 2011 Categories: Apache, Linux, PHP

I wrote a quick 1 liner last week to get the Google keywords/phrases people were searching to get to my site from the apache logs. The script parses the apache logs and searches for users coming from Google. It then parses each line and outputs the urldecoded version with the number of hits for each keyword/phrase.

cat access_log access_ssl_log | grep --line-buffered 'www.google.com' | egrep --line-buffered -o 'q=.*\&' | tr -d 'q=' | cut -d\& -f1 | egrep --line-buffered '[a-zA-Z0-9]{1}\r' | php -R 'echo urldecode($argn) . "\n";' | sed -e 's/^[ \t]*//g' | sort | uniq -c | sort -n

–Sample Output–

2 java program to count freuency of letters
2 letter freuency in java
2 myslimport csv
2 php bubble sort
2 rand with vectors c++
2 which logical unit of the computer retains information
2 zend_form_element select
4 google weather api
4 php developer resume
4 selection sort example
5 six logical units of a computer

No Comments

MOV Files on PS3

Written by Tully on February 20, 2011 Categories: Linux

This last weekend I bought a new HD ZI8 camcorder. I wanted to play the movies files on my PS3. I run a media server using ushare on my Linux box. The ZI8 camcorder saves the recorded videos in .mov format. These files would not play on my PS3. After some research, I found a solution using ffmpeg. The command I use to convert these files to work on the PS3 using my media server is below.

ffmpeg -i original_file.mov -acodec mp2 -ar 32000 -vcodec mpeg1video -qscale 14 new_file.mpg
No Comments

Zend Form Element Select Helper

Written by Tully on January 26, 2011 Categories: PHP Tags: , ,

Today I wrote a small helper that will transform an array to work with Zend Form Element Select. Zend Form Element Select uses the key of an array as the value, and the value as the key. I’m not sure why Zend did this, but I wrote a small helper class that can be used to re-arrange an array to work properly with the Zend Element Select. To use the class, just give it the array, the key you would like to use as the name, and the key you’d like to use for the value.

class Helpers_FormHelper {

    public static function createNewArrayWithGivenKeyValuePairs(Array $data, $key, $value) {
        $transformedData = array();
        foreach ($data as $row) {
                    $transformedData[$row[$value]] = $row[$key];
        }
        return $transformedData;
    }
}

Example:

Helpers_FormHelper::createNewArrayWithGivenKeyValuePairs($colors, 'name', 'id');

Before

array
  0 =>
    array
      'id' => string '1' (length=1)
      'name' => string 'Red' (length=3)
  1 =>
    array
      'id' => string '2' (length=1)
      'name' => string 'Blue' (length=4)
  2 =>
    array
      'id' => string '3' (length=1)
      'name' => string 'Yellow' (length=6)
  3 =>
    array
      'id' => string '4' (length=1)
      'name' => string 'Orange' (length=6)
  4 =>
    array
      'id' => string '5' (length=1)
      'name' => string 'Green' (length=5)

After

array
  1 => string 'Red' (length=8)
  2 => string 'Blue' (length=7)
  3 => string 'Yellow' (length=7)
  4 => string 'Orange' (length=6)
  5 => string 'Green' (length=8)
No Comments

MySQL Distance Between Two Locations

Written by Tully on January 7, 2011 Categories: MySQL

Problem:
I need to return table rows within a set amount of miles from given latitude/longitude.

Solution:
1. Create a MySQL function that takes the coordinates of point A and point B and returns the distance in miles.
2. Write a MySQL select statement that uses the newly created function to return rows where distance is less then X miles.

Calculate distance between two points on a globe.

DELIMITER //
CREATE FUNCTION `GetDistance`(
 lat1  numeric (9,6),
 lon1  numeric (9,6),
 lat2  numeric (9,6),
 lon2  numeric (9,6)
) RETURNS decimal(10,5)
    READS SQL DATA
BEGIN
  DECLARE  x  decimal (20,10);
  DECLARE  pi  decimal (21,20);
  SET  pi = 3.14159265358979323846;
  SET  x = sin( lat1 * pi/180 ) * sin( lat2 * pi/180  ) + cos(
 lat1 *pi/180 ) * cos( lat2 * pi/180 ) * cos(  abs( (lon2 * pi/180) -
 (lon1 *pi/180) ) );
  SET  x = acos( x );
  RETURN  ( 1.852 * 60.0 * ((x/pi)*180) ) / 1.609344;
END //
DELIMITER ;

Example:

mysql> select City, GetDistance(Latitude, Longitude, (SELECT Latitude from hotels where City = 'Pasadena' and StateProvince = 'CA' limit 1),(SELECT Longitude from hotels where City = 'Pasadena' and StateProvince = 'CA' limit 1)) as Distance from hotels where StateProvince = 'CA' group by City, StateProvince having Distance < 10 order by Distance DESC;
+----------------+----------+
| City           | Distance |
+----------------+----------+
| Duarte         |  9.83023 |
| Monrovia       |  9.03029 |
| El Monte       |  8.99051 |
| South El Monte |  8.80477 |
| Rosemead       |  8.09559 |
| Arcadia        |  6.91626 |
| Glendale       |  6.34357 |
| Monterey Park  |  5.67806 |
| San Gabriel    |  4.90842 |
| Alhambra       |  3.37174 |
| Pasadena       |  0.00000 |
+----------------+----------+
11 rows in set, 9240 warnings (0.36 sec)

Note: The above will return only unique cities that are within 10 miles of Pasadena, CA. To bring back all the matched rows just remove the "group by City, StateProvince".

1 Comment

Website Domain Checker

Written by Tully on November 3, 2010 Categories: PHP

Today I wanted to check a few domains and see if they were available or already taken. I figured the best way to do this would be to check if there was any DNS records for the requested domains.  I did a quick look at the functions available to me in PHP, and came across the function checkdnsrr. The checkdnsrr function can be used to check a domain for any type of DNS records. So now that I found the function to use, I wrote a simple 6 line PHP script I can use from the command line. The script takes 1 parameter, the domain name.

To use the script from the command line, you would type ./domainChecker tullyrankin.com where “tullyrankin.com” would be replaced with whatever domain you are checking. If the domain has no DNS records, the output will be “Domain is available!”. If the domain has any DNS records, the response will be “Domain is already taken”. The code for this script is below.

#!/usr/bin/php -f
<?php
if ($argc < 2)
	die("Usage: php ".basename($argv[0])." [domain]\n");

if (checkdnsrr($argv[1], "ANY"))
	echo "Domain is already taken\n";
else
	echo "Domain is available!\n";
No Comments

Qmail Queue

Written by Tully on October 27, 2010 Categories: Linux

Today I wanted to check how many emails were in the queue for Qmail. I wanted to display where all the outgoing emails were getting sent, and get a count of how many are going to that email address. To complete this task, I put together a quick 1 liner that loops through the queued emails, greps the “to” field, and then sorts and counts the results. The line of bash I wrote to do this is shown below.

for i in `find /var/qmail/queue/mess -type f`;do cat $i | egrep -o ‘To:.*[com,org,net]‘ | awk ‘{print $2}’ >> /tmp/emailTmp;done; cat /tmp/emailTmp | sort | uniq -c | sort -n;rm -f /tmp/emailTmp;

No Comments