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.


Learn Best Practice, don’t settle for them

March 11, 2010

I’m always trying to find what they call “Best Practice” on the problems that occur when creating a website, but they are not always easy to find on the specific problems, and sometimes they are a little bit hard to understand. For example, a lot of Best Practices are described in so-called Patterns, a template of how to build your website, but these Patterns is often hard to understand – especially if you’re trying to force them into your code. When you code a bit, and you get into a problem that one of these patterns append to, then you often understand why this is called a best practise and learn it. When you have learnt it, you can then use it and modify it to match your project in a better way.

I recently read the article Your Website is Unique. Don’t Settle for Best Practices. at Future Now, giving a little more insight at why not always settle for the best practice(when you want to increase conversion rate). The main idea is that your web page is unique, and that you have to use whatever changes that makes it unique instead of going for solutions that are made of someone else. I’m taking this idea further, to the stage when you are coding your site, instead of optimizing it.

Dont get me wrong. I still love best practices. I still are going to look for those problem solving patterns. They might be much more important in the back-end than in the front end. The thing I’m going to make sure to take into consideration is, if these best practises are best for my unique site, and that they don’t make my ideas become a copy of someone elses. Code as you can, so that you understand your code and are able to modify it with ease.

Test your code, and consider other programmers solutions after you fully understand them.

As an example, I can take the first guest book that I “programmed”. I didn’t know PHP very well back then, and had never used MySQL to store anything – so this was really basic. For me it looked like code I did not understand, so I copy pasted it, modified a bit, and got it to work – but I did not really understand it. So, when I now look back at that code, I se how flawed it was, because now I know how to code it. Even thou that guest book code was made by a programmer, based on some good practices at that time, I did not learn or know about them back then. When I look back at it now, and understand the logic, I see that even the original script was flawed, because it do not match the criteria I’ve now learned to be good code.

So, are you an experienced programmer, your code are probably mostly very good practise. Are you an average programmer, you’ll probably learn a lot from these experienced programmers. But if you are a unexperienced programmer, learn first the basics, understand the code of average programmers, and strive to achieve understanding of good code. This way, you can make your site your own. I consider myself average, that is trying to achieve what experienced programmers can do.


Persistent MySQL connection

February 23, 2010

It was not that long ago I figured out what this ment, even thou persistent is kind of self-explanatory. I read that this was a must on a sql connection, but I never learnt it at school or did find out how to do it. For me it was a fancy word for a more complex connection type, but is it really more complex?

What I usually do, is that I use the singleton pattern on my database connection so that on each load the connection is created only once and then reused for every new use. A database connection is expensive, so it is a good thing not to create it a lot, and this is what singleton does. A persistent connection is like a singleton to the server – and does the thing that I hoped singleton would do when I first heard about it.

A persistent connection does not close, but it reused by the different connections to the server. This means that the same connection is reused by every user that connects to the server, and there is not created a new one for each time. Sounds simple? It is simple.

The real use of it is probably only when you have a bigger site with many users and traffic is big, so it is not really necessary for small websites that barely use a connections and have under 50 visitors a day. The singleton helps a lot on each user page load, when the connection is preserved and reuses for the page load, but still, using a persistent connection could slightly improve speed even thou it is probably not noticeably. The real problem solved with persistence is that you can have many more simultaneous connections to the database – getting rid of the connection overhead problem.

How to do it?
I use the mysqli extension for PHP, and the only thing needed is to add a ‘p:’ to the host address, like this:

$db = new mysqli('p:localhost', 'username', 'password', 'databasename');

This only works with PHP 5.3.0 or higher, so be sure you have it both locally and on the server. I you don’t have it or don’t use mysqli, then there is an alternative, to switch form mysql_connect to mysql_pconnect.

That simple, really – and no other change to code.


How to set that title tag?

February 15, 2010

I’m in that place in developing my new site that I have to decide how I will manage the inclusion of pages, and there is a problem what I’ve really never bother about before. How to change the title tag in HTML the best possible way. This is a must for several reasons. First off, it makes the SEO(Search Engine Optimisation) better by giving a descriptive title to the page that show up in results. Secondly, most browsers now use tabbed browsing and to se on the tab what page it is you are on is a good thing.

Now, I have to tell that I do not use frameworks – mainly because I want to learn stuff myself first – so even thou they probably have implemented a good solution, I still need to fine one myself that will satisfy my needs and make the programming part good.

The problem might not be a big problem, but it is really a good example on why a good design should be implemented. The way I have done it before is simply to have one title for each page – because the title is in the header, and the header was an HTML file I included at the top of the php. Easy fix is to add some php that gets the page attribute from the url, and then does an if else on every page to give the right title. The problem is, this is an if else, or switch, that you then probably have to implement a lot of times in the code – for example to find out which menu item you are currently on – and makes the code unneccessary hard to read. The rule of making most of the logic in a underlaying architectural layer should apply.

So, the solution then? Well, I tell you my simple plan that is under developement.

I’m going to make the page a PHP Object, (pseudocode) like this:

$page = new Page($_GET['page']);

The “?page=user” is set in as an attribute to the page object. The same is done with the id=1, and other attributes if they exists. Then when the page is printed the header is put together.

$page->printHTML();

printHTML() is using the self::getHeader and self::getBody to build the complete HTML wrapped in Should Body and Header be Objects too?
Should Footer, mainBody, navBar, Logo, sideBar be objects as well?

To be honest, I really don’t know how far I will make it – but I do se a pattern that every changeable part of the design should be objects – so that they can be built on they own. Especially Header, Body and sideBar(that is a part of the body). This is a bit out of scope right now, but the point is to make a design that is object-oriented right to the core, making the attributes on the object decide what HTML to include, and then present it the right way.

Back to the title, lets imagine we have a simple Page object with a simple all in one getHTML() function. This then contain the following simplified code:

return ''.self::getTitle().''.self::getBody().'';

The getTitle() function should do something like this:

$title = 'Sitename - '.$this->page; //User
if($this->id){
$user = new User($this->id);
$user->get(); //Get the user from database
$title .= ' - '.$user->getName();
}
return $title;

This is not the code I’m going to use, it’s just to show the logic. I think this approach gives good practise in programming an OO(Object Oriented) way, and hopefully makes the site flexible too.

Does this make any sense at all?