Better use of a Getter method in PHP

February 25, 2012

You are probably familiar with getters and setters in object-oriented code. Usually they are something like this:

public function GetId(){
   return $this->id;
}
public function SetId($value=0){
   $this->id = $value;
}

Normally I improve these two methods by setting them into one method, like this:

public function Id($value=null){
   if($value == null){
      return $this->id;
   } else {
      $this->id = $value;
   }
}

But when doing this you have no place to add arguments into the getter method, based on the idea of a improved getter. Having an input argument as the fallback value if what you are getting is the false value. This is the new getter:

public function GetId($fallback=0){
   if(!$this->id || $this->id == 0)){
      return $fallback;
   } else {
      return $this->id;
   }
}

For an id this kind of fallback functionality may not make that much sense(but it might), but for a GetName or other it probably is. Consider this:

$html = 
'<input name="name" value="'.
($obj->GetName()?$obj->GetName():'Please enter your name')
.'" />';

Now you can replace it with this reducing unneccessary logic from the presentation:

$html = 
'<input name="name" value="'.
$obj->GetName('Please enter your name')
.'" />';

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.


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.


A DOM Experience

June 9, 2010

I’m currently writing a website, and trying out different things to learn what the best solution is. This time around I was playing around with how to easiest create the HTML elements and attributes, and ended up with creating a simple HTML class. When I looked at it, it reminded me of DOM – and I asked myself – why didn’t I use that in the first place?

I use mainly DOM to create XML, and since XHTML has a XML structure and can be validated with a DTD – It should work well to build it with DOM elements and attributes.

In the beginning it seemed harmless and went pretty well, but when I then wanted to test my code it went bad. The problem was the same thing that I struggled some years back when I first was introduced to DOM, and I think it may be the one reason that it makes hard to program DOM in an object-oriented fashion. DOM is not a very flexible way to create a whole advanced web page in anyways, but maybe especially if you have chunks of HTML returned by objects.

The problem of DOM in my opinion is simply that you cannot just create an element and add it to a tree. No, you need a DOMDocument object, to create the element belonging to the tree, and then you have to add the element to an element already on that tree. Why is this so bad then? Because you cannot make chunks of XML and add it in to the document without having access to the parent and the root element. It can become pretty messy to pass them along the whole time.

DOM is great for modifying HTML and XML, getting stuff out and adding content to the tree – not creating them. That is my current opinion. Maybe there is some good ways to do it, but I didn’t want to waste my time anymore experimenting on it.

Back to my HTML class: This one can do it just as I created it to, generating HTML – not modifying, not adding content to a file nor getting stuff out.


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?