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

Should I use AngularJS or React?

Initially released in 2009, the Google-backed AngularJS has since risen to become the incumbent JavaScript framework of choice for building dynamic single page applications (SPAs) on the web. On the other hand, React was developed and released by Facebook in 2013 and is the relative “new kid on the block.” It brings some revolutionary new innovations to the “view” component of the Model View Controller (MVC) architecture.

While there is indeed some overlap in function, the two technologies are as different as Google and Facebook themselves. AngularJS is a framework, while React is a library. Read on to explore some of the key differences between the two technologies and learn how you can use one or both for your next web project.

AngularJS vs react
AngularJS vs react

WHAT IS ANGULARJS?

AngularJS is a comprehensive JavaScript framework that contains everything you need to set up the client-side of a website. Like all frameworks, it provides a programming pattern or structure (in this case MVC) that helps streamline and standardize the web development workflow.

Some of the key advantages that have helped AngularJS rise in popularity are listed below:

  • Angular directives (extension to HTML)
  • Dependency injection
  • Two-way data binding
  • A solid templating engine
  • On-board form validation

Since AngularJS is a full-sized framework packed with features, let’s focus on how it handles the “V” portion of MVC so that we can make a more appropriate comparison with React.

AngularJS manipulates the DOM (Document Object Model) by extending HTML with directives. Thanks to two-way data binding, any changes to the view are also reflected in the data and vice versa. This has the advantage of reducing much of the programming overhead involved with syncing up the view with the model, which speeds up development time.

While two-way data binding works great for many applications, there are times when it can really start to slow things down—particularly when it has to manipulate or render large blocks of data-heavy content, like a photo gallery or lists containing hundreds of items. For applications like these, you might want to take advantage of Angular’s modularity and swap out the “V” for a more formidable rendering engine like React.

WHAT IS REACT?

React (also known as React.js or ReactJS) is an open-source JavaScript library for rendering views. While full frameworks like AngularJS provide the model, view, and controller, React is a library that caters only to the view. It uses one-way data binding, but with a unique twist that helps it gain a huge performance advantage over competing technologies.

Let’s take a look at some of the key tech differentiators that make React stand out from the rest:

THE VIRTUAL DOM

This is the key piece of tech responsible for the magic behind React’s amazing rendering performance. Instead of manipulating the DOM directly (which can be error prone), React stores two copies of a Virtual DOM, the original and an updated version that reflects changes fed in from the view. The two versions are run through a React function that singles out the differences and outputs a stream of DOM operations that only alter the parts of the view that actually changed. As a result, time and resources are saved, as only the parts that are actually changing are affected by changes in the view.

JSX FILES

JSX files go against the modern tendency to want to keep HTML and JavaScript code separate. This isn’t a bad thing with React’s sleek and simple syntax, however—you end up with a single self-contained component that tells you exactly how it will render in the view. It also helps that it’s optional, so those who are more accustomed to traditional programming paradigms don’t have to use it if they don’t want to.

SERVER-SIDE RENDERING

Server-side rendering also goes against a relatively recent trend of rendering everything on the client-side. React can be rendered on both the client and server, giving greater coding flexibility and giving the Virtual DOM the breathing room it needs to really spread its wings.

REACT NATIVE

Normally when you try to build an app for mobile devices using JavaScript, you have to rely on a cross-platform framework like Cordova or Ionic. While these frameworks can greatly speed up development time, they’ll never be as sleek and smooth as a native app. Enter React Native, a framework that enables you to build components for native UI widgets the same way you build them for HTML. React treats the view layer as a pure output of state, so switching its purpose from the web to mobile is as simple as swapping your tags for tags via thev React Native framework. It also means your mobile app benefits from the same principles that make React so blazingly fast for web applications. JavaScript code will never be as fast as the native code for a device, but for most tasks, React Native is more than capable of delivering a smooth user experience.

WHEN SHOULD YOU USE REACT?

React shines when you have lots of dynamic content changing within the view. Most client-side solutions on the web today struggle with rendering large lists of items within a single view. This “struggle” may be on the order of milliseconds, but in this increasingly digital world, a half a second delay is all it takes to kill your user experience. It’s why sites that have a lot of dynamic, constantly changing, data-intensive content like Instagram or Facebook choose to power their applications with React.

As a library, you can also use React as the view component of AngularJS or other frameworks, because it does not tie you to a specific technology stack. That said, there’s a quickly growing community and a number of existing libraries and add-ons that can help you build an app from scratch. Consider Flux, the application architecture Facebook uses to create an application powered by React. React is also perfect for those familiar with ClojureScript and its immutable data structures—the Om project is the rising star for those looking to build dynamic applications using these technologies.

YOU SHOULD USE ANGULARJS IF…

Development time is at a premium, and you need a full, comprehensive framework that will get you running quickly out of the box. As we mentioned earlier, comparing a library to a framework isn’t really a valid question, as you can always use one with the other.

The real question to ask is when shouldn’t you use React? React is not backwards compatible with browsers older than IE8. Also, the community is young, so it’s possible you’ll have to do a lot of “reinventing of the wheel” in order to get the specific features you’re looking for. It’s also up for debate whether or not installing React is worth the trouble if your project is either a simple webpage or if AngularJS is already more than capable of rendering your view.

With the recent release of Angular 2.0 on May 2, 2016, Angular devotees have another reason to stick with their framework of choice. Angular 2.0 shipped with a huge performance boost, including support for server-side rendering and a similar approach to using one-way data binding to only manipulate the parts of the DOM that need to be changed. However, Angular 2.0 also involved a major rewrite of the framework, so whether you choose to install React or upgrade to the next generation of Angular, there’s still going to be a learning curve to overcome.

Angular Material Autocomplete Example with Ajax Request

Hello Friends,

Today I am going to show you how to make a search page with Auto complete component of Angular Material JS.

So problem statement will be, I need to created an Single Page App where i can search for Movie Poster on basis of Movie Name.

Solution:

Inorder to create a Single Page App, I have used AngularJS, Angular Material JS, Angular Animate for Animation , Angular Aria and Angular Message.

For CSS i have used default css of Angular Material

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css">
      <!-- Angular Material requires Angular.js Libraries -->
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-aria.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js"></script>

  <!-- Angular Material Library -->
  <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.js"></script>

Firstly I have created a template using Default template Code of Angular Material Autocomplete

<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak>
  <md-content class="md-padding">
    <form ng-submit="$event.preventDefault()">
      <p>Use <code>md-autocomplete</code> to search for matches from local or remote data sources.</p>
      <md-autocomplete
          ng-disabled="ctrl.isDisabled"
          md-no-cache="ctrl.noCache"
          md-selected-item="ctrl.selectedItem"
          md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
          md-search-text="ctrl.searchText"
          md-selected-item-change="ctrl.selectedItemChange(item)"
          md-items="item in ctrl.querySearch(ctrl.searchText)"
          md-item-text="item.display"
          md-min-length="0"
          placeholder="What is your favorite US state?">
        <md-item-template>
          <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
        </md-item-template>
        <md-not-found>
          No states matching "{{ctrl.searchText}}" were found.
          <a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
        </md-not-found>
      </md-autocomplete>
      <br/>
      <md-checkbox ng-model="ctrl.simulateQuery">Simulate query for results?</md-checkbox>
      <md-checkbox ng-model="ctrl.noCache">Disable caching of queries?</md-checkbox>
      <md-checkbox ng-model="ctrl.isDisabled">Disable the input?</md-checkbox>
      <p>By default, <code>md-autocomplete</code> will cache results when performing a query.  After the initial call is performed, it will use the cached results to eliminate unnecessary server requests or lookup logic. This can be disabled above.</p>
    </form>
  </md-content>
</div>

for JavaScript

(function () {
  'use strict';
  angular
      .module('autocompleteDemo', ['ngMaterial'])
      .controller('DemoCtrl', DemoCtrl);
  function DemoCtrl ($timeout, $q, $log) {
    var self = this;
    self.simulateQuery = false;
    self.isDisabled    = false;
    // list of `state` value/display objects
    self.states        = loadAll();
    self.querySearch   = querySearch;
    self.selectedItemChange = selectedItemChange;
    self.searchTextChange   = searchTextChange;
    self.newState = newState;
    function newState(state) {
      alert("Sorry! You'll need to create a Constituion for " + state + " first!");
    }
    // ******************************
    // Internal methods
    // ******************************
    /**
     * Search for states... use $timeout to simulate
     * remote dataservice call.
     */
    function querySearch (query) {
      var results = query ? self.states.filter( createFilterFor(query) ) : self.states,
          deferred;
      if (self.simulateQuery) {
        deferred = $q.defer();
        $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
        return deferred.promise;
      } else {
        return results;
      }
    }
    function searchTextChange(text) {
      $log.info('Text changed to ' + text);
    }
    function selectedItemChange(item) {
      $log.info('Item changed to ' + JSON.stringify(item));
    }
    /**
     * Build `states` list of key/value pairs
     */
    function loadAll() {
      var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
              Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
              Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
              Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
              North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
              South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
              Wisconsin, Wyoming';
      return allStates.split(/, +/g).map( function (state) {
        return {
          value: state.toLowerCase(),
          display: state
        };
      });
    }
    /**
     * Create filter function for a query string
     */
    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(state) {
        return (state.value.indexOf(lowercaseQuery) === 0);
      };
    }
  }
})();

Now in above javascript code snippet, there is function “loadAll” which loads all the hard coded state value from variable “allStates” in the array objects.

Now we don’t require hard code value, we need something dynamic like an AJAX request which will request an api for the values.

So, let us modify “loadAll” function, according to our need

I am using OMDB Api for getting Movie Name and Movie Poster.

http://www.omdbapi.com/?s={keyword}

Creating an http Service,

app.factory('AutocompleteSearchService', ['$http', function($http){
    return {
        get: function(text) {
            return $http.get("autocomplete.php?keyword=" + text);
      }
   };
}]);

Using that service in loadAll Function and modify it

  function loadAll(query) {
    AutocompleteSearchService.get(query).success(function(data) {
      var loadItems = [];
      loadItems = data.result.data.map(function(obj){
        return {
          value: obj.title.toLowerCase(),
          display: obj.title
        };
      });
      self.states = loadItems;
    });
  }

Update the self.state variable to empty array object.

before : self.states        = loadAll();

after  : self.states = [];

Call “loadAll” function in “querySearch” function and pass query object to “loadAll” function,

function querySearch (query) {
        loadAll(query);
        //console.log(self.states);
        var results = query ? self.states.filter( createFilterFor(query) ) : self.states,
          deferred;
      if (self.simulateQuery) {
        deferred = $q.defer();
        $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
         return deferred.promise;
      } else {
        return results;
      }
  }

Now hit, CTRL+f5 and check whether Autocomplete is working or not.I hope it will work. if not you can refer example  link .

Now Autocomplete is done, displaying result on selecting the Autcomplete value is remaining, let us finish that also.

update <Body> html below html snippet

<md-card  ng-if="ctrl.displayResult">
 <img ng-src="{{ ctrl.result.image }}" class="md-card-image" alt="{{ctrl.result.display}}" >
 <md-card-content>
   <h2>{{ctrl.result.display}}</h2>
   <p>Card content</p>
 </md-card-content>
 <md-card-footer>
   Card footer
 </md-card-footer>
</md-card>

Update md Autocomplete Template,

<md-autocomplete
          ng-disabled="ctrl.isDisabled"
          md-no-cache="ctrl.noCache"
          md-selected-item="ctrl.selectedItem"
          md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
          md-search-text="ctrl.searchText"
          md-selected-item-change="ctrl.displaySearchedResult(item)"
          md-items="item in ctrl.querySearch(ctrl.searchText)"
          md-item-text="item.display"
          md-min-length="0"
          placeholder="Search">
        <md-item-template>
          <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
        </md-item-template>
      </md-autocomplete>

if you check mdAutoComplete snippet, you will find a small change which is,

md-selected-item-change=”ctrl.displaySearchedResult(item)

displaySearchedResult(item)” is a function need to be create in a controller, by default “mdAutoComplete” directive will pass the selected item in “displaySearchedResult” function.

function displaySearchedResult(selectedItem) {
       self.displayResult = true;
       self.result = selectedItem;
  }

Now hit CTRL+F5 and you are done.

So we have completed our problem statement successfully.In case you are not able to achieve it. I am providing a link of an example.

Thank for Reading.

 

ReactJS Fundamentals – 100% free Online Course

ReactJS

This course is for front-end developers who want to get a head-start in ReactJS by learning the fundamentals as quickly as possible.

Students who take this course will learn to use React components, JSX and React’s top-down design methodology to build interactive interfaces while cutting down on code complexity.

The course is presented in a series of videos, quizzes and coding exercises. Students can choose to code along with the lectures, or download sample code provided with each lecture.

The course dives straight into a simple demonstration application to provide an overview of React concepts, all of which are explored later in the course in detail as students build the second, larger example application.

If you want to get up to speed in ReactJS as quickly as possible, this is the course for you!

What are the requirements?

  • You should have a basic understanding of Javascript.
  • You should be understand how HTML, Javascript and CSS work together.
  • You should be comfortable typing code in a plain text-editor and running it in a browser.

What am I going to get from this course?

  • Create web interfaces using React components and JSX
  • Understand the advantage of using React
  • Understand how JSX becomes HTML and Javascript
  • Create reusable components using JSX
  • Reduce code complexity using React’s event model
  • Understand how pages render using React’s virtual DOM

What is the target audience?

  • Developers who understand Javascript
  • Front-end developers who have worked with other JS frameworks in the past (e.g. Angular)
  • It is NOT for developers who wish to use React with server-side Javascript
  • It is NOT for developers who with to learn a workflow using broserify/gulp/grunt etc and ReactJS

Take it now!

PHP : Predefined Interfaces and Classes

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

PHP.

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

<?php
// 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 ) {
        reset($data);
        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
#int(0)
#string(3) "php"
#int(1)
#string(10) "javascript"
#int(2)
#string(2) "c#"
#int(3)
#string(4) "java"

// if TYPE == 2
#string(3) "one"
#string(3) "php"
#int(0)
#string(10) "javascript"
#string(5) "three"
#string(2) "c#"
#int(1)
#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.

<?php
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:

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

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:

<?php
$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);
            }
        }
    }
    closedir($resource);
    rmdir($path);
};
$deleteDirectory("path/to/directoy");
?>

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:

<?php
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

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 192.0.0.1 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
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

lucene

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.

ElasticSearch

 
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.