The evolution of how I code common objects

November 20, 2011

I always try to make my code as small as possible, as long as it is understandable to a degree – and simple code is for me often that. DRY is a good rule, sometimes hard to figure out how to not repeat myself, but sometimes I discover good techniques.

In my early programming days, in the case of objects, I always made every object like this:

class Student {
   private $name;
   private $address;
   
   public function __construct($name, $address){
      $this->setName($name);
      $this->setAddress($address);
   }
   
   public function setName($name){
      $this->name = $name;
   }
   public function getName(){
      return $this->name;
   }
   public function setAddress($address){
      $this->address = $address;
   }
   public function getAddress(){
      return $this->address;
   }
}

$student = new Student();
$student->SetName('John');
echo $student->GetName();

Then I discovered that I don’t need to have a getter and setter for every property, I wanted to get rid of them and it could be done like this:

class Student {
   private $name;
   private $address;
   
   public function __construct($name, $address){
      $this->Name($name);
      $this->Address($address);
   }
   
   public function Name($name=null){
      if($name===null){
         return $this->name;
      }
      $this->name = $name;
   }
   public function Address($address=null){
      if($address===null){
         return $this->address;
      }
      $this->address = $address;
   }
}

$student = new Student();
$student->Name('John');
echo $student->Name();

Notice, that the use of null here do that you cannot use null as a value to a property, but the properties are null if you get them and they are not set. Anyways, this became all too much code when you got like 10+ objects with 10+ properties each, repeating the syntax for every property. So I turned into something like this:

class Student {
   private $name;
   private $address;
   
   public function __construct($name, $address){
      $this->Name($name);
      $this->Address($address);
   }
   
   public function set_get($property, $value=null){
      if($value===null){
         return $this->$property;
      }
      $this->$property = $value;
   }
   
   public function Name($name=null){
      $this->set_get('name', $name);
   }
   public function Address($address=null){
      $this->set_get('address', $address);
   }
}

$student = new Student();
$student->Name('John');
echo $student->Name();

But why do one have to go through a method for each property? we can easily get rid of all that by simply using the set & get and then use an array as the property holder.

class Student {
   private $properties = array();
   
   public function set($property, $value){
      $this->properties[$property] = $value;
   }
   public function get($property){
      return (isset($this->properties[$property])
              ?$this->properties[$property]
              :false;
   }
}

$student = new Student();
$student->set('name', 'John');
echo $student->get('name');

Less code, easy to maintain, only drawback is to make som additional actions in every set/get, something that I seldom do anyways. Also, every set/get does not turn up in the list of methods that Eclipse/NetBeans find. If needed those can get own methods. Still, this is all too much for every single class when the code is the same on many – it is better to extend a class that has that code:

class Master {
   private $properties = array();
      
   public function set($property, $value){
      $this->properties[$property] = $value;
   }
   public function get($property){
      return (isset($this->properties[$property])
              ?$this->properties[$property]
              :false;
   }
}

class Student extends Master {}

$student = new Student();
$student->set('name', 'John');
echo $student->get('name');

This way every object get the same functionality and only one line is required to make one object. But why not go even further. Both in how values are set and get, and how classes are created. PHP has this magic function called __autoload(), and including this inside it make it so that any class can be created even if it does not exist:

class Master {
   private $properties = array();
   public function val($prop, $val=null){
      if($val===null){
         return (isset($this->properties[$prop])
                 ?$this->properties[$prop]
                 :false);
      } 
      $this->properties[$prop] = $val;
   }
}
function __autoload($class) {
   eval('class '.$class.' extends Master {}');
}

$student = new Student();
$student->val('name', 'John');
echo $student->val('name');

Now I can create any object with any name on the fly. It is like a stdClass, but with functionality and not anonymous. But isn’t the use of eval like… evil? Well, typically it should be avoided, especially if the content you put in is user-generated from a form. If this is the case, you have to strip away everything from the class name that does not belong in a class name before you evaluate it. Don’t do it if you don’t know what you are doing. There are some more stuff I want to do with this:

class Master {
   private $props = array();
   public function val($prop, $val=null){
      if($val===null){
         return (isset($this->props[$prop])
                 ?$this->props[$prop]
                 :false);
      } 
      $this->props[$prop] = $val;
      return $this;
   }
}
function __autoload($class) {
   eval('class '.$class.' extends Master {}');
}
function obj($name){
   return new $name();
}

echo obj('Student')->val('name', 'John')->val('name');

Like that! Now I don’t have to initiate a new object every time I want to make one, and I added chaining so that every value can be set more fluid. All of the code above is only a starting point, and need additional stuff to make them robust, secure, and stuff like that. I hope you get the idea, because in many projects it is unnecessary and dull to create bloated objects for every simple type of class you want to use. In more complex projects you may need to skip some of the simplifications, to get more flexibility in functionality for each class.


Debug slow code with ticks

October 24, 2011

I made this small snippet of code today, using my style of coding with a singleton class wrapped into a function. The idea is to time the differents parts of the code to find where the code is slowest, and thus, where to improve and optimize. The way you use the code is like this:

tick('Initialize');
/* CODE TO TEST */
tick('Code snippet one');
/* CODE TO TEST */
tick('Code snippet two');
tick()->show();

This will echo something like:

Msg: Initialize
Msg: Code snippet one
Time: 3.543 sec
Msg: Code snippet two
Time: 1.002 sec

Here is the full code:

function tick($msg = ''){
    $instance = ticks::inst();
    if($msg != ''){
        $instance->tick($msg);
    }
    return $instance;
}

class ticks {
    private $tick = array();
    private static $instance;
   
    public static function inst(){
        if(!isset(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }
   
    public function tick($msg=''){
        $time = (string)microtime(true);
        $this->tick[$time] = $msg;
    }
   
    public function show(){
        $last = 0;
        foreach($this->tick as $time => $msg){
            $time = (float)$time;
            echo 'Msg: "'.$msg.'"';
            if($last_time != 0){
                $sec = round($time-$last, 3);
                echo 'Time: "'.$sec.' sec"';
            }
            $last = $time;
        }
    }
}

Is PHP frameworks bound for patterns?

February 12, 2011

I was looking into the code of some common and uncommon PHP frameworks, and all of them proudly showed off their implementation of MVC pattern. Some of them were using a variety of other patterns and techniques – and I was wondering, do they really have to?

I was all confused when the different frameworks had their huge folder structure and a lot of stuff you had to do in order to echo out “Hello World”. And they said it was easy and fast. The fastest and most easy is still to write echo “Hello World”.

Its ok and good to implement MVC structure on a framework – it’s almost a nessecity, because programmers all know what it’s about and can easily adjust. But don’t tell me that your framework is special when it’s not. Dont tell me that it’s simple when it’s not.

I think, on the framework I’m building and the projects I’m working on, that the framework frees me from being bound to MVC and patterns (or was it the other way around, that they bind me to use MVC and patterns?). Instead I create my own based on the needs of the site (it be an abstraction of MVC or other patterns). Frameworks, in my opinion, is for abstracting away some code and make it easy to write the application. I like thinking new and creative.

But the again. I never liked frameworks. So my vision is clouded in the matter, I admit that.


Sexy Code

February 5, 2011

Why does JavaScript get all this attention and rethinking these days? Wherever I turn my browser there is a lot about jQuery, node.js, prototype etc. Why cannot the same techniques be applied server-side, on PHP? Aint PHP sexy? JavaScript was not sexy at a point until someone made something with it and it became fantastic and easy. How did that happen? Are JavaScript developers more creative? Is it a better and more flexible language? Is it because its front end and handles interaction?

Well. I’m going to try to code sexy when I do PHP. Right now I’m writing this html parser that is neat and cool. I want to be a part of server-side language revolution with PHP. It has potential! I don’t want to hear about Ruby on Rails, .Net or Python – lets empower PHP, and get rid of all that crappy code out there.

I’ve programmed a database class multiple times, and its an evolution. This happens in every aspect of my code all the time, and that’s really a journey. Here are the database example:

First it was spaghetti.
Second time I made it in a config file.
Third time I switched out mysql with mysqli and made some functions.
Fourth time I made the database a class.
Fifth time I accessed it through a controller and DAO classes.
Sixth time around I made it a singleton and reused the connection.
Seventh time I added pconnect and it became persistent.
Eight time, then the database object extended the mysqli class.
Ninth improvement was to make a ORM expand the connection.
Tenth evolution was to make an easier access for the creation of advanced queries.
Eleventh time, I made the ORM chainable and combined more advanced queries to it.
Twelfth thing was to improve the to interact with different kinds of result sets.
Thirteenth, in the end, the chainable database singleton class extending mysqli got wrapped in a function for easy access.

How do you like this kind of code:
echo query('tablename')->columns('id, name, regdate')->where('id > 155')->orderby('name')->asc()->toarray()->html();

And the future still brings more:
– The code to support multiple different databases
– Extends the support for joins and relations
– Add better template engine to the output presentation
– Make the mess faster

That is what I’m currently working with…


Reducing database queries

September 12, 2010

I found a real badass design flaw on my newly created ORM system the other day. On the register form for a movie, the page had 119 queries taking about 0.085 seconds of running time. Since the site is not finished and the movie I was editing was a simple test, this would have been maybe 250+ queries for one movie, and the data would have been much more on in the tables so the time of each query probably would have been much higher in a real live situation. Have this in mind. What I had done, was to fetch the relations in the many-to-many table with one query each(so that I could use the same get method for every object, including relations). Really dumb, but I did not think it would affect that much in the beginning as long as each of them were fast.

Well, it took time, and I rewrote the system to get every relation in one query per table – reducing the amount of queries to 51 and the time went down to about 0.040 seconds for the page load. That made me think, 51 still sounded a lot to me, so I decided to analyze more. I noticed then that I made the same query many times to some of the tables. For instance, the country table, where I fetched all the objects every time I needed the list. And that list I needed in many places, more precise, in many of the relations. The solution to this began as a crazy simple idea that worked.

What did I do?

In the object that fetched the countries ( SELECT * FROM country ) and made the country object list of it (as mentioned, unfinished and short list), I added a private static $table = array(); at the top. Then I simply used logic from the singleton pattern. I checked if the self::$table['country'] was set with the list, if yes, I used the old list – if no, I created the list.

The amount queries was reduced to 33, and time to 0.035 seconds.

I still need to see if this is a good solution in the long run, as the time to execute the page varied a bit more than before. Can’t wait to see how it performs when the tables gets filled with data.


Database connection speed in php

September 2, 2010

So, on this current project of mine, I have one unfinished page that have currently 31 fast mysql queries(to a database that contain a very little data) – and I wanted to see how different settings would affect the speed. I have heard that connections are costly, but how costly are they really? These are the average results of my little test:

One connection for each query: 0,045 sec
One persistent connection for each query: 0,025 sec
One connection used in a Singleton pattern: 0,0175 sec
One persistent connection used in a Singleton pattern: 0,0165 sec

Summary:
The old method is the slowest by far! If you have many concurrent users on the webpage persistent connection will help a bit. But the best effect is from using a Singleton connection – or another method where you use one instance of the connection on all the queries. Persistent connection uses some time fetching the connection from mysql on the server, so it’s faster to do it in code.


Storing Images with PHP & Mysql – The right way

April 22, 2010

I’ve in that stage of my latest project that I have to decide how to store images to the server, and how to use the database the best way to do this. I know that I’ve done this wrong a couple of times, but hopefully I’ve find a good practice of this now. Not quite sure if this is the best way, but this is how I think after looking into the matter:

There are several things I consider to be important:
1. SEO.
The filenames need to be descriptive and searchable.
2. Database
Images should not be stored in the database, but the filename and id should. You need to know what image goes with what movie. It is possible to store images into database, but it makes the database big and I can image working with the images becomes little more complicated. There are advantages to this too, but it is not the way I’m going to do it.
3. Thumbnails
It’s a good practice not to resize in the <img> tag, so a good system for thumbnails must be at hand.
4. URI
Where to put the files is also something you have to consider carefully. Is it best to put everything in one folder? Probably not. What about “movie-id/images/image.jpg” or “images/movie-id/image.jpg”? Much better.

Let’s take an example database with four tables: Movie, ImageType, MovieImage and Image

Movie:
Important part of movie is that it must have an id and a title.
ImageType:
Must have an id and a type, ex: cover, poster and screenshot
MovieImage:
Realtionship between the movie, image and type. Contains the foreign key to image, movie and imagetype, where one of them has to be unique.
Image:
The image should have an id to the image so that it can be connected to a movie and made unique. In addition it should contain a filename, that is generated in php from the id, title of movie and type of image.

Cooking it all together:
The filename must be SEO optimized, so the syntax to use should be like: id-type-movie-name.jpg. You could remove the type from the name, but it’s a good way to distinguish between the different image types, making the SEO better too. Movie name should be separated by a hyphen to be most SEO friendly. By storing filename once with id instead of generating it every time and out from id, type and title is good practice because if the title is changed (from “Lord of the rings” to the more accurate “The Lord of the Rings: Fellowship of the Ring”) the filename points to the right file – id-type-lord-of-the-rings.jpg. Generating thumbs could then follow a standard of adding a -thumb-width-height or something to the name – or simply create it on the fly with a php method, even thou I think the first option is more correct. When getting all images to a movie you can easily sort by type, and get the filename from database – and then show it on your webpage by creating the correct url, ex: images/movie-id/1923-cover-lord-of-the-rings.jpg.

By thinking like this, the image uploading and storing become much more simplified for me than how I’ve done it before.