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

upstream backend {
   server weight=5;
   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.

Architecture of Apache Lucence


Architecture of Lucence consist of:

Document: It is a main data carrier used during indexing and search, containing one or more fields, that contain the data we put and get from Lucene.

Field: It is a section of the document which is built of two parts: the name and the value.

Term: It is a unit of search representing a word from the text.

Token: It is an occurrence of a term from the text of the field. It consists of term text, start and end offset, and a type.

Apache Lucene writes all the information to the structure called inverted index. It is a data structure that maps the terms in the index to the documents, not the other way round like the relational database does. You can think of an inverted index as a data structure, where data is term oriented rather than document oriented.


Each index is divided into multiple write once and read many time segments. When indexing, after a single segment is written to disk, it can’t be updated. For example, the information about deleted documents is stored in a separate file, but the segment itself is not updated. However, multiple segments can be merged together in a process called segments merge. After forcing, segments are merged, or after Lucene decides it is time for merging to be performed, segments are merged together by Lucene to create larger ones. This can be I/O demanding; however, it is needed to clean up some information because during that time some information that is not needed anymore is deleted, for example the deleted documents. In addition to this, searching with the use of one larger segment is faster than searching against multiple smaller ones holding the same data. However, once again, remember that segments merging is an I/O demanding operation and you shouldn’t force merging, just configure your merge policy carefully.

AngularJS vs. Ember.js: Which JavaScript Framework Is Best For You?

A lot has changed since the early days of the web when a website would make a single request to the server, which would respond with the entire webpage to be displayed. Back then, the client-side of an application was a paper-thin veneer of HTML, query parameters, cookies, and request headers—and servers did all the heavy lifting.

It’s a very different story today. The front-end of modern websites is now complex enough to handle much of the magic that allows single page applications (SPAs) to deliver the sleek “desktop-like” user experiences that make them so popular. In this article, we’ll look at two of the most popular JavaScript frameworks available for building SPAs—AngularJS and Ember. Both are open-source frameworks based on the model view controller (MVC) design pattern that use wildly different design philosophies to achieve their goals.

Angularjs Vs EmberJs

Read on to learn more about these two competing frameworks.

What Is AngularJS?

AngularJS is a comprehensive, open-source JavaScript framework that solves the problem of developing SPAs by extending the functionality of HTML with directives. AngularJS famously describes itself as “what HTML would have been, had it been designed for building web apps.” The framework places an emphasis on simple modular code and test-driven development.

Some of the key technical features that differentiate AngularJS from Ember are:

Simplified syntax by using vanilla JavaScript objects for modelsDOM-based templating with directivesDependency injectionMore flexible opinionation

AngularJS places an emphasis on getting your app up and running quickly. It opts for syntactic simplicity by using JavaScript objects for models. However, this comes with the performance tradeoff of relying on “dirty checking,” in which a deep comparison on all models within the view must be performed.

Angular developers must be wary of the number of bound objects within the view in order to avoid bogging down the application’s digest cycle. This isn’t usually an issue for most SPAs, but it is the major reason the newly released Angular 2.0 added server-side rendering and one-way data binding, among other major rewrites.

What Is Ember?

Ember combines proven concepts from native frameworks like Apple’s Cocoa with the lightweight sensibilities of open-source frameworks like Ruby on Rails and Backbone.js to create an open-source JavaScript framework that can scale with an entrepreneur’s ambitions. Like AngularJS, Ember is a full-featured framework that specializes in making dynamic, beautifully rendered SPAs. Let’s take a look at some of the key factors that differentiate Ember from AngularJS:

Avoids “dirty checking” by using accessorsString-based templating system with HandlebarsHigh degree of opinionationMore powerful routing at the expense of added complexity

Ember emphasizes scalability—it’s meant for apps that plan to scale into much bigger projects, and like a concerned parent, it enforces stricter rules on how you write your code to ensure that your application avoids bottlenecks and is primed for growth.

By opting for a string-based templating system like Handlebars, it’s possible to achieve quicker boot times by pre-compiling templates on the server. Server-side rendering also has the SEO (search engine optimization) advantage of natural indexing by Google crawlers—AngularJS by comparison must boot an entire browser environment called PhantomJS, which can really put a drain on resources. The tradeoff? The code is more complex.

Which Framework Is Right for Your Needs?

Both AngularJS and Ember serve a similar singular purpose—to make the development of dynamic SPAs with engaging UI/UX faster and easier for the developer. That means both offer perks like two-way data binding, DOM manipulation, easy unit testing, modular code, and the benefits of the MVC architecture. Where they differ is in their design philosophies and goals.

Use AngularJS If…

You’re starting a new project from scratch, time is at a premium, and your application is a small to medium-sized app. These applications are unlikely to run into the “dirty checking” bottleneck, meaning you’ll be able to take full advantage of the simplicity and coding speed that comes with using vanilla JavaScript objects as models. AngularJS is also a good choice if you like the feel of manipulating the DOM with an extended HTML syntax or wish to take advantage of the much larger community.

Even if you’re feeling ambitious, it’s worth noting that with the release of Angular 2.0 it’s now possible to take advantage of server-side rendering and avoid the pitfalls of “dirty checking,” provided you’re willing to tackle the learning curve that comes with a major rewrite.

Use Ember If…

You’ve got big plans for your app and want to make sure you build your SPA right from the bottom up. Frameworks exist to help developers work in accordance with best practices and avoid coding themselves into a bottleneck. Ember was designed with the mindset of “standing on the shoulders of giants” and it really shows within the careful (albeit verbose) syntax of this framework.

Other reasons to consider Ember—even if your application is to remain smaller—is that it offers faster boot times and inherent stability. With the recent release of Ember 2.0, the framework has been modified to bring out the best of Glimmer, Ember’s blazingly fast rendering engine.

A Brief Word About 2.0

While Ember 2.0 has been out since 2015, Angular 2.0 was just released on May 2, 2016, so be sure to give it a little more time to mature. We’ll cover the next generation of Ember and Angular in a future post once these new releases have had a chance to grow into themselves.