YACassandraPDO : How to fetch UUID column from cassandra table

It is observer that when we fetch the UUID field using YACassandraPDO driver in PHP it fetches the garbage. for example

select dateof(uuidfield) as theTimeStamp from table;

output will be :

array(1) {
array(2) {
string(8) "�;e$��"
string(8) "�;e$��"


array(1) {
array(2) {
string(8) "2012-12-04 10:00:00+0100"
string(8) "2012-12-04 10:00:00+0100"

For timestamp, pdo returning the hexodecimal string. You can use below function to convert it back to date string.

function getDateStringFromHex($str) {
$date = unpack('H*', $str);
$time = hexdec($date[1]) / 1000;
$dateStr = date('Y-m-d H:i:s', $time);
return $dateStr;

Achieve Best Performance with PHP7 + NGINX

I don’t know much about hhvm..but i can help you with apache,nginx and php7.

I have used php7 + nginx combination and achieved around 1Million request per second in our stress and mixed load testing.

I have also tested same thing with apache2, Apache faces what is called the C10K problem – strictly speaking, difficulty supporting more than 10,000 connections at a time. (Apache falls well short of this goal.) Apache allocates memory to every additional connection, so it tends to start swapping to disk as concurrent connections increase. This sends site performance into a downward spiral and can lead the entire server to crash or freeze.

In opposite to that,NGINX runs an ongoing event loop that handles requests as they occur, without allocating resources to the requestors.

Nginx also has strong caching mechanism. It can be used for caching static as well as dynamic files. CloudFlare, a widely used CDN, uses NGINX as its operating system.

PHP 7 is said to be twice as fast as previous versions of PHP, and to use considerably less memory. It’s uses Abstract Syntax Tree mechanism for compilation which boost performance.It also has internal opcode caching feature.You can also use generator(yield) feature to perform co-operative parallel processing.

In order to get best performance.you have to fine tune your database,code and logic.keeping database connection persistent always help to increase throughout.

Memcache or redis Always plays important role in caching your results ,which will boost your performance.

At last most important key factor is infrastructure.You will need high end cpu in order to achieve best performance.

PHP 7 Performance with NGINX: Web Serving & Caching

PHP : Predefined Interfaces and Classes

Advance PHP consist of some interesting concepts. Let’s us learn them in this post


First of all. Let start with OOPS basics,

What is an Interface???

It is similar to class, it is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Along with abstract methods an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

What is an class ?

In object-oriented programming , a class is a template definition of the methods and variables in a particular kind of object . Thus, an object is a specific instance of a class; it contains real values instead of variables.

So we have some predefined Interfaces and Classes in PHP, Like

The Traversable Interface :

In PHP, there is foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Traversable Interface to detect if a class is traversable using foreach.

Traversable is Abstract base interface that cannot be implemented alone. Instead it must be implemented by either IteratorAggregate or Iterator.

The Iterator Interface :

Iterator Interface extends the Traversable Interface.

Traversable Synopsis

Iterator extends Traversable {
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )

Iterator::current — Return the current element
Iterator::key — Return the key of the current element
Iterator::next — Move forward to next element
Iterator::rewind — Rewind the Iterator to the first element
Iterator::valid — Checks if current position is valid

PHP already provides a number of iterators for many day to day tasks. See SPL iterators for a list.

The IteratorAggregate interface :

IteratorAggregate Interface extends the Traversable Interface.

IteratorAggregate extends Traversable {
/* Methods */
abstract public Traversable getIterator ( void )

IteratorAggregate::getIterator — Retrieve an external iterator

Example how to use IteratorAggregate Interface

// IteratorAggregate
// Create indexed and associative arrays.

class myData implements IteratorAggregate {

    private $array = [];
    const TYPE_INDEXED = 1;
    const TYPE_ASSOCIATIVE = 2;

    public function __construct( array $data, $type = self::TYPE_INDEXED ) {
        while( list($k, $v) = each($data) ) {
            $type == self::TYPE_INDEXED ?
            $this->array[] = $v :
            $this->array[$k] = $v;

    public function getIterator() {
        return new ArrayIterator($this->array);


$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',], /*TYPE 1 or 2*/ );

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo PHP_EOL;

// if TYPE == 1
#string(3) "php"
#string(10) "javascript"
#string(2) "c#"
#string(4) "java"

// if TYPE == 2
#string(3) "one"
#string(3) "php"
#string(10) "javascript"
#string(5) "three"
#string(2) "c#"
#string(4) "java"
The Throwable Interface

PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

Exception is the base class for all Exceptions in PHP 5, and the base class for all user exceptions in PHP 7.

In PHP 7, Exception implements the Throwable interface.

Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.

Throwable Interface Synopsis

Throwable {
/* Methods */
abstract public string getMessage ( void )
abstract public int getCode ( void )
abstract public string getFile ( void )
abstract public int getLine ( void )
abstract public array getTrace ( void )
abstract public string getTraceAsString ( void )
abstract public Throwable getPrevious ( void )
abstract public string __toString ( void )

Exception implements Throwable Interface

Exception {
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public mixed getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
 The ArrayAccess Interface:

Interface to provide accessing objects as an arrays

Interface Synopsis

ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )

It consist of Abstract Method like

ArrayAccess::offsetExists — Whether an offset exists
ArrayAccess::offsetGet — Offset to retrieve
ArrayAccess::offsetSet — Assign a value to the specified offset
ArrayAccess::offsetUnset — Unset an offset

The Serializable Interface

This method is used for customized serializing.

Serializable {
/* Methods */
abstract public string serialize ( void )
abstract public void unserialize ( string $serialized )

The Closure Class

Class used to represent anonymous functions.

Now what is anonymous functions ???

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

$greet = function($name)
    printf("Hello %s\r\n", $name);


Closures Synopsis

Closure {
/* Methods */
private __construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] )
public Closure bindTo ( object $newthis [, mixed $newscope = "static" ] )
public mixed call ( object $newthis [, mixed $... ] )

Closure::__construct — Constructor that disallows instantiation
Closure::bind — Duplicates a closure with a specific bound object and class scope
Closure::bindTo — Duplicates the closure with a new bound object and class scope
Closure::call — Binds and calls the closure

Example to delete a directory with all subdirectories and files:

$deleteDirectory = null;
$deleteDirectory = function($path) use (&$deleteDirectory) {
    $resource = opendir($path);
    while (($item = readdir($resource)) !== false) {
        if ($item !== "." && $item !== "..") {
            if (is_dir($path . "/" . $item)) {
                $deleteDirectory($path . "/" . $item);
            } else {
                unlink($path . "/" . $item);

The Generator Class

It return generator object

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

A simple example of this is to re-implement the range() function as a generator. The standard range() function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling range(0, 1000000) will result in well over 100 MB of memory being used.

Fibonacci generator:

function fib($n)
    $cur = 1;
    $prev = 0;
    for ($i = 0; $i < $n; $i++) {
        yield $cur;

        $temp = $cur;
        $cur = $prev + $cur;
        $prev = $temp;

$fibs = fib(9);
foreach ($fibs as $fib) {
    echo " " . $fib;

// prints: 1 1 2 3 5 8 13 21 34

Hope you like this post. Please do share you reviews in below comments section

8 Tips for Boosting Drupal 8 Performance using Nginx

Drupal is a leading open-source content management system.Drupal is used for everything from personal blogs to gigantic enterprise and governmental projects, and other complex work.

Drupal is based on PHP, a scripting language which is easy to learn and easy to use for rapid prototyping, followed by a quick move to production. However, the basic operation of PHP can contribute to performance problems when a site needs to be able to scale rapidly due to short-term spikes in usage or long-term growth.

Also, most Drupal sites use the Apache HTTP Server web server, which has its own performance limitations. The tips in this blog post show how to solve common performance problems that face Drupal-based sites. With some imagination and hard work, sites can be quickly re-architected to remove performance bottlenecks and lay the groundwork for growth up to many times current traffic volumes.

Tip 1 – Plan Your Site Architecture

Most Drupal sites initially use Apache HTTP Server as their web server. Apache is used among a wide range of websites, and instructions for configuring it are widely available. However, as websites grow in performance, many sites move to NGINX. NGINX is the leader at busier sites (the top 100,000 sites, top 10,000 sites, and top 1,000 sites).

Apache and Drupal share similar problems when a site gets busier:

Apache faces what is called the C10K problem – strictly speaking, difficulty supporting more than 10,000 connections at a time. (Apache falls well short of this goal.) Apache allocates memory to every additional connection, so it tends to start swapping to disk as concurrent connections increase. This sends site performance into a downward spiral and can lead the entire server to crash or freeze.
Drupal does a fair amount of work to serve each request that it receives, with each request consuming memory and CPU time. Similarly to Apache, but at a much lower number of connections, Drupal site performance can fall into a downward spiral.
Also, when an application server also handles Internet traffic and other functions, it becomes a potential problem in multiple ways. It’s vulnerable to all of the different kinds of problems that a website can have, represents a single point of failure, and needs to be optimized for incompatible tasks, such as fast responsiveness to Internet requests, fast application processing, and fast disk access, as well as high security.

So to address performance bottlenecks as a site grows, you can take several separate but related steps, as described in this blog post:

Replace Apache with NGINX as the web server for your Drupal site. This improves performance and sharply reduces memory utilization when many thousands of connections run concurrently.
Implement a reverse proxy server. NGINX is a very popular reverse proxy server for Drupal sites and for sites of all kinds. Implementing a reverse proxy server removes the burden of handling Internet traffic from your application server and allows other performance-enhancing steps: caching of static files and the use of multiple load-balanced application servers.

Monitor traffic among servers. Once you’re running multiple servers, you need the ability to monitor performance across them.

Note: You can implement NGINX as a reverse proxy server with either Apache or NGINX as your web server. Decoupling these two functions can simplify implementation.


Tip 2 – Replace Your Web Server

The easy way to support multiple connections is to fork a new process for each new connection. This gives you access to all the capabilities of Apache for each new connection. However, the resulting connections are “heavy” – each connection has non-trivial start-up time, debugging complexity and, most importantly, memory requirements.

NGINX was developed to eliminate the overhead that this simplistic approach incurs. NGINX runs an ongoing event loop that handles requests as they occur, without allocating resources to the requestors.

So simply replacing Apache with NGINX is a “quick fix” for performance issues. You can make this change without changing your actual application code.


Tip 3 – Rewrite URLs

There is a configuration issue that arises when replacing Apache with NGINX. If site layout is complex, it’s desirable to display a simplified, user-friendly URL. Short URLs are a vital component for security, flexibility, and web usability.


In most web servers, URL rewriting is accomplished via the mod_rewrite module in the .htaccess (hypertext access) file, which is a directory-level configuration file.


The following NGINX rewrite rule uses the rewrite directive. It matches URLs that begin with the string /download and then include the /media/ or /audio/ directory somewhere later in the path. It replaces those elements with /mp3/ and adds the appropriate file extension, .mp3 or .ra. The $1 and $2 variables capture the path elements that aren’t changing. As an example, /download/cdn-west/media/file1 becomes /download/cdn-west/mp3/file1.mp3.

server {
   rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
   rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  last;
   return  403;

Tip 4 – Deploy a Reverse Proxy Server

A reverse proxy server receives requests from browsers and then does not just immediately process them. Instead, the reverse proxy server examines each request and decides, Solomon-like, what to do with it: either carry out the request itself or send it to another server for fulfillment.

The reverse proxy server communicates with the application server quickly, over a local area network. When the application server finishes a request and hands the result back to the reverse proxy server, it doesn’t have to wait to communicate with the actual client over the Internet; instead, the application server can go right back to handling the next application-related request. The reverse proxy server then sends the response back to the client.


Inserting a reverse proxy server can immediately “rescue” a site that’s tipping over due to excessive traffic, security problems (which can now be addressed away from the application processing), or other issues. The reverse proxy server also introduces new flexibility into the site architecture. The new capabilities include:


» Caching static files
» Caching dynamic files/Microcaching
» Load Balancing
» Scalability
» Security management
» Security protocol termination.
» Monitoring and Management
» flexibility and redundancy Management


Tip 5 – Cache Static Files

The more common – nearly ubiquitous – use for NGINX as a reverse proxy server is to use it for caching of static files: graphics and code files – JPEGs, PNGs, CSS files, JavaScript files, and the like. This is very easy to do. It gets the cached files to the user faster and offloads the Drupal server from a significant number of transactions per pageview.

The following configuration block sets up NGINX caching. The proxy_cache_path specifies where cached content is stored in the local file system and allocates a named zone in shared memory. The proxy_cache directive is placed in the context that you want to cache for and references the shared memory zone. For more details, see this article on NGINX content caching.

http {
   proxy_cache_path /data/nginx/cache keys_zone=one:10m;

   server {
       proxy_cache one;
       location / {
           proxy_pass http://localhost:8000;

For further caching efficiency for static files, consider a content delivery network (CDN). CloudFlare, a widely used CDN, uses NGINX as its operating system.


Tip 6 – Cache Dynamic Files

Drupal handles caching of PHP-generated web pages for you, and this can significantly improve site performance. As with microcaching for any platform, users don’t all get a newly created version of the web page; instead, they get a copy that’s perhaps a second or ten seconds old. This is usually not a problem, and is preferable to having your overall site performance begin to slow as traffic increases. (In which case, users are not getting fresh content for a different, and worse, reason.)

There are two problems with Drupal’s caching. First, Drupal is not efficient at caching. Second, when Drupal is getting overloaded, even the work needed to retrieve cached pages is significant. Whereas, with NGINX, you have a powerful and useful option: bypassing Drupal caching completely.

That’s right – NGINX handles both static file caching and PHP page caching.

Tip 7 – Use Multiple Application Servers and Load Balancing

With a single application server, you only have what’s called vertical scalability: to get more performance, you need a bigger, faster server. This approach is potentially expensive, because the biggest, fastest servers are disproportionately expensive. It’s also inherently limited, because a single device always has an inherent performance limit. When you need more performance, you have to upgrade or replace your current device, a disruptive operation.

Implementing a reverse proxy server, as described in Tip 2 above, allows you to use multiple application servers, giving you horizontal scalability: to get more performance, just add more servers. With the right software tools, such as those found in NGINX Plus, adding and removing servers can be done with no downtime at all.

However, when there are multiple application servers, there has to be some technique for deciding which server gets the next request. This is called load balancing, and techniques range from the simple – a round-robin approach where the next request goes to the next server in line – to sophisticated techniques in which the system checks servers to see which one is least busy (and therefore most available) before forwarding a request.

Load balancing can be performed by hardware appliances or by software load balancers running on standard hardware. Software-based approaches are more flexible – easily used in customer-owned servers, private clouds, and public clouds.

NGINX and NGINX Plus support five load-balancing methods, plus server weights. Four methods are supported in both open source NGINX and NGINX Plus; the Least Time method is supported only in NGINX Plus:

»Round Robin – Each new request goes to the next server in the list, regardless of how busy each server is.
»Least Connection – The next request goes to the server with the fewest active connections.
»Hash – The next request is assigned based on a user-defined key (generic hash) or the IP address (the IP Hash method).
»IP Hash – The next request is assigned based on the client IP address.
»Least Time (NGINX Plus only) – NGINX Plus tracks response time for forwarded client requests, then combines that with “least connections” information to determine where to send new requests.

The following code shows the weight parameter on the server directive for backend1.example.com:

upstream backend {
   server backend1.example.com weight=5;
   server backend2.example.com;
   server backup;

Tip 8 – Support Session Persistence

Adding multiple application servers introduces a problem: what if your app supports interactive functionality, such as a purchasing session, which assumes that the same server handles all requests for a given user throughout a browser session?

Note: When session persistence is in use, loads are still being balanced, but it’s user sessions that are being allocated across application servers, not individual user requests. For a busy system, the difference in granularity doesn’t have much impact.

Session persistence keeps a specific client assigned to the same server throughout its session. Only NGINX Plus offers session persistence

Cookie insertion. When a client makes its first request, NGINX Plus creates a session cookie and returns it to the client. The client includes it in future requests and NGINX Plus uses it to route those requests to the server that responded to the first request.

Lesser Know Facts About PHP7

PHP 7 would encapsulate for betterment of PHP web development.
Below are some known facts of PHP 7.
  • High Performance : PHP 7 is based on PHPNG or PHP Next-Gen project which ultimately aims to speed up the PHP applications.
  • JIT Engine or Just In Time Engine: It was absolutely for this reason that the new PHPNG has been developed. The purpose is to implement the JIT engine for dynamically compiling the Zend opcodes into native machine code. This would enhance the speed of code compilation and execution. Therefore, speed of implementing the code is drastically improved thereby enabling for faster development processes.
  • Abstract Syntax Tree: Abstract syntax tree is meant to be an intermediary step in the compilation process of PHP. This is said to enhance the speed of PHP further with more optimizations done to the compilation and code execution process. However, in the times to come, AST is expected to be exposed to other PHP extensions as well that could open opportunity for more interesting tools like static code analyzers for the users to utilize for better results with PHP.
  • Asynchronous Programming:Asynchronous programming takes care of event handling which is related to the input-output operations or other tasks that may be going in parallel like file access, database operations, timers and much more. This feature would push up the PHP performance to an extremely new level by allowing the future PHP versions to easily implement the execution of multiple tasks in a parallel fashion.
  • Spaceship Operator, Declarations & Scalar Types: The PHP 7 has introduced a new operator similar to TIE fighter. This operator allows for three-way combined comparisons and specifically for string sorting.