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.


A tip when you are stuck

June 20, 2011

The other day at work I was making this algorithm, but did not get it to work. It looked so simple, but it was not – so I worked with it for a few hours without result.

When I took the time of for a few days, and decided to look at the problem again I fixed it in a few minutes. It was not a perfect fix, but as good as.

So, the tip when you are stuck:

Take some days off, and think of other things, and when you are back you may se an easy solution.


Ideas of March.

March 19, 2011

Oh blogging, oh blogging. Thy threshold is low, but the maintenance is big.

I like reading blogs. Especially those that have categories and tags to filter out all the stuff you don’t want to read about. The only thing that bothers me is that you often have to read a lot of blogs to find updated material on the things I care about, especially in the PHP community. Great post should be advertised and marked cool! If only the people who do have some cool code to provide could blog more frequent with a lot of cool code!! Sigh.

It’s a challenge. I know that, having some blogs out there with different kinds of content, updated every now and then. Blogging takes time if you want to do it good. People want an updated blog. Blogs does not bring that big of an income. But still, people keep blogging, I keep blogging, and you keep blogging. Every once and then someone finds your post in a time of need, and the purpose of the post is fulfilled. Do not blog for the masses, blog for the few that can evolve into masses. Blog for yourself. Blog to make a history, if only your own blogging history! That is a best practice!


The blessing in documenting code

February 23, 2011

I’m currently working on this framework in PHP but I was very unsure about what features to add. That’s why I began to document in the code at once, but it didn’t work right. It was too many changes in the code to begin with and I didn’t really know what I wanted – so the documenting was a messy draft that had no effect and became soon outdated.

But, that’s not the whole story. A framework need a good API, and I began working with it and found that it was actually a lot of fun. Firstly I listed every method I could think of, and then I began to write the functionality of each of them including examples of their usage. This way I found a lot of things to improve on the method functionality, I got a really good flow on programming them. It resulted in a really great API documentation as well.

What did I learn?

Different projects need different types of documenting. If you are unsure about your project try a more planned approach and then when the project is finishing up – then write the documentation in code. Other projects that has a lot of repetition in how methods act(like getters and setters, or getall_xx_fromdatabase) – they are easy to document in the code as PHP Doc because you know how to implement them and what you need them for. There is no point in building an API for a site like that. It’s not about what works for you, it’s about what works for your project.

This approach works also on testing. There is no point it creating unit tests for a framework that is under developement and have no real structure in what methods return or work. If you have a project with a lot of methods where you have define what they do, you can easily write Unit Tests for these methods. But if you, as I have, a method that does a lot of different stuff – then the best way is to have a test page and test alongside documentation. Later on, when you do a change, you can check if the test page renders the right way. When you have finished you can polish this test page, and make UnitTest for every possible use case.

Learn how to be flexible in how to document. When you do it right it might be fun. But do document!


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…


So, how do a programmer learn CSS?

November 7, 2010

I’m a programmer. I like to design stuff too, so I have a fair amount of knowledge about CSS. But how do I learn CSS even better?

Well, I stumbled upon this article about css minifier comparison: phpied.com – CSS minifiers comparison

CSS Tidy seemed to be the obvious best choice, so I thought I’d take up the challenge and make my own CSS minifier – based on the Ideas I had when I started to think about the logic behind. That’s where the fun began.

After some hours of work I managed to create a simple CSS minifier with PHP, that still is a way to go to match the capabilities of CSS Tidy, but where I even managed to be better in some cases. I still see a lot of improvement potential on my small script (~13 kb and counting – CSS Tidy is ~100kb), so hopefully the improvements can make my css files even smaller and crush the competition :-p

There is still a long way to alpha version(probably tons of bugs to fix before it’s stable), but when I come to it I’m probably going to put it out there as a web service.

What did I learn so far?
– A lot of CSS tricks!
– How to write CSS with more confidence.
– When shorthand css is favorable (“always” is the wrong answer).
– CSS never really stops being a mess :-p
– You can write very simple css, creating huge css files, and then easily minify and optimize size when in production.
– That the effort of creating very small css from scratch become somewhat pointless.
– How to write CSS the best for optimized minification.


Remember your customer

October 16, 2010

When you design or create a web page you have to remember who your main customer is. Or, do you? Is design and usability all about satisfying the supposed impression made by your customer?

I would say yes, and no.

Where I work, the business is all about money – and the ones that pay is not the typical web user. The ordinary customers to the site is all kinds of people, from the web novices to web experts. When we program and design, we make it as easy as possible. The UI is not very intuitive, but it is understandable. There is always a call to action, like “click here” or a description to simple tasks. I don’t always like this, but we need to do it this way if we want to reach out to the masses.

On the other side, the projects I do at home – they are partly for my own interest, but also part of using (hopefully) intuitive and creative solutions to attract the users. A way to get customers. A way to create attention. The average web user should figure out the features, and the design should be obvious but with features that are not that obvious until you start using the site more. This is on my premisses and terms, not on the end users – and there really is no support department to call if you are a novice and need help.

The third scenario is websites where the main feature is to test new features, new ideas, new ways to present and manipulate data. Typically a test site for new features in for example HTML 5, CSS 3 or some fancy JavaScript. Often these are a bit over the top creative websites that even pro web users have to use some time to tame. I think sites like that is mostly to test the web, to suggest new ways, to be ahead of the developement and to not care all about what will be a standard UI at the end to the common user. We need these sites.

These three examples are three different ways to program and design. What your goal is up to you to find out, but when a blog – or some expert – say that this is a trend, and that is a thing you should have, or a menu should look like this and a button like that – you really should think about the consequence. Purpose, content, design. They go hand in hand.


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.


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.