Category: PHP

Bring some Ruby/Prototype flavour in your PHP array

You know that in ruby/prototype you can traverse thru each element of array like this Array.each(function(){/*function body*/}). It has also some methods like without(), inspect(), indexOf();last(),  first() and others…. so how about implementing these cool methods in your regular PHP array?? No problem, lets extend the ArrayObject and have some fun. Here is the class.

class ExtendedArrayObject extends ArrayObject {

        private $_array;
        public function __construct()
        {
                if (is_array(func_get_arg(0)))
                $this->_array = func_get_arg(0);
                else
                $this->_array = func_get_args();
                parent::__construct($this->_array);
        }

        public function each($callback)
        {
                $iterator = $this->getIterator();

                while($iterator->valid()) {
                        $callback($iterator->current());
                        $iterator->next();
                }

        }

        public function without()
        {
                $args = func_get_args();
                return array_values(array_diff($this->_array,$args));
        }

        public function first()
        {
                return $this->_array[0];
        }

        public function indexOf($value)
        {
                return array_search($value,$this->_array);
        }

        public function inspect()
        {
                echo “<pre>”.print_r($this->_array, true).”</pre>”;
        }

        public function last()
        {
                return $this->_array[count($this->_array)-1];
        }

        public function reverse($applyToSelf=false)
        {
                if (!$applyToSelf)
                return array_reverse($this->_array);
                else
                {
                        $_array = array_reverse($this->_array);
                        $this->_array = $_array;
                        parent::__construct($this->_array);
                        return $this->_array;
                }
        }

        public function shift()
        {
                $_element = array_shift($this->_array);
                parent::__construct($this->_array);
                return $_element;
        }

        public function pop()
        {
                $_element = array_pop($this->_array);
                parent::__construct($this->_array);
                return $_element;
        }

}

######################################

Now you can use it like this

$newArray = new ExtendedArrayObject(array(1,2,3,4,5,6));

or you can even construct it like this

$newArray = new ExtendedArrayObject(1,2,3,4,5,6);

then you can use these methods

function speak($value)
{
  echo $value;

}

$newArray->each(speak)
$newArray->without(2,3,4);
$newArray->inspect();
$newArray->indexOf(5);
$newArray->reverse();
$newArray->reverse(true); /*for changing array itself*/
$newArray->shift();
$newArray->pop();
$newArray->last();
$newArray->first();

So how is this ExtendedArrayObject, like it?

Regards
Hasin Hayder
http://hasin.wordpress.com

Autoloading Data Models

Hi Guys

Consider you have a model like this

class samplemodel
{
public method setName(){/*set the name*}
public method setEmail(){/*set the email*}
}

Models are usually relevant to database tables. So if you have tables with 10-12+ fields you may define accessor methods for all these fields in your model. Now when loading data manually in the model after submitting an HTML form you need to call them like this

$model = new samplemodel();
$model->setName(“some name”);
$model->setEmail(“some email”);
……………………..

For models with few accessor methods it may be easy to type manually all these data. But for 10-20-30 its totally ridiculous.

Thats why I designed this small Automatic Data Loader class which takes a model as first argument and and data array as second argument and then loads data from that array to that model. How is it looking?

$val)
{
if (is_callable(array($module,”get{$key}”),$callable))
{
echo “$key
“;
call_user_func(array(&$module,”set{$key}”),$val);
}
}
}
}
?>

Now if you have two input object named “email” and “name” for example in yoru html form and you call this loader as shown below, it will load all the data from $_POST to the model automatically.

$model = new samplemodel();
dataloader::load($model, $_POST);

as the model is accessed with BY_REFERENCE style, so it will fetch $model->setName() and $model->setEmail with appropriate $_POST data and your model will be loaded automatically.

This comes really handy when you have to load models with many accessor methods. I developed this object while working for Bangla Chat Engine last night and Ha Ha HA, it really saves my time.

Caution: Using raw user submitted data from $_POST or $_GET is not secured. You should filter them first.

phpexperts get-together at 16th september, 2006

SomewhereIn

It was a great party yesterday we had at somewherein. From this month we started the phpexperts monthly meeting which is sponsored by somewherein this month. Yesterday we were scheduled to start at 3:00 pm. The first who knocked the door were tahsin, najnin and kamrunnahar. Tahsin is the member of phpexperts and other two were her interestd friends. Later Prasun and Biplob came in. Shortly after that we had Mizan bhai, Rinku da, Munaz bhai, murshed, Arafat bhai, hasn, Emon, joyeb, rafik bhai, shoeb bhai, raisul and another friend of rafik bhai.

We introduced somewherein and pageflakes in our meeting. We discussed about the current trends and the market situation. Everyone agree that we should increase the awareness abd professionalism in this field. RInku da and Mizan bhai shows us what is the current situation. Later we had an interesting presentation from Hasan regarding design patterns and then we all started talking about DP. Dp is always useful but unnecessary use of DP may decrease the productivity and increase the cost of project.

After hasan’s presentation we discussed about security features of an web application and I show how sql injection and xss could be vulnerable for your applications.

Mizan bhai and ringku da talked about some interesting issues regarding database optimization.

The most interesting part was after hours of the meeting. We 9 people were still there in some close conversation and we discussed about promoting php in Bangladesh as well as promoting the name of local developers and groups internationally. We all agreed that we should bring forward the name of Bangladesh in this sector. We planned about starting some open source projects. But starting it in large scale from the beginning wouldn’t be that much effective as we see many well planned initiative comes to an end because of communication gap and lack of management. So we planned to start it in small scale – our first open source project will be a “Bangla Chat Solution” – I advanced a bit in planning and I will share it with group from today.

Finally we got a fantastic idea to write a very good bangle book on PHP. Everyone was so happy with this idea that we were surprised – this is a real problem that there is no good bangle book in Bangladesh right now. So if we, the leading php community can start writing one, it would be great obviously. We setup a small group who are interested to write the book. Mizan bhai and I will manage the project and co ordinate the writers. Primarily I, Mizan bhai, Arafat bhai, Munaz bhai, Raisul, Hasan, Murshed and Prasun agree to write. But if anyone of you are interested, you are most welcome to join.

The meeting ends at 8:30 and we are very happy with the decisions taken. We hope that you will join in next meeting and participate with us in these interesting sessions.

Thanks to somewherein for sponsoring this great party.

A brand new day

Yesterday Dhaka was a hot city due to political strike of opposition party. I was in home with new idea and works. I wake up at 9PM and started writing the pending and last chapter of my wordpress book, “developing widgets and plugins”. Ayesha and Afif went to a relatives house so that I was all alone in home and my work ran on full throttle. I completed around 13 pages yesterday.

At night I started my long planned project “Golpo”, the Unicode based bangla group chat solution for netizens. I was working with the DAO and I almost finished it. I was planning for this project for a long time and DB schema was ready, just needed to start the work.

From now on, I will publish my upgrade regularly on this project. I know that I will be stuck with UI part because I am not a good designer.

Lets roll the project – It will be finished soon.

Creating Thumbnail of WebPages using WebThumb API

Joshua Eichorn, the author of “Understanding AJAX” and a renowned php developer recently released WebThumb, a site to create thumbnails of web pages. The whole system is developed in c and it uses Mozilla engine to render the webpage into images. Shortly after publishing WebThumb, he released a set of API so that developers can create thumbnails from their applications. This API is very simple to use. In this Article we are going to discuss how we can incorporate WebThumb API in PHP to create thumbnail of web pages from our PHP applications.

Using WebThumb API, you can generate a thumbnail in three steps. First you have to place a request containing the URL. As soon as your request is successful, WebThumb store your request in queue. That means you are not getting the thumbnail instantly (well, there are other factors also. to fetch an url requires time, so it is not possible to generate the thumbnail in real time) – In second step you have to check whether your thumbnail has been generated or it is still in the queue. If you get a green signal, you will proceed to the third step where you have to request a download URL of your thumbnails. Before jumping into the code, let’s take a look to the API format.

Step 1: Place a request
To request thumbnail for an URL, you should post an XML message to the WebThumb server in the following format

<webthumb>
	<apikey>apikey here</apikey>
	<request>
		<url>webthumb.bluga.net</url>
	</request>
</webthumb>

You may wonder at this stage that we didn’t discus about the apikey yet. So what is this and where from you can obtain your key? (more…)

Generate Thumbnail of Any Webpage using PHP

Joshua Eichorn recently released a fantastic service for creating thumbnail of webpages at runtime. The service is named as “WebThumb” . Later he relased some API for developers to incorporate the service using a API-Key. The API-Key is available after registering at the site.

Today I made a PHP Wrapper of his WebThumb API using Curl. Now you can create Thumbnails using this wrapper class from PHP. I released my wrapper under LGPL and setup and online version also.

See the demo Online

Download The Code

I hope you will enjoy it.

Using More DBs concurrently in PHP+MySQL – a Solution

Last night Hasan provided me a new solution which seems awesome. I am describing it here

$db1 = mysql_connect("host","user","pwd")
mysql_select_db("db1", $db1);
$res1 = mysql_query("query",$db1);

$db2 = mysql_connect("host","user","pwd")
mysql_select_db("db2", $db2);
$res2 = mysql_query("query",$db2);

At this point you can only fetch records from you previous ResultSet, i.e $res1 – But you cannot execute new query in $db1, even if you supply the link as because the link was overwritten by the new db.

so at this point the following script will fail
$res3 = mysql_query("query",$db1); //this will fail

So how to solve that?

take a look below.
$db1 = mysql_connect("host","user","pwd")
mysql_select_db("db1", $db1);
$res1 = mysql_query("query",$db1);

$db2 = mysql_connect("host","user","pwd", true)
mysql_select_db("db2", $db2);
$res2 = mysql_query("query",$db2);

So mysql_connect hasa nother optional boolean parameter which indicates whether a link will be created or not. as we connect to the $db2 with this optional parameter set to ‘true’, so both link will remain live.

now the following query will execute successfully.
$res3 = mysql_query("query",$db1);

Thanks goes to Hasan for informing me abt the fourth parameter.

Qucik and Dirty – using 2 DB concurrently in MySQL

Day b4 yesterday I was stuck with a simple and frustrating problem. You know that using builtin mysql support in PHP you cannot use concurrently more than one database to work with. That was also my problem while working in such a project where I badly need to read data from one database, validate it against existing data in second database and then insert the data into the second database. So you got the project? Yes its a simple data migration project. But the problem is that I cannot import the old database tables into the new one and I have to work with them keeping seperate.

So you may ask how about reading all the data from first database, then store it in a temporary media and then again read them while inserting in second db. Well that was not possible because in first DB I had 10 tables and in I have to merge all those info in two table in second database. Also I have to validate some of those data against existing data in second DB.

There comes the idea. What I did is a quick-n-dirty solution of this problem. I connected to the first DB using MySQL API, and I connected to the 2nd DB using MySQLi API. That gives me live connection of two DB at the same time. So I read data from first DB using MySQL API and then inserted using MySQLi API.

For sure I could apply another solutions like temporary storage. But why bother when you can trick??? This is just a one time operation, no matter how you do it. All you need is a merged output, at minimum efforts. Ha Ha Ha.

Using Blog API – Part 2: Get Categories and Posts

In our first part we just discussed what is a blogging API and how we can utilize them. In this post I am going to show how to fetch available categories in a blog and how to retrieve a specific post.

To retrieve available categories you have to use metaWeblog.getCategories as shown below

<?php
	include("xmlrpc.inc.php");

	$c = new xmlrpc_client("/xmlrpc.php", "hasin.wordpress.com", 80);
	$c->return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals

	echo "<pre>";

	$x = new xmlrpcmsg("metaWeblog.getCategories",array(php_xmlrpc_encode("1"),
	                                     php_xmlrpc_encode("someusername"),
	                                     php_xmlrpc_encode("somepassword")));


	$r =$c->send($x);
    if ($r->errno=="0")
	print_r($r);
?>

And To retrieve a specific post you have to metaWeblog.getPost API as shown here

<?php
	include("xmlrpc.inc.php");

	$c = new xmlrpc_client("/xmlrpc.php", "hasin.wordpress.com", 80);
	$c->return_type = 'phpvals'; // let client give us back php values instead of xmlrpcvals

	echo "<pre>";

	$x = new xmlrpcmsg("metaWeblog.getPost",array(php_xmlrpc_encode("1"), //postId
	                                     php_xmlrpc_encode("someusername"),
	                                     php_xmlrpc_encode("somepassword")));


	$r =$c->send($x);
    if ($r->errno=="0")
	print_r($r);
?>