Posts Tagged ‘PHP’

Aptana Cloud - Hands On

Sunday, June 1st, 2008

I received beta access today to Aptana cloud, something I’d previously mentioned. Aptana cloud is targeted at rapid development, in particular web applications that need to scale rapidly (think Facebook applications etc.)

Aptana cloud plugs nicely into the Aptana IDE as you would expect and as an extra treat it comes with a beta version of the new PHP editor and a pre-release version of Jaxer 1.0. This post will discuss some of the key features and my experience of trying out for the first time…

The only obvious change after the install if you can see a cloud control button next the Jaxer button at the top of the IDE.

Showing IDE changes

After creating a project it then is automatically available in the cloud options.

When you click on the project under the cloud menu you are taken through a (very easy to use) wizard for configuration. This runs your through a few steps, setting up a site name, picking a payment plan (the beta is free), payment details and so on. Most of these screens are fairly standard, however the service selection is quite interesting. I imagine these prices are not final, so just take them with a pinch of salt.

The payment scheme seems to be quite flexible and we can see a large number of services that are included, PHP being the main server side language at the moment, with Aptana Jaxer still being a beta… (Ruby of Rails is on the ‘coming soon’ list). The prices range from the cheapest being 256 MB ram and 5 GB hard disc for $0.99 a day, up to 2 GB of ram and 25 GB hard disc for $8.22 a day. Seems fairly reasonably priced.

After set-up is finished, it phones home and does some magic. Shortly after displaying the following screen;

And sure enough, browse on over to http://mycloud.aptanacloud.com/ to see the following screen.

After that, you’re set up. You can go ahead and develop the application as normal. When you next go into the project in the cloud menu it provides you with a simple synchronisation process for uploading new and changed files. Going to http://mycloud.aptanacloud.com/index.php shows the output of a phpinfo. Currently running 5.2.5, thankfully nice and up to date! Doesn’t look like you are able to use pear however… that is shame.

This has been a very quick into, just to show exactly how easy it is to get started with a new project, there is a whole host of facilities that have been integrated that I’ve not covered. See the following screenshot for a quick look-see. Database management, SVN, back-ups and more all now easily managed from one IDE.

The first questions that then spring to mind are, I don’t see how to develop with two versions for testing etc. As we don’t want to be testing under a live environment do we! I’m assuming there is also a way for developing with SVN and having multiple developers working on the same projects.

All in all, I’m quite impressed and look forward to seeing this develop further.

I’ve liked the idea of Jaxer since I first heard about it, now with Aptana cloud I’ve got some online hosting where I can try out a few things. Expect some Jaxer posts coming soon! :)

p.s. I didn’t notice any of the new PHP features…

Lambda Functions - Does your language support it?

Sunday, May 18th, 2008

What are Lambda functions? Basically lambdas are functions that can be treated as anonymous or as objects. It depends on the language that is being used. They are very useful and at the core of the Functional Programming paradigm. So what languages can you create lambas in? Here is a few;

JavaScript

  1. var foo = function(x, y){
  2.     return x + y;
  3. }
  4.  
  5. alert(foo(2, 4));

PHP

  1. $foo = create_function(‘$x,$y’, ‘return $x + $y;’);
  2.  
  3. echo $foo(2,4);

Python

  1. foo = lambda x, y: x + y
  2.  
  3. print foo(2,4)

These are of course very simple examples and don’t show the full potential. I’ve been a fan of lambdas for a while now and wanted to see what languages supported them. If you know of others you want me to add, post them in the comments. I know many other languages can, I just posted up the languages I’m familiar with.

I think out of all the examples I’ve looked at so far I like the style of them most in either JavaScript of Python.

Analysing PHP Objects and Classes

Monday, May 5th, 2008

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.

Lazy Loading in PHP with __autoload

Saturday, April 26th, 2008

__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();

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

Saturday, April 19th, 2008

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();”.