Tag-Archive for ◊ functions ◊

I’ve been exploring these days how to create a definition of some method outside of it’s class. Usually there is no need to do that, but I had to write a class which works as a calculator with different input fields. Each input field has it’s own custom formula and I really wanted to avoid the eval() function.

The idea is simple: to create a class with some extra empty function (method), which can be defined from the outside, more specificly through it’s object in it’s custom way.

class Test {
    initialize: function(){
        ...
        this.my_extra();
    },
    function_1: function(){...},
    function_2: function(){...},
    my_extra: function(){ return 0; }
}

var A1 = new Test();
A1.my_extra = function(a){
    return a * a;
}

I tested this functionality in many different ways and I must say it works fine in almost any way you want. Outside methods can use arguments, call other class’s methods, call $(el) objects, and so on… You don’t even have to define an empty method inside the class, but it is convenient because you don’t know if it will be defined by object or not.

The numberConverter class

And here is my calculator with three input fields: tax, price, full price. By changing any of those fields the other two fields must re-calculate. Each field has it’s own calculation formula, it’s own event and affects a different field.

HTML:

<div id="page">
        <select id="tax">
		<option value="0">0</option>
		<option value="20">20</option>
	</select>
	<input id="price" type="text" />
	<input id="full_price" type="text" />
</div>

JS:

var p = new numberConverter('price',{
	onEvent: 'keyup',
	affects: 'full_price'
});
p.formula = function(){
	return p.val() * (1 + p.val('tax') / 100);
}
 
var t = new numberConverter('tax',{
	onEvent: 'change',
	affects: 'full_price'
});
t.formula = function(){
	return t.val('price') * (1 + t.val() / 100);
}
 
var f = new numberConverter('full_price',{
	onEvent: 'keyup',
	affects: 'price'
});
f.formula = function(){
	return f.val('full_price') / (1 + f.val('tax') / 100);
}

You can see that every new object defines it’s own calculation formula, which uses the val method from class to adjust decimal points and decimal places.

The numberConverter demo is here.

Parsing HTML tables with simpleXML
Sunday, July 25th, 2010 | Author:

Sometimes it still happens that you have to parse the entire HTML tables from other websites and many times that is the only way to do it. Here is a little tip how to make it simple with php’s simpleXML.

First you have to get the website with file_get_contents($url) and extract the table out (with preg_match or substr).

When you have the entire table in the $table variable, just put the <?xml version=”1.0″?> in front of it. That is necessary to call the simplexml_load_string($table) function. The table must be xhtml compliant otherwise the simplexml would raise errors.

The last step is the foreach($xml->children() as $tr){} loop, where you can access any cell row by row and get the data out of it. Thanks to the simplexml the data is already parsed out of the HTML tags and ready for use.

Example:

//get page
$url = 'http://www.apache.org/server-status';
$content = file_get_contents($url);
//get table
$start = strpos($content, '<table');
$end = strpos($content, '</table>') + 8; //length of </table>
$table = substr($content, $start, $end - $start);
//make it usable
$table = '<?xml version="1.0"?>' . str_replace('nowrap', '', $table);
$xml = simplexml_load_string($table);
//go through data, I need just 13. cell
foreach($xml->children() as $tr){
     if(isset($tr->td[12])) echo $tr->td[12].'<br/>';
}
Category: Web development  | Tags: , ,  | Leave a Comment
Generate an unique ID with PHP
Wednesday, June 30th, 2010 | Author:

While creating a webshop I had to generate some unique IDs for market orders. The autoincrement numeric ID is simply not good enough, because someone (for example your competition) could track the number of your orders. So I had to create a simple system to apply some unique ID number to every order that would not reveal how many orders we had so far.

I quickly realised that the md5 hash is too long, because the order code should be much shorter to use it on documents.

The only unique value, I could imagine, is time. If I write a php time() value it is already unique and will never repeat again. Of course you could have two or more orders in the same second of time, so it has to be more specific.

Here is my function:

function uniqueID(){

$time = microtime(1);
$parts = explode(‘.’, (string)$time);
return strtoupper(strrev(dechex($parts[0]) . dechex($parts[1]))) . dechex(rand());

}

//Returns for example 75020CB2C417f

I tested it with this loop:

for($i = 0; $i < 100; $i++){
$array[] = uniqueID();
}

and the $array was always unique! Of course all 100 unique IDs were generated in the same milisecond, but the rand() function ensures that you have no duplicates. I used the dechex() to get shorter results and strrev() to ensure that the result is not so obvious.

The rest is up to you. You should also try to insert some dashes to get more “document look” number, for example 75-020CB2C4-17f. And even if somebody could crack this unique ID, the only result would be the exact time of the order and nothing more!

Category: Web development  | Tags: ,  | Leave a Comment
Simple chart from <div>s
Sunday, March 21st, 2010 | Author:

Here is a simple PHP function for generating simple charts from div elements.

function chart($array, $size){
	$max = max($array);
	$ratio = $size / $max;
	$out = '';

	foreach($array as $el){
		$width = ceil($el * $ratio);
		$out .= "<div class=\"chart\" style=\"width: ".$width."px;\">$el</div>\n";
	}

	return $out;
}

There is a lot of room for improvements but I kept it as simple as possible deliberately. Many times you can find useful PHP scripts on the internet which are so complex that they aren’t useful any more.

Usage:

$test = array (35070, 24440, 4730, 35700, 29380, 22860, 28870, 22730, 26270);

echo chart($test, 400);

You can style your chart elements as you like, of course!

That’s it, you can check demo here!

Category: Web development  | Tags: ,  | Leave a Comment