Archive for the 'Programming' Category

Apr 24 2008

Some More PHP Abilities You May Not Know About

Published by David Jeffries under Programming

Because my first PHP abilities you may not know about post seemed to be useful, here is part 2: some more PHP abilities you may not know about. If you want to learn about ternary operators, calling functions from strings, or variable variables, check out the previous post. Read on to lean about some other things that you can do with PHP.

Modify variable by reference

<?php
$test = 'new';
modify($test);
echo $test; //prints new variable;
function modify(&$variable){
  $variable .= ' variable';
}
?>

By using the "&" symbol before the parameter in the function, you pass a reference of the variable to the function.

This saves you from having to say $david = duplicate($david), which can be nice in some situations.

Point a variable to another
This is similar to the example above. You are able to set a variable to reference another by using "=&", an example below:

<?php
$david = 'i am david';
$joe =& $david;
$joe = 'i am joe';
echo $david; //prints i am joe.
?>

In this example, any change to $joe will result in a change to $david, because $joe is essentially $david.

Default parameter value
I'm amazed at how many people don't know about this. When setting up a function's parameters you are able to specify a default value if the parameter is not passed.

<?php
func('test');
function func($foo, $bar = 'value'){
  echo $foo . $bar; //we didnt pass $bar, so the result will be 'testvalue'
}
?>

The parameter $bar is not passed to the function, so the default value of 'value' is used instead.

Create variable from a string
I explained variable variables in the PHP post previous to this one, but did you know that you can combine two (or more) strings then treat the result as a variable?

<?php
 $var = 'my';
 $bar = 'var';
 $myvar = 'testing';
 echo ${$var . $bar}; //prints the $myvar variable (testing)
?>

Man, PHP is crazy.

4 responses so far

Apr 04 2008

Some PHP Abilities You May Not Know About

Published by David Jeffries under Programming

Throughout my time programming PHP I've come across a few interesting things about the language. Coming from a primarily Java background, it seems quite strange to be able to do some of these things so easily.

Having said that, here are a few things with PHP that I've found interesting, and hopefully some of these things you've never heard about.

Call a PHP function from a string
PHP is an interesting language. To do the following in Java, it would be much more complex - around 5-10 lines of code. In PHP however, it is quite simple to call a function dynamically from a string.

<?php
  $call_this = "phpinfo";
  $call_this();
?>

You can even pass arguments to the variable like you were calling the function directly - it's pretty cool. Here's a practical example: Consider a function that accepts either a jpeg or png image file and resizes it (this is only a subset of the function).

<?php
  switch($imgType){
    case "jpeg":
      $create = "imagecreatefromjpeg";
      break;
    case "png":
      $create = "imagecreatefrompng";
      break;
  }
  $create($filename); //this will create either a jpeg or png
?>

This makes the code considerably cleaner by dynamically setting the function that will be called.

Ternary operator
This is a quick way to write an IF statement, without the structure and braces. The way it works is like a normal if statement, you pass it true or false (in the following case, ($test == true) == true), and then the ? means then and the : means else. It's pretty simple, and is nice to use for simple one liners, in cases like the following example.

<?php
  $test = true;
  echo $test == true ? "is true!" : "not true";
  //will print "is true!";
?>

A little bit nicer than

<?php
  $test = true;
  if($test == true){
    echo "is true!";
  }else{
    echo "not true";
  }
?>

Easily echo a variable
I don't really like this method, I prefer to just use <?php echo "string"; ?>, but maybe this way is faster - I'm not sure. Either way, pretty much all it does is echo the variable that is after the equals sign.

<?php
  $val = 50;
?>
<!-- some HTML or whatever -->
<?= $val ?>

Variable variables
Variable variables are variables that can be dynamically set with strings. In the following code, you will notice that we set the variable $val to "hello" and then set the variable variable (the string that $val holds ("hello")) to the string "variable variable". When we echo $hello, the text "variable variable" will be printed.

<?php
  $val = 'hello';
  $$val = 'variable variable';
  //the string that is set in $val is now the name of our variable.
  echo $hello; //will print 'variable variable'
?>

Calling a variable variable function
Expanding on the variable variables, you could actually combine that example with calling a PHP function by a string and do this:

<?php
  $val = 'show_info';
  $$val = 'phpinfo';
  echo $show_info(); //will echo phpinfo()
?>

Here, "show_info" is the name of the variable, and its pointing to "phpinfo" Writing $show_info() calls the function that the variable variable is pointing to. It's kind of confusing and would probably only be used in some really complex code, but it does work.

38 responses so far

Mar 30 2008

Firefox textbox blinking problem

Published by David Jeffries under Programming

Today I encountered a weird bug in Firefox where the cursor was not showing up and blinking in a text box that I had on the web page I was working on. This was really annoying because it was hard to tell which text box was focused on and which one was being typed into.

It turns out that the problem was with a text box inside a div that had its position style attribute set to absolute. After playing around I found out that wrapping the text box in a div and setting the overflow: auto, fixed the problem. Actually searching for and reading the official Firefox bug report also confirmed that this was the way to fix it.

FireFox bug:

<div style="position:absolute;">
  <input type="text">
</div>
<!-- this will cause the cursor to not show up and blink-->

Fixing the bug:

<div style="position:absolute;">
  <div style="overflow:auto;">
    <input type="text">
  </div>
</div>
<!-- this will show the cursor blinking in the textbox -->

Hope that saves you some time!

2 responses so far

Mar 09 2008

The Singleton is My Favourite Design Pattern

Published by David Jeffries under Programming

I find it amazing the number of people that have studied computer science who do not know what the singleton design pattern is. It's so important when designing software I don't think I could create efficient code without it.

What it is

A singleton is a design pattern that forces the creation of only one instance of a class. That is, once a class has been instantiated, the running instance is referenced, not a new one.

How it works

The singleton is one of the rare times a private constructor is used. The reason for this is mentioned above, we only want one instance of the object so we don't allow access to the constructor. Instead, we will use a public static method to get the instance. I'll give the code here in PHP, it's actually quite simple.

Implementation

<?php
class MyClass {
 
  private static $instance;
 
  private function __construct(){
  }
 
  public static function getInstance(){
    if(self::$instance == null){
      self::$instance = new self;
    }
    return self::$instance;
  }
 
  public function method1(){
    //do some stuff
  }
 
  public function method2(){
    //do some more stuff
  }
}
?>

That is a full singleton implementation in PHP. Now, when you want to get the current object, it would look something like this:

<?php
$obj = MyClass::getInstance();
 
$obj->method1();
?>

The whole thing is very simple. All getInstance() does is creates a new instance of its own class if the variable $instance is null (meaning the class has not been instantiated yet), and if $instance is not null, it is just returned (we do not want to create another one!).

Why I love it

I've seen PHP scripts that totally do not know how to deal with database classes. Either they open and close connections as needed, or open connections when they're not needed and leave them open throughout the pages execution. Both are, in my opinion, not correct.

A database class should never have more than one instance of itself open. Only one instance (one connection) to the database should be made which ensures a minimal number of connections. You can see how implementing a singleton design pattern into a database class can be very beneficial.

You can see an example at the projects area that demonstrates the singleton with a database.

No responses yet

Feb 08 2008

Google Geocode Request Limits

Published by David Jeffries under Programming

Google maps API is pretty cool, well written piece of software. Everything is pretty much perfect except for one thing. Geocoding. According to the signup page, you can geocode 15,000 addresses per day per API key. Here's the exact text:

There is a limit of 15,000 geocode requests per day per Maps API key. If you go over this 24-hour limit, the Maps API geocoder may stop working for you temporarily. If you continue to abuse this limit, your access to the Maps API geocoder may be blocked permanently.

So anyways, after designing my software to die at 14,500 requests, and then farm it out to a different server with a different API key, I found out that they made a change, and the limit is now 15,000 requests per IP. Well that's nice, but that means that most of the geocoding should be done on the client side. This is great because there's no way a client will ever hit 15 thousand, (at least not in this current project), but bad because it requires a pretty big rewrite of code.

After rewriting my code to do most of the geocoding on the client side I found out that the 15,000 requests per day per API key isn't actually 15k/day. It's more like 625 requests per hour - 10.4 per minute - or 1.7 requests per second. Make any more than that and you get throttled.

From some testing I did I found that you can make about 12 requests in a row before you start to get throttled. More than that and there will be a ~4-5 second delay until you can make another ~12 requests. It's not really nice to do this - so here is my resulting code:

var i=0;
//geoSave holds n addresses that need geocoding
while(i < geoSave.length){
  setTimeout("findAddress('"+geoSave[i]+"',2000*i);
  i++
}
 
function findAddress(address){
  geocoder.getLocations(address, function(response){
    //do stuff with the response
  });
}

So there it is, a simple 2 second delay and the client is able to make unlimited geocode requests.

One response so far