Probability poll in PHP

March 20, 2012

I searched for a good way to make a poll in PHP, that made it easy to pick a user by X chance of probability in relation to other users. I did not find any easy and simple solution so I wrote one myself.

class poll {
    private $data = array();
    private $list = array();
            
    public function add($data, $value){
        $this->data[] = $data;
        end($this->data);
        for($i=0; $i < $value; $i++){
            list[] = &$this->data[key($this->data)];
        }
    }
    public function get(){
        return $this->list[rand(0, count($this->list)-1)];
    }
}

You add the items into the poll with specified probability, and then pick one item from the poll based on all the items in it. Example of two users in the poll both having the probability of 50% to be picked:

$poll = new poll();
$poll->add($user1, 50); //or 1
$poll->add($user2, 50); //and 1
$chosen = $poll->get();

There are some flaws and many ways to expand the class (like including the removal of the chosen from the poll – so that you can pick more and not the same twice), but I tried to make the most simple solution of a poll like this.

Hope you like it 🙂


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.


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;
        }
    }
}

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.


PHP $_GET in JavaScript

June 15, 2011

This other day I encountered a situation where I needed to pass in variables to a javascript. I had built the javascript in a PHP file before, and could easily use PHP to inject the variables like this:

var name = "<?php echo $name ?>"

But when I wanted to separate the javascript from PHP I could not access the PHP variables anymore, the solution was to do it like this:

<script src=”my_script.js?name=<?php echo $name ?>” ></script >

and then access the variable from the script by $_GET.name

The code on jsfiddle:
http://jsfiddle.net/ctncP/


try to catch this if else

May 1, 2011

How should you write “try catch” and “if else”?

I’ve seen a lot of this:

if() {
}
else {
}

try {
}
catch {
}

But it really should be like:

if() {
} else {
}

try {
} catch {
}

Why? It’s really a little detail, but in the first examples it looks like you could add code between the try and the catch, because they are two blocks of code. But the catch belongs to the try, so it should not be seperated by a new line.


Thoughts about __toString() in PHP

March 23, 2011

PHP is a loosely typed language(the same variable can be a string or number), but sometimes I think it should be even more loose in some aspects and allow even more magic. Maybe that was a wrong way of putting it, but especially in the case of __toString() in PHP I think that the developers copied Java without thinking the possibilities of the method, what it could have been if it was not bound to “String”. “String” is this old thing, actually one of the first things, that was created out of 0 and 1.

If you’re not familiar with __toString() method, I’ll first explain what it does. The __ tells you that this is a magic method, and it is a feature provided in an object in PHP and many other languages. The point of __toString() is to return a string value of the object if it is in a string context, or simply put, echoed. Example:


class Person {
private $fname = 'John';
private $lname = 'Doe';
public function __toString(){
return $this->fname.' '.$this->lname;
}
}

$person = new Person();
echo $person; //John Doe

For me this gives my object a new dimension. My Object is a string and an object. And I’m mostly fine with it, more than that, I love the feature.

What I would like to change is to change the __toString() method into __toValue(), or add more functions like __toArray() and __toObject() or __toWhatever() that can be used if the __toString is not set or/and in a prioritized order(I say if the __toString() is not set, because it should not be deprecated at first).

Let’s make __toArray() the example. I would like my object to be interpreted as an array in some cases if the object way is not supported. The best way to show what I mean is to use an example:


class Person {
private $fname = 'John';
private $lname = 'Doe';
public function __toArray(){
return array('fname'=>$this->fname, 'lname'=>$this->lname);
}
}
$person = new Person();
//NOT VALID PHP
echo $person['fname']; //John

//VALID PHP
$person = $person->__toArray();
echo $person['fname']; //John

As you can see, the idea is likeable – and I’m not the first one to propose the add-on. But why do I like this?
– Because it gives an Object more functionality
– You can do much more cool stuff without having to create and call functions for them
– Gives objects multiple dimensions, and makes them more rich
– Cool if you need to transform an Object into different types of structures and easily append into different situations
– You could use an Object in new places, like directly in a foreach loop
– Why should this only work with strings?
– Can give access to private and protected values of the object where casting((array)Object) does not work
– __toString() is actually faster than calling a public method toString() that does the same.
– Great way of simplifying some frameworks
– __toString() limits the use of something that should not be limited in my opinion

Why not?
– It’s not that hard to make an own toArray() method that does the magic without being magic
– Magic methods may add some more “WTF?” to some programmers
– (whispering carefully from a corner)We should not use magic methods that much? (Why not?)

Well, I really can’t think of many bad things with some extra magic. Are there other arguments for or against?


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!


Send large emails in php

March 17, 2011

I’ve encountered this problem once a long time ago, and used a lot of time finding a solution back then. Probably because no one really directly issued this problem.

When you send large text in your mail, specially HTML, you have to remember to encode the message right and chunk it. Why? The email standard RFC2822 only accepts line lengths of 998 chars, and if you send longer lines you probably encounter a lot of problems in different email clients. This may be line breaks or spaces after every chunk of 998 chars, that could be in the middle of an HTML tag or link, making the email body a mess.

To avoid this, you have to use base64 encoding on the email body header:

“Content-Transfer-Encoding: base64\r\n”

The second thing you have to do is to encode your content string with base64 and chunk it into chunks before appending to the email.

chunk_split(base64_encode($content))

base64 encoding is something email clients can read and because the sting of HTML is encoded into this format you don’t get the spaces between every chunk of content when the client displays the content.

These two lines is the only thing you probably need to append when you ha long text or large emails with data longer than 998 chars. Today I encountered this problem again, and I knew about the solution so I knew what to google to find the right answer. But I did not find it right away, because there was not any really good, and short, explanation anywhere that said exactly what I needed to do.