Tag Archives: PHP

Optimizing variables cache in Drupal 6

In Drupal 6, a number of caching strategies are incorporated to handle large traffic. One of them is the serialization of the whole variable table. It is being cached in the database and gets extracted into global $conf variable in each invoke.

In one of our production sites, we faced hard time to keep up with the memory requirement of PHP for the unserialization of this variable from the cache. The variables table was so large that we had to assign around 1GB memory to each PHP thread so that the value can be unserialized without memory exhaustion. This made it much harder to scale the application.

So, we decided to do something about it and successfully handled it by doing the following:

1. First of all, we installed the memcache module to move the cache storage from DB to memory

2. We then edited the memcache module’s cache_get and cache_set functions to store/retrieve individual items from the variables array and split/join them when requested.

3. This requires a memcache call for each of the items in the variable array, but consumes a small amount of memory as there is no huge unserialize operation going on.

4. We performed a few tests to see if the site is working as before, and found its working perfectly!

Here is the code in case you are facing similar issue: Continue reading

Using Mockery as a mocking framework with PHPUnit

A few days ago I was explaining mocking to a few colleagues. I came up with the following quick n dirty code to show them the elegance of Mockery as a mocking framework.

The code is straight-forward: it checks the health of a server using a tiny heart beat script.

1. The script residing in the remote server:

/remote/heart.php

$response = array('status' => 'online');

header("Content-type: application/json");
echo json_encode($response);

2. The class that tries to fetch the status from the remote server:

/test/Heartbeat.php

class Heartbeat
{
    private $http;

    public function __construct(Http $http)
    {
        $this->http = $http;
    }
    
    public function checkHealth()
    {
        $url = 'http://localhost/remote/heart.php';
        $response = $this->http->getResponse($url);

        $beat = json_decode($response);
        return (!is_null($beat) && $beat->status == 'online');
    }
}

Continue reading

Node access rebuild using Drush

In one of our Drupal production site, we have around 84K nodes. Periodically we need to rebuild the content access permission, which takes around 6 hours to complete when done through the browser. Being very unhappy with it, today found the following drush use:

Emrans-MacBook-Air ~: drush php-eval 'node_access_rebuild();'

The results were immediate, the whole rebuild now takes only 20 minutes!

A clean way of integrating PHPUnit 3.5.x with CodeIgniter 2.x

Now a days, my default choice of framework is always Zend Framework. However, I have to maintain a couple live projects in CodeIgniter from early days. I feel its very important to have tests around critical applications, so I have attempted a couple times to integrate PHPUnit with CodeIgniter but failed every time – well, until now.

I’ve managed it this time with hooks. It provides a clean way of bootstrapping the framework and then performing tests on the Model layer – for me testing the model layer has been sufficient. The use is very simple as it does not require any change in how a regular CodeIgniter application is built.

Grab the code from github.

Example – /tests/PostTest.php

<?php

class PostTest extends PHPUnit_Framework_TestCase
{
    private $CI;

    public function setUp()
    {
        $this->CI = &get_instance();
        $this->CI->load->database('testing');
    }

    public function testGetsAllPosts()
    {
        $this->CI->load->model('post');
        $posts = $this->CI->post->getAll();
        $this->assertEquals(1, count($posts));
    }
}

Continue reading

Quick start on new Facebook PHP SDK (IFrame based)

This post is more than couple year old. It solved the issues when the SDK was first released and facebook had lack of documentation. However, now facebook has very rich set of documnetation and you should follow that instead!

The new Facebook API has already spread over the application developers and if you’re like me, you’ve already got your hands dirty to see how this new thing works. If you have tried to follow the documentation to authorize/get session in your canvas application, it is likely you have already hit roadblocks. Well, I am no savior but I have glued together a few clues and got it working for myself.

I am assuming that you have already created your application by following the Getting Started section from the official documentation. Also, this is for IFrame based applications only.

Enough talking, let’s get some code.

Step 1: Get the new SDK

Download the new SDK from github. We will only need the facebook.php file from the src folder. In our project directory, let’s create a folder called “lib” and put the file there.

Step 2: A configuration file

Let’s now create a configuration file to store our facebook configuration. Let’s name it config.php. Here goes the source:

<?php

define("FACEBOOK_APP_ID", '113795715321151');
define("FACEBOOK_API_KEY", '064baf5fb98de050cd7b9a001ca1988b');
define("FACEBOOK_SECRET_KEY", '430f43c01f6dfe02c284b4545976f9ce');
define("FACEBOOK_CANVAS_URL", 'http://apps.facebook.com/emran-test-app/');

Step 3: Application Main Page

This file will be the main entry point to our facebook application. It just instantiates the facebook object, sets the configuration and checks for a valid session. If it does not find a valid session, it redirects to the login page. For first time visitors, it will be the authorization page. On later requests, the operation will occur in the background – without any user interaction.

<?php

include_once 'lib/facebook.php';
include_once 'config.php';

$facebook = new Facebook(array(
    'appId'  => FACEBOOK_APP_ID,
    'secret' => FACEBOOK_SECRET_KEY,
    'cookie' => true,
    'domain' => 'phpfour.com'
));

$session = $facebook->getSession();

if (!$session) {
    
    $url = $facebook->getLoginUrl(array(
        'canvas' => 1,
        'fbconnect' => 0
    ));

    echo "<script" . " type='text/javascript'" . ">top.location.href = '$url';</script>";

} else {

    try {

        $uid = $facebook->getUser();
        $me = $facebook->api('/me');

        $updated = date("l, F j, Y", strtotime($me['updated_time']));

        echo "Hello " . $me['name'] . "<br />";
        echo "You last updated your profile on " . $updated;

    } catch (FacebookApiException $e) {

        echo "Error:" . print_r($e, true);

    }
}

Continue reading

Enterprise PHP

I presented this talk on the Soft Expo 2010 – the largest software fair in Bangladesh. The intention was to clear some of the misconception about PHP, the growth of PHP, how it can fit in the enterprise now, etc.

After these, I shed light on some topics that a company/developer should keep in mind in order to write good software in PHP. This was followed by live session on caching, mysql query optimization, use of Xdebug, etc.

So here goes the presentation:

And a big thanks to Ivo Jansch’s “PHP in the real wolrd” presentation, from where I took inspiration.

Cheers!

Changing the default controller naming convention in CodeIgniter

CodeIgniter is one of my favorite framework and I often use it for developing application quickly. Although it is very flexible in most cases, I find its naming convention to be strict. Many times I have faced this problem when my controller’s class name and a model/library’s class names are the same – a Fatal error is inevitable and I have to forcefully change the name of the conflicting class to something less desirable (say from Users to UsersModel). Today I wanted to end this problem.

So I extended the CI_Router core class and made change to the _validate_request method. Now I can name my controller classes in this fashion: UsersController and it resides on the file system as controllers/UsersController.php. If you’ve tried other established frameworks, you should notice that this naming convention is widely used. So, if you have the same need, then just download the MY_Router.php file and put it on your application/libraries folder. That’s it.

Here is how your controller would start:

[cc lang='php']
< ?php

class UsersController extends Controller
{
public function __construct()
{
parent::__construct();
}
}
[/cc]
Continue reading

phpXperts ’09 seminar

At last the phpXperts seminar on “Current Web Trends” have taken place and I was one of the speakers there. Among all the topics, mine was a bit suggestive and naturally a bit less exciting. I spoke about how to become a PHP ninja – what are the characteristics they posses, what are the tools they use, what are the paths they follow etc. It’s actually a follow-up of one of my blog posts: “Becoming a kick-ass PHP ninja“.

Here goes the slides:

All the other slides, pictures, and videos are available here.

Enjoy!

Using Twitter for sending server downtime alert

Today I’ve written this simple PHP script to alert me through Twitter whenever our company’s local server is down. The script is called by a cron every 5 mins in my central hosting. Without much babble, here goes the code (if you’re interested to know why I needed this, that’s at the bottom of the post):

<?php

// Specify the target URL in your server
$targetUrl  = 'http://YOUR_SERVER_URL';

// Specify what the response is from the server
$targetText = 'Hello from Daredevil';

// We will be using cURL for fetching the content
$ch = curl_init();

// Set the params
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Get the response
$response = curl_exec($ch);
curl_close($ch);

// Are things in right place ?
if ($response == $targetText) {
    die('Site is up and running!');
}

// Nope, so here are the sender's twitter info
$username = 'SENDER_TWITTER_USERNAME';
$password = 'SENDER_TWITTER_PASSWORD';

// Receiver's twitter username
$receiver = 'RECEIVER_TWITTER_USERNAME';

// Alert message to send
$message = 'Daredevil is not responding, please fix ASAP!';

// The Twitter API address (new direct message)
$url = 'http://twitter.com/direct_messages/new.json';

// We will be using cURL for this
$ch = curl_init();

// Set the params
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$receiver&amp;text=$message");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

// Send the request
$response = curl_exec($ch);
curl_close($ch);

// Success or failure
if (!empty($response)) {
    echo 'Recipient has been notified.';
} else {
    echo 'No response from twitter.';
}

Why I needed this?

Recently we have setup a server at our office for committing work to a local SVN repository and have the QA test our work whenever they are ready. We also have a staging server where we do SVN update from this repo. Now, for the last few days, I’ve found the local server to be off due to a few reasons – but every time I realized this at night when I am back home and can’t do anything to turn it on. So I thought about this Twitter alert which is sent to my cell phone immediately when the server goes offline.

Btw, if Twitter doesn’t send SMS to your country, don’t worry. Check out the excellent service at Twe2 that I’ve been using for a couple days.

Cheers!