Galactocracy

May 11th, 2008 by Dougal

It’s been a busy week so I don’t have much time to write. Therefore, I’m just going to do a quick plug of a Facebook application I made with some friends. Don’t worry – it’s not one of those applications that’s going to be annoying and force you do invite people or ask you silly questions in an attempt to tell you who you really are.

Galactocracy rather is a turn based strategy game, similar in some ways to the board game risk. It is rather set in space.

So anyway, there isn’t much point in me telling you too much about it. I think the game sells itself when you give it a shot.

So why not head over to http://apps.facebook.com/galactocracy/ and try it out.

I’ll be waiting for you at the other side of the battlefield to fight it out for supreme control over the universe ;)

P.S. Next I’m going to be covering something JavaScript or Python. Not sure what yet, maybe something a little bit silly just for fun.

Analysing PHP Objects and Classes

May 5th, 2008 by Dougal

Analysing PHP Objects and Classes

Due to the dynamic nature of PHP as a programming language it can be quite difficult to determine what is happening. This is then even harder if you don’t have access to debugging tools such as those in Zend Studio.

How can you view an object?

  1. header("Content-Type: text/plain");
  2.  
  3. class Foo {
  4.  
  5.     private $name = "Fred";
  6.     private $age = 30;
  7.    
  8.     public function __construct(){}
  9.    
  10.     public function bar(){
  11.         echo "Hello World";
  12.     }
  13.  
  14. }
  15.  
  16. $myFoo = new Foo();
  17.  
  18. print_r($myFoo);
  19. $content = print_r($myFoo, true);
  20.  
  21. var_dump($myFoo);

These all are all ways of outputting objects and can prove to be invaluable. I find using print_r particularly useful for logging data errors to a file or database that you can analyse later.

  1. Foo Object
  2. (
  3.     [name:private] => Fred
  4.     [age:private] => 30
  5. )
  6. object(Foo)#1 (2) {
  7.     ["name:private"]=>
  8.         string(4) "Fred"
  9.     ["age:private"]=>
  10.         int(30)
  11. }

Reflection

“In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.” Wikipedia (http://en.wikipedia.org/wiki/Reflection_%28computer_science%29) .

Ok, so what does that mean? Basically, Reflection is a way of programmatically dealing with classes. So you can find out information about them. Including the properties and values.

What’s inside a class?

As of PHP 5 there is now a very powerful reflection library available. This includes a number of very useful objects. The two we will be focusing on are ReflectionClass and Reflection. Here is the one liner that can do it all….

  1. Reflection::export(new ReflectionClass(‘SimpleXMLElement’));

To set up a simple test case for this I used;

  1. header("Content-Type: text/plain");
  2.  
  3. Reflection::export(new ReflectionClass(‘SimpleXMLElement’));

This creates quite a bit of output;

  1. Class [   class SimpleXMLElement implements Traversable ] {
  2.    
  3.     - Constants [0] {
  4.     }
  5.    
  6.     - Static properties [0] {
  7.     }
  8.    
  9.     - Static methods [0] {
  10.     }
  11.    
  12.     - Properties [0] {
  13.     }
  14.    
  15.     - Methods [12] {
  16.         Method [  final public method __construct ] {
  17.         }
  18.    
  19.         Method [  public method asXML ] {
  20.         }
  21.    
  22.         Method [  public method saveXML ] {
  23.         }
  24.        
  25.         Method [  public method xpath ] {
  26.         }
  27.        
  28.         Method [  public method registerXPathNamespace ] {
  29.         }
  30.        
  31.         Method [  public method attributes ] {
  32.         }
  33.        
  34.         Method [  public method children ] {
  35.         }
  36.        
  37.         Method [  public method getNamespaces ] {
  38.         }
  39.        
  40.         Method [  public method getDocNamespaces ] {
  41.         }
  42.        
  43.         Method [  public method getName ] {
  44.         }
  45.        
  46.         Method [  public method addChild ] {
  47.         }
  48.        
  49.         Method [  public method addAttribute ] {
  50.         }
  51.     }
  52. }

So what does it all mean? It’s quite a bit to read through. So starting from the top;

Line one shows us the definition of the class but it’s got a few things more than we are used to seeing. The first being <internal:SimpleXML>. This means that it exists internally, as in its implemented in C code rather than native PHP. SimpleXML is the name of the package that the class is in. Then on this line we can see the name of the class, any classes it extends and any interfaces it implements.
The next step as we go in we can see its divided into various different sections. These are fairly self explanatory so I won’t go into too much detail. Again, for each method you can see its implemented internally and is in the SimpleXML package.

  1. header("Content-Type: text/plain");
  2.  
  3. class Test{
  4.  
  5.     private function hello(){
  6.    
  7.     }
  8.  
  9. }
  10.  
  11. Reflection::export(new ReflectionClass(‘Test’));

The above example is the same as before but with a simple class made up for it. The output follows

  1. Class [  class Test ] {
  2. @@ C:\Important\www\BlogExamples\5. Analysing PHP Objects and Classes\reflection.php 6-12
  3.    
  4.     - Constants [0] {
  5.     }
  6.    
  7.     - Static properties [0] {
  8.     }
  9.    
  10.     - Static methods [0] {
  11.     }
  12.    
  13.     - Properties [0] {
  14.     }
  15.    
  16.     - Methods [1] {
  17.         Method [  private method hello ] {
  18.             @@ C:\Important\www\BlogExamples\5. Analysing PHP Objects and Classes\reflection.php 8 - 10
  19.         }
  20.     }
  21. }

This has a very similar result to the output on the SimpleXMLElement in terms of the content. The key differences are, internal is now replaced by ‘user’ and rather than have a package name there is a special value represented by ‘@@’ that shows where the code resides. It’s nice to see it even shows the line numbers for the class and the methods.

So…

What is this all useful for? Generally on the whole PHP’s documentation is very good. However, it doesn’t always show the differences between versions of PHP clearly, some of the newer features remain less well documented or perhaps the documentation doesn’t have good coverage in your native language.

Either way, will this ever replace reading the source code and documentation? Well, probably not. However for internal code thats written in C unless you want to read that it makes for quite a handy reference.

Aptana Cloud

April 29th, 2008 by Dougal

From the makers of the Aptana IDE and Jaxer. We have another interesting product, Aptana Cloud. There is plenty of coverage out there already so I wont attempt to compete. Here are some of the best;

This looks very interesting to me and I’m a big supporter of all things JavaScript (note you don’t have to use JavaScript for Aptana Cloud).

Lazy Loading in PHP with __autoload

April 26th, 2008 by Dougal

__autoload is one of the magic methods added to PHP in version 5. It creates a very easy way for you to manage all your different class files. Actually, with __autoload you don’t need to manage them.

Often you will see in PHP projects files that include the other files needed for that page. You can then end up with a while bunch of require_once calls and so on. This can be quite tedious to maintain and you may not always need all the files.

When you create a new instance of a class PHP checks for it and if it can’t be found the __autoload method is called. It’s passed in one parameter, the name of the class.

  1. function __autoload($class){
  2.  
  3.     require "/path/to/class/files/$class.php";
  4.  
  5. }
  6.  
  7. $x = new Foo();

Above is a simple example of autoload in action. When a new Foo is created the autoload function requires /path/to/class/files/Foo.php. So with a simple naming convention each class in its own file where the file name is the name of the class (similar to Java) you can easily include files.

This example can be taken slightly further to manage hierarchies of classes…

  1. function __autoload($class){
  2.  
  3.     $class = str_replace(‘_’, ‘/’, $class);
  4.     $path = "/path/to/class/files/$class.php";
  5.     require $path;
  6.  
  7. }
  8.  
  9. $x = new Foo_Bar();

The above code simply replaces all underscores ( _ ) with forward slashes ( / ) before requiring the class. The naming convention changes slightly for this, the class name Foo_Bar would be found in following path: /path/to/class/files/Foo/Bar.php.

  1. function __autoload($class){
  2.  
  3.     $class = str_replace(‘_’, ‘/’, $class);
  4.     $path = "/path/to/class/files/$class.php";
  5.  
  6.     if(file_exists($path)){
  7.         require $path;
  8.     } else {
  9.         // Error handling here, log it etc.
  10.         // Exceptions cannot be thrown.
  11.     }
  12.  
  13. }
  14.  
  15. $x = new Foo_Bar_Fail();
  16.  

The final example shows the same code again with some optional error checking. It allows you to log errors and so on. However, exceptions cannot be thrown by __autoload unless its being called by class_exists. Since this function calls autoload to look for classes. When trying to throw exceptions, PHP runs into a fatal error before its thrown due to the order or __autload. This means a fatal error will be triggered as the class can’t be found and the exception will vanish.

Following up to this post I plan to do one of spl_autoload soon. With this you can have PHP automatically run its own autoload procedure on include paths. For further reading on this follow the link below. The documentation is a little sparse however.

Enjoy, lazy loading!

Useful links;

Design Patterns: Singleton

April 19th, 2008 by Dougal

The singleton design pattern is a way of enforcing only one instance of an object. This is achieved by making 3 fairly simple steps to a class. Firstly making the constructor private, creating a static member variable that will contain the instance and then creating a static method for accessing the instance.

So, In PHP it would be;

  1. class Foo {
  2.    
  3.     private static $instance = null;
  4.    
  5.     private function __construct(){
  6.         // Private, so can’t be accessed from outside
  7.     }
  8.    
  9.     private static function getInstance(){
  10.         if($this->instance == null) {
  11.             $this->instance = new Foo();
  12.         }
  13.         return $this->instance;
  14.     }
  15.    
  16.     public function bar(){
  17.         echo "I am one, I am a singleton!";
  18.     }
  19.    
  20. }
  21.  
  22. // Example usage
  23. $foo = Foo::getInstance();
  24. $foo->bar();
  25. // or the chaining method
  26. Foo::getInstance()->bar();
  27. // Note this will not work
  28. $myfoo = new Foo();

Why are singletons good? It’s almost like a global object right? What is good about a singleton as opposed to a concrete class? A concrete class has more flexibility as you can create multiple instances and then each instance can of course be different. However, what if you only ever want one instance of an object and ensure you don’t accidentally make another instance (or another developer doesn’t). You could use globals but they need to be managed somehow and people can still make mistakes and forget things.

The most common example is a database class, you might want to make sure that you only open one connection to the database. Creating multiple instances of database class could (depending how you programmed it) open multiple database connections and be inefficient.

The singleton can also be useful if an object that is used infrequently across a website. It can provide you easy access to it without having to worry about passing the object around. In the above code, you can access that object instance with this snippet of code “Foo::getInstance();”.

New Blog

April 12th, 2008 by Dougal

So, this is my first post. Just a quick introduction to this blog and what you can expect to find here.

Interestingly I’ve always has mixed feelings about blogs. I’ve always been fairly anti personal blogs. They seem to be generally a waste of time, besides, who wants to know what I ate for breakfast? (I skipped breakfast today by the way). So instead of that, I’m going to attempt to make a blog based on my experiences as a developer.

Basically, this blog is going to be strongly focused around programming. I’ll be covering a number of languages and platforms. Most likely this will depend on what I’m using in my studies or in the workplace at that time.

I have a wide range of interests when it comes to programming, including JavaScript, PHP, .NET and everything in between. So you can expect coverage of all these topics in a fairly random order. Depending what takes my interest first!

I’m going to aim to try and do a post weekly, all going well and I’m not on holiday or something.

Some of the following are topic idea’s that I currently have;

  • Design Patterns
  • Cover some of the less well documented PHP features. Such as the magic methods or Soap (SoapClient, SoapServer etc.).
  • Talking about new technologies such as Silverlight or Jaxer.
  • Having fun with JavaScript – like animations and pyhsics.

I’m also open open to suggestions of topics. Feel free to send them in.

Edit;

On a side note, the design and layout of this page is going to be a work in progress. It’s not really the main focus of this website