Monday, 18 June 2018

PHP 7 Performance And Security


PHP is widely used for custom software development. Usage statistics indicate that PHP accounts for over 80 percent of all websites, topping 240 million sites according to the Netcraft web server survey. PHP 7 (2015) is the most important revolution for PHP since the release of PHP 5 in 2004. The speed of PHP 7 and security improvements alone make upgrading to PHP 7 worthwhile. In this post, we will discuss these improvements in more details.

PHP 7 is based on the PHPNG engine (or Zend Engine 3.0) that speeds up PHP applications more than the previous PHP interpreter (Zend Engine 2.0). Thanks to PHPNG, your apps see up to 2x faster performance and 50% better memory consumption than PHP 5.6, allowing you to serve more concurrent users without adding any additional hardware. This means that your server returns pages to your users twice as fast. It also means that a single server can handle twice as many requests and you could need half as many servers in order to serve the same number of customers at the same speed as they did before. It has an impact in terms of real-world dollars.

With the major release of PHP 7.x, PHP's performance has been drastically improved in various frameworks, eCommerce and CMS platforms. Zend has done performance test on varioud apps for php 5.6, php 7 and HHVM 3.7. Improved excecution time, more than 2x faster compared to PHP 5.6. Memory consumptions are decreased by 30%.

What is HHVM?

Due to performance issues with PHP the team at Facebook developed the HipHop Virtual Machine (HHVM). It is a system that uses just-in-time (JIT) compilation to convert PHP code into a machine language to establish a synergy between the PHP code and the underlying hardware that runs it.

As per perfomance benchmarks transactions in Magento are 3x faster, Drupal 8 is 72% faster in PHP 7. Wordpress requests using 100M CPU instructions in PHP 5.6 can now do the same job in just 25M CPU uses in PHP 7. Frameworks like Laravel and Zend has shown a very well perfomance using PHP 7 as compared to PHP 5.6. Compared to other dynamic web page languages like python, perl and ruby etc., PHP has been faster and with PHP 7 it's even much more faster.




Source: http://www.zend.com/en/resources/php7_infographic

Following are the new features added to PHP 7 that improved the quality of the language, saves development time, etc.

- Scalar Type Declaration
- Return Type Declaration
- Null Coalescing Operator
- Spaceship Operator
- Constant Arrays using define
- Annonymus Classes
- Unicode codepoint escape syntax
- Group use declarations
- intdiv() New integer division function
Following has been deprecated in PHP 7

- Static calls to non-static methods
- PHP 4 style constructors
- password_hash() salt option
- ldap_sort()

PHP 7 is new and the most decorated dynamic web page language of current times ;)

Friday, 8 June 2018

PHP and Zend Engine

What is Zend Engine ?

The Zend Engine has been the core scripting engine of PHP since PHP version 4

The Zend engine is a set of components that make PHP what it is. The most important Zend engine component is the Zend Virtual Machine, which is composed of the Zend Compiler and the Zend Executor components. We could also add the OPCache zend extension in such category. Those three components are the heart of PHP (or the brain, you choose), they are critical and they are the most complex parts of all the PHP source code. In the current chapter, we’ll try to open them and detail them.


Zend's History with PHP


Zend's contribution to PHP began in 1997 when Zeev Suraski and Andi Gutmans started work on a rewrite of the core scripting engine of PHP. This work helped to redefine PHP as a full-featured development language.

Zend's contributions continued with PHP 4 which saw the introduction of the Zend Engine, a highly optimized execution engine. This enhancement allowed modules such as debuggers, performance boosters and custom loaders to dynamically extend PHP for a broader range of functionality. Whenever you're using any plug-in module today, you're doing so thanks to the extensibility support of the Zend Engine. In addition, the Zend Engine provides memory and resource management, and other standard services for the PHP language. Zend continued its work on PHP and Zend engine with the introduction of Zend Engine 2. Zend Engine 2 debuted in PHP 5.0 and added a robust and extensible object model and even more performance enhancements.
In PHP extensions are known to be "Zend extentions" and modules are known to be "PHP modules.

In traditional life, we talk about “PHP extensions” versus “Zend extensions”.
The thing that differentiate them is the way they are loaded :
  • PHP extensions (aka PHP “modules”) are loaded in INI files as a “extension=pib.so” line
  • Zend extensions are loaded in INI files as a “zend_extension=pib.so” line
First of all, Zend extensions are compiled and loaded the same way as PHP extensions.

Sources:
- www.zend.com
- www.phpinternalsbook.com

Tuesday, 24 April 2018

Understanding Javascript

 

Functional Programming

A very familiar term "Functional Programming". This is some programming paradigm that javascript falls into. A functional programming language is declarative, that means programming with expressions or declarations instead of statements. There are lot more to know about functional programming like pure functions, and it avoids changing state and mutable data etc., but lets get started with javascript first.

Data Structure and Data Types

Javascript is loosely typed or a dynamic language. That means a variable in javascript has no specific value type, i.e. any type of value can be assigned ro re-assigned to any variable. As it's dynanically typed, type checking are done at runtime.

e.g.
var x = 'foo'; // String
var x = 29;    // Number

Data types

    Primitives:
        Boolean
        Null
        Undefined
        Number
        String
        Symbol (new in ES6)
      
    and Object

Object


Except Object all other types are immutable. Objects are collections of properties having value of any type, including object. Usually objects consists of several variables and/or functions of related data and/or functionality.

Comparing to a real life object, a javascript object consists of properties and behavior.

var car = new Object(); // Object Declaration

Access to properties of an object with a dot-notation:
ObjectName.PropertyName

car.name = 'Creta';
car.company = 'Hyundai';

There are different styles for creating objects in javascript, like:

1) Object literals

var car = {
  name: 'Creta',
  company: 'Hyundai',
  f: function() {},
  g: function() {}
};
 


2) Constructor Functions


function car() {
  return {
    name: 'Creta',
    company: 'Hyundai',
    f: function() {},
    g: function() {}
  };
}

var o = new thing();

In javascript most things are objects like core javascript String and Array.

Javascript Constructors:

Javascript does's support classes, but it has constructors. Constructors are regular functions used with new operator to create objects.

[Source: https://css-tricks.com/understanding-javascript-constructors/]
1) Native Constructor: Available automatically in the execution environment at runtime (e.g. Array, Object, etc)
2) Custom Constructor: Defines properties and methods for your own type of object.


A prototype-based language


Javascript is classless prototype-based programming. It gives you delegation inheritance.

Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of reusing existing objects via delegation that serve as prototypes. [Wikipedia]

Prototype

comming soon.. stay tuned...



Thursday, 5 April 2018

Angular for Beginners I

Caution: knowledge of HTML, CSS and JavaScript are required.

Then AngularJS Now Angular It all started with AngularJS 1.x and then AngularJS 2, and now it's finally Angular, with the latest updates and bug fixes being worked on by the Angular team. Angular is a framework for building client applications in HTML, CSS, and either JavaScript or a language like TypeScript that can be transpiled to JavaScript. This post is all about Angular (Not AngularJS).

TypeScript is a superset of JavaScript. That means any valid JavaScript code is valid TypeScript code. But many prefer TypeScript because it has additional features that we don’t have in the current version of JavaScript that most browsers understand. So, when building Angular applications, we need to have our TypeScript code converted into JavaScript code that browsers can understand. This process is called transpilation which is the combination of translate and compile. And that’s the job of the TypeScript compiler.

Let's get our hands dirty!

Make sure you have latest stable node version installed. Go to you terminal and install Angular CLI using the node package manager (npm).

// -g flag stands for global
// Without -g, Angular CLI will be installed only in the current folder
// and it’s not going to be accessible anywhere else.
 

npm install -g @angular/cli

Install typescript as the new app you are going to create via CLI will have typescript code out of the box.

npm install -g typescript

Create a new Angular app using the CLI.

ng new my-app

Start the application.  

cd my-app
ng serve


Open http://localhost:4200/ in your browser and you should have the default app running.

Note: For permission errors, user sudo.


Structure of Angular Application

  1. e2e: includes end-to-end tests.
  2. node_modules: all the third-party libraries that our project is dependent upon.
  3. src: the actual source code of our Angular application.
  4. package.json: It has project meta data and dependencies information.
Apart from these, there are few other files including test runners and configeration files.

Architecture of Angular Apps

Now that we have generate and serve a new Angular project let’s look at the architecture of Angular applications.

Component

Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Components are defined using the @component decorator. Unlike directives, components always have a template and only one component can be instantiated per an element in a template. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component.

The most fundamental building block in an Angular application is a component. A component consists of three pieces:

HTML markup: to render that view
State: the data to display on the view
Behavior: the logic behind that view. For example, what should happen when the user clicks a button.

WE WILL DISCUSS MORE ON THIS IN THE NEXT POST.

Now, at the root of the application, we have a component called AppComponent. This is the root of every Angular application.

In src/app folder you will see following files:

app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts

These files represent AppComponent, which is the root component for our application. In this particular case, all these files are inside the app folder.

Lets go edit some of these files and see what's happening ;)

Every Angular app has a root module where you define the main component to load. In the default Angular app, the root module is defined inside the app.module.ts. When the AppModule loads, it checks which component is bootstrapped and loads that module. As seen in the app.module.ts, the module which is bootstrapped is AppComponent. The AppComponent component is defined in the file app.component.ts.

A component is defined using the @Component decorator. Inside the @Component decorator, you can define the component selector, the component template, and the related style.

So, in terms of the implementation, each component in an Angular project is physically implemented using four files:

    A CSS file: where we define all the styles for that component. These styles will only be scoped to this component and will not leak to the outside. This is what Shadow DOM does. But not all browsers today support Shadow DOM. So, Angular uses a technique to emulate the Shadow DOM.
    An HTML file: contains the markup to render in the DOM.
    A spec file: includes the unit tests.
    A TypeScript file: where we define the state (the data to display) and behavior (logic) of our component.

You will also see an app.module.ts file.  This file defines the root module of our application and tells angular how to assemble the app.

We will meet in our next POST :)
bye bye


Wednesday, 4 April 2018

ReactJS Interview Questions

What is React?

React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications.

The key point in this answer is that React’s core purpose is to build UI components; it is often referred to as just the “V” (View) in an “MVC” architecture. Therefore it has no opinions on the other pieces of your technology stack and can be seamlessly integrated into any application.

What are the features of React? 

Major features of React are listed below:
  1. It uses the virtual DOM instead of the real DOM.
  2. It uses server-side rendering.
  3. It follows uni-directional data flow or data binding.

 

How is React different?

  1. Because React is a small library focused on building UI components, it is necessarily different than a lot of other JavaScript frameworks.
  2. By contrast, React focuses exclusively on the creation of components, and has few (if any) opinions about an application’s architecture. This allows a developer an incredible amount of flexibility in choosing the architecture they deem “best” — though it also places the responsibility of choosing (or building) those parts on the developer.
  3. It can be conveniently used on the client as well as server side
  4. React is easy to integrate with other frameworks like Meteor, Angular, etc
  5. Using React, writing UI test cases become extremely easy
  6. Because of JSX, code’s readability increases

What is JSX?

It is called JSX, and it is a syntax extension to JavaScript. JSX produces React “elements” and can be rendered to DOM. This syntax is neither a string nor HTML. It helps to put your markup and login in same file.

React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

What is virtual DOM?

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

What is Props?

Props are Read-Only
Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function:

function sum(a, b) {
  return a + b;
} 
 
Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.
In contrast, this function is impure because it changes its own input:

function withdraw(account, amount) {
  account.total -= amount;
} 
 
React is pretty flexible but it has a single strict rule:
All React components must act like pure functions with respect to their props.

What are stateless components?


If React components are essentially state machines that generate UI markup, then what are stateless components?
Stateless components (a flavor of “reusable” components) are nothing more than pure functions that render DOM based solely on the properties provided to them.

const StatelessCmp = props => {
  return (
    <div className="my-stateless-component">
      {props.name}: {props.birthday}
    </div>
  );
};

// ---
ReactDOM.render(
  <StatelessCmp name="Art" birthday="10/01/1980" />,
  document.getElementById('main')
);
 

What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

How can you update the state of a component?

State of a component can be updated using this.setState().
 

What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions. 

Explain the lifecycle methods of React components in detail.

  1. componentWillMount()  Executed just before rendering takes place both on the client as well as server-side.
  2. componentDidMount()  Executed on the client side only after the first render.
  3. componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.
  4. shouldComponentUpdate()  Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.
  5. componentWillUpdate() – Called just before rendering takes place in the DOM.
  6. componentDidUpdate()  Called immediately after rendering takes place.
  7. componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.

What are pure functional Components?

Traditional React Components as we have seen thus far are creating a class with class Example extends React.Component or React.createClass(). These create stateful components if we ever set the state (i.e. this.setState(), getInitialState(), or this.state = {} inside a constructor()).

If we have no intention for a Component to need state, or to need lifecycle methods, we can actually write Components with a pure function, hence the term “pure functional Component”:

function Date(props){
    let {msg="The date is:"} = props
    let now = new Date()
    return <div>
        <span>{msg}</span>
        <time>{now.toLocaleDateString()}</time>
    </div>
}
 
This function that returns a React Element can be used whereever we see fit:
DOM.render(<div><Date msg="Today is"/><div>)
You might notice that <Date/> also takes a prop – we can still pass information into the Component.

Explain the purpose of render() in React.

Each React component must have a render() compulsory. If more than one HTML elements needs to be rendered, then they must be grouped together inside one enclosing tag such as
, ,
etc. It returns to the single react element which is the presentation of native DOM Component. This function must be kept pure i.e., it must return the same result each time it is invoked.

What are Higher Order Components(HOC)?

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wraps another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

What can you do with HOC?

HOC can be used for many tasks like:
  1. Code reuse, logic and bootstrap abstraction
  2. Render High jacking
  3. State abstraction and manipulation
  4. Props manipulation
What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

Why is switch keyword used in React Router v4?

Although a <div> is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch> tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.


What is Redux?

Redux is one of the hottest libraries for front end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

List down the components of Redux.

Redux is composed of the following components:
Action – It’s an object that describes what happened.
Reducer –  It is a place to determine how the state will change.
Store – State/ Object tree of the entire application is saved in the Store.
View – Simply displays the data provided by the Store.

How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. 
Below is an example of Action and Action Creator:

function addTodo(text) {
return {
type: ADD_TODO,
text
}
}

Explain the role of Reducer.
 

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

What is the significance of Store in Redux?
 

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

 
More on the next post .... stay tuned :)


React.js for Beginners

A JavaScript library for building UI (user interfaces).

Features:

- One of it's unique feature is that not only does it perform on the client side, but it can also be rendered server side.

- A programming concept of virtual DOM makes it faster. virtual DOM is the clone of the actual DOM kept in memory and is used by react to sync with the actual DOM. This process is called reconciliation.

- Fiber is the new reconciliation engine in React 16. Its main goal is to enable incremental rendering of the virtual DOM. Read more.

- The most important concept to understand in React.js is the component.It can be either a function(stateless) component or a class(stateful) component.

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.


Getting Started


  1. Make sure you have a recent version of Node.js installed.
  2. Follow the installation instructions to create a new project.

    Create React App is the best way to start building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. You’ll need to have Node >= 6 on your machine.

    // Install create-react-app CLI 
    npm install -g create-react-app
     
    // create an app 
    create-react-app my-app
     
    This is what you will get in your terminal after successful installation.
     

PHP 7 Performance And Security

PHP is widely used for custom software development. Usage statistics indicate that PHP accounts for over 80 percent of all websites, toppi...