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

Thursday, April 4, 2013

Install and Configure Memcache/Memcached on Windows and CodeIgniter

I recently spent some time installing and configuring Memcache/Memcached on windows and codeigniter. There are some issues in the configuration i.e. CI supports Memcached and Windows support Memcache. So thought of sharing the steps.

First of all let's install Memcached. You can download Memcached from http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip

Unzip the file in some directory (let's say C:\Memcached). Open command prompt as Administrator. Point to the C:\Memcached directory. Next step is to install Memcached, you can do that by using following command:

c:\Memcached\memcached.exe -d install

Next step is to run memcached server. Use following command to do that

c:\Memcached\memcached.exe -d start

This will run the memcached server on port 11211. Now, let's configure php to run memcached. Open php.ini file and find ;extension=php_memcache.dll. If you find this line then simply remove semicolon from the start of line. If you don't find this line then add it at the end of extensions section. After extensions section, add a new line and paste following:

[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20  
memcache.chunk_size =8192  
memcache.default_port = 11211

Next step is to download php_memcache.dll file. You can download the file from http://downloads.php.net/pierre/ . Unzip the php_memcache.dll file and place it in php/ext/ folder.

Now, let's configure CI to run memcached. Create memcached.php file in application/config folder and place following code in it:

<?php

  if (!defined('BASEPATH')) exit('No direct script access allowed');

    $config['memcached'] = array(
        'hostname' => '127.0.0.1',
        'port'        => 11211,
        'weight'    => 1
    );

?>

Next, open \system\libraries\Cache\drivers\Cache_memcached.php file and in the function is_supported(), replace following line
if ( !extension_loaded('memcached'))
with
if ( !extension_loaded('memcached') && !extension_loaded('memcache'))
.Then in _setup_memcached() function, replace following line:
$this->memcached = new Memcached();
with:
if(class_exists("Memcached"))
  $this->_memcached = new Memcached();
else
  $this->_memcached = new Memcache();

Now, restart apache and create a test function in CI controller and paste following code in it to give it a try:

$this->load->driver('cache',array('adapter'=>'mecached'));
$this->cache->memcached->save('foo', 'bar', 10);
echo $this->cache->memcached->get('foo');

You can find the details of Cache plugin in CI at http://ellislab.com/codeigniter/user-guide/librarie/caching.html

Sunday, May 13, 2012

Strategy to handle worker threads in php and create daemon

If you are working on a project which requires fair amount of background work to be done, then you must have seen the requirement of keeping background threads separate. Unfortunately, there is no explicit way of threading in php (there are a number of way around to do this, but those to me look like hacks rather a supported feature). Such needs are normally seen in a project which requires some work to be done which is not needed immediately. For example, if a user uploads a picture and you want to crop that picture, or, you want to send some sort of notification email etc. This is a classical case of having a worker thread doing all these tasks in parallel. There are a number of open source libraries available which take care of such things e.g. https://github.com/pda/pheanstalk . But if you want to do this yourself, then here is a simple strategy.

  1. Create a queue in memcache or add the jobs in some table in DB
  2. Create a php script which takes a job out from memcache queue to from the table in DB and executes the job
  3. Run the php script as a background thread.

 First two points are fairly simple. So, lets talk about third point now. How would you run the php script as a background thread. There are two ways in linux to do this. One is to run the script as a cron. To know how to run a script as a cron job, refer to my post here => http://saadnawaz.blogspot.com/2012/05/create-cron-job-in-linux.html. Now, if you think that your job is something which can run after 1 minute, then simply write the php script and add entry in the crontab. Though, in most of cases, 1 minute is just a bit too much delay. So, the next option is creating a daemon. Daemon is a process which runs in the background. What you should be doing is running the worker php script as a daemon. Follow the following steps to do that:(this is just one way of creating a daemon, there are other ways as well, but this seems simplest to me)

1. Create a shell script which executes the php script file, which is gonna be something like:

while true
do
     php /pathtofile/filename.php
     sleep 5
done

What this shell script is doing is fairly straight forward. You have an infinite loop which runs a php script file, and after than sleeps for 5 seconds. So, basically you are achieving something like cron, but you are executing the script every 5 seconds (which cron can't do, since, the granularity is upto minutes).

Since, this is treated as an executable, therefore, make sure you have given appropriate rights on the script and php worker file.

2. Run the shell script as a daemon:

/completePathToFile/shell.sh &

The "&" at the end runs this as a daemon.

Now, keep in mind, it's always better to use an existing solution rather reinventing the wheel. But, if your problem is not big enough to use open source solutions, then the above strategy should get you started.

Sunday, January 22, 2012

A simple strategy for time localization

If you are building a webapp which is dependent on time (for example, a bidding or betting application) then you must have seen the requirement to show time on the webapp depending on the timezone of the logged in user. The other day i was going through various blogs and i saw a couple of posts by different blogs covering this approach and i was amazed to see that how complex route they took. So, i thought to write a post describing some really easy steps to achieve this.
There are multiple decisions/questions that you have to answer in order to achieve this goal.

1. In what timezone will you save the time in your db?
2. How would you get user's timezone?
3. When do you want to change the timezone according to user's timezone?

In this post i'll go through each of the above questions one by one.

In order to answer the first question, the best option is to go for GMT/UTC timezone. The reason is that it's extremely easy to convert time from GMT to GMT+8 or GMT0-5 etc. You can simply add/subtract the difference from the timestamp. But, you have to consider another thing here, if you are hosting your webapp on a shared server, then you need to consider the timestamp your shared hosting server is using. Because for any time critical webapp, you'll be frequently getting the current time and the server will be returning you the timestamp depending on the timezone it has set. Most of the shared hosting servers don't allow you to change the timezone. Now, you can also keep GMT/UTC timezone as the default timezone and you can change the timezone of the current time as well. Both are valid ways,  so it's up to you what to go for. Now, whenever user enters some datetime, you convert the datetime entered into the default timezone and save it in your db.

Now, the second question, i.e. how would you get user's timezone. Now there are a couple of ways to achieve this.

1. Ask the user for his timezone upon registration and use that
This is a fairly popular and accurate method of getting user's timestamp. The only problem in this approach is that it's not dynamic, i.e. if the user moves to a different timezone, he'll have to manually change his timezone on your webapp. If you don't mind putting your users through this step, then this method is recommended.

2. Get the timezone from the ip of the user
This is another method of getting the timezone of the logged in user. You can use ip of the user to track his geolocation and from that you can determine his timezone. Though, personally i don't think this is a good approach to go for. In my personal opinion it looks like an over kill unless you are already tracking and showing data on the basis of user's geolocation.

3. Get the timezone of the user through javascript.
I personally like this method because of its simplicity. You can easily get the timezone of the logged in user through following steps.
  • Get the timezone of the logged in user on your main page. For this i saw such complex approaches that i was amazed. Certainly some people love to bring gun to a knife fight :s .You can achieve this through one line of the following code
    • - (new Date.getTimezoneOffset()/60)
      • This method basically returns the difference between GMT and local time in minutes. So, if you are at GMT+2 then Date.getTimezoneOffset() will return -120 and if you are at GMT-2 then it will return 120. Therefore, simply put a - before it and divide the result by 60 and you'll get the time difference in hours. 
  • Make an ajax call and send this time difference on some server page and store it in session or cookie. A simple snippet of the code is
                         <?php 
             session_start();
             $_SESSION['userTimeZone'] = $_GET['utz'];
           ?>
Now, you have user's timezone saved in session. Whenever, you want to display a time, simply convert the stored time into user's timezone. Now, again there are multiple ways to achieve this. One very simple way is to save user's timezone in terms of seconds and simply add/subtract from the stored timestamp (if you used GMT as your default timezone). Or, you can use the following code to achieve this as well. (in order to use the following code you need to save user's timezone in proper format i.e. GMT+2)

public function convertTimeZone($date, $from_tz, $to_tz, $dateFormat) {
    $dateObj = new DateTime($date, new DateTimeZone($from_tz));
    $dateObj->setTimezone(new DateTimeZone($to_tz));
   
    return $dateObj->format($dateFormat);
}


And there you go, it's as simple as that.

Friday, November 5, 2010

HTML_Template_IT

If you are working with a large web application, then you must keep the user interface and the data separate. A very good open source template method for this purpose is HTML_Template_IT. I found a very good and nice tutorial on the same, so thought of sharing it. View the following URL to see the tutorial.

http://www.weberdev.com/ViewArticle/Using-PEAR-HTML_Template_IT-For-Modular-Interface-Design