Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, December 16, 2014

Memcache and PHP

In this post I'm going to use PHP Memcache module as an interface to memcached. If you need to reduce the database load for your webapp this approach seems pretty cool.

I assume you have already installed PHP/MySQL and a compiler on your machine. You can install "build-essential" in order to install Memcache.
sudo apt-get install build-essential

Install php5-memcache
sudo apt-get install php5-memcache

Install Memcache daemon
sudo apt-get install memcached

Install PHP Pear
sudo apt-get install php-pear
Add Memcache using PECL module
sudo pecl install memcache
Update memcache.ini using following,
extension=memcache.so
Verify  Memcache installation

i) Try telnetting to your Memcache instance using,
telnet localhost 11211
ii) phpinfo()



Lets write our first simple PHP script,
<?php
$memcache = new Memcache();
$memcache->addServer('localhost', 11211) or die ("Could not connect");
$key = md5('my-name'); // Unique key
$cache_result = array();
$cache_result = $memcache->get($key); // Memcached object
if($cache_result){
// Second Request
$demos_result=$cache_result;
echo "Result found in memcache\n";
}else{
// Initial Request
$name= "Udara R";
$memcache->set($key, $name);
echo "Result not found in memcache, added to the memcache \n";
}
echo $cache_result."\n";
?>
So here I'm using md5 value of the "my-name" string as the key, you can use unique ID (UUID)  while storing values in Memcache.
$key = md5('my-name');

Then I'm trying to retrieve existing value attached to my key,
$cache_result = $memcache->get($key);
If we are unable to retrieve anything from Memcache, then set key-value pair using,
$memcache->set($key, $name);
Our objective is to reduce the database load in this post, so we can interrupt our data retrieve logic to find relevant data in Memcache first, then query from database and put in to the cache layer, if not exists.

Tuesday, October 21, 2014

Talking to an Arduino from PHP

I was able to talk to my Arduino without using an Ethernet or a wireless shield.
Best part is that I only have 4 lines in my PHP script :)

Things you need to have :

Arduino board with a USB Cable
Breadboard
1 LED
Few jumper wires
220 OHM resistor

Additionally Arduino IDE, PHP, Apache2 installed Linux box :)

1. Connect Arduino's GND pin to breadboard's ground line.
2. Connect Digital pin 13 to breadboard's + line.
3. Connect LED's Anode(long leg) with the breadboard's + line using the 200 OHM resistor.
4. Connect LED's cathode(short leg) with breadboard's - line directly using a jumper cable.

You are done with the circuit prototype, Now connect the Arduino board to your PC.

Open Arduino IDE, click on tools> Serial port. You can see the device connected to a port similar to "/dev/ttyACM0".

Let's write our PHP snippet,

<?php
  $comPort = "/dev/ttyACM0"; /*Update to the correct port */
  $fp =fopen($comPort, "w");
  fwrite($fp, "switch"); /* We are going to write "switch" */
  fclose($fp); 
?>
That is it, host this snippet switch_uno.php within  /var/www/php-arduino directory. lets write our Arduino sketch.

String val;

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

void loop()
{
    while (Serial.available()){
        delay(10);
        char c = Serial.read();
        if (c == ','){
            break;
        }

        val+= c;
    }

    if (val == "switch") {
        if(digitalRead(13) == LOW){
            digitalWrite(13, HIGH);
            delay(100);
            Serial.println(1);
        }else if(digitalRead(13) == HIGH){
            digitalWrite(13, LOW);
            delay(100);
            Serial.println(0);
        }
        val="";
    }


}

Upload above sketch to your Arduino and open the serial monitor window within the Arduino IDE.
In order to execute our PHP snippet,
Lets open a terminal window and change directory to the /var/www/php-arduino directory.

run sudo php switch_uno.php your LED will be on :) If you run the same command again LED will be off.

You can do the same by using PHP serial class also.

Friday, October 25, 2013

MongoDB - usage of Primary Key

Like other databases MongoDB also uses primary keys to distinguish documents.
We can provide our own, otherwise MongoDB will create itself a primary key for each document. This key is a Object which consists of time-stamp and information about the machine which document created.

How to provide our own primary key

$connection = new Mongo( "10.100.0.128:27017" );
$db = $connection->selectDB("primary_key_blog");
$collection = $db->blog_collection;
$collection.insert({ _id: 1, author: "UdaraR", blog: "http://udarakr.blogspot.com" });

else we can just say,

$collection.insert({author: "UdaraR", blog: "http://udarakr.blogspot.com" });

If we read the document we stored back,
 $collection->findone( array( "author" => "UdaraR" ) );
You can see that MongoDB itself added the 12 bytes ObjectId.

The greatest thing in the second method is that you can extract created-time without storing it separately. You can simply use ObjectId.getTimestamp() method to get this done.
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp();
Other than the above usage, as in all other databases the primary usage will be to query using the ObjectId.

$id = new MongoId("507c7f79bcf86cd7994f6c0e");
$collection->findone( array( "_id" => $id ) );
Keep in mind this is not equal to string "507c7f79bcf86cd7994f6c0e".

Other than findone, we can provide this ObjectId with find, remove, update etc.

Tried this sample on linux environment with the use of mongo driver.