Coding standards for achieving high code quality using PSR

Coding Standards are an important factor for achieving a high code quality.A common visual style, naming conventions and other technical settings allow us to produce a homogenous code which is easy to read and maintain.

you can read my article here : https://medium.com

Implementing authentication security in express with JWT

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.It comprises a compact and URL-safe JSON object, which is cryptographically signed to verify its authenticity, and which can also be encrypted if the payload contains sensitive information.JWT.IO allows you to decode, verify and generate JWT.

Implementing security token in express.js


How to use jWT with express.js.

Create project directory and install required dependencies with below shown commands.


//create an folder express-jwt-tutorial
mkdir express-jwt-tutorial
//change the directory
cd express-jwt-tutorial
//It will create package.json file under the current directory
npm init --yes
// It will download all mentioned modules into node_modules directory
npm install --save express body-parser jsonwebtoken

Package Information :

express is the Node framework.
body-parser will let us pull POST content from our HTTP request.
jsonwebtoken is a library which will take care of generating and verifying


Now create a file called app.js in your directory.

// app.js
// importing express lib
const express = require('express');
// creating express instance
const app = express();
 
// importing body-parser, which will handle the user input bodies
const bodyParser = require('body-parser');
 
// importing jsonwebtoken module, this module will create and decode the JWT tokens.
const jsonWebToken = require('jsonwebtoken');
 
app.use(bodyParser.json()); // only parses json data
app.use(bodyParser.urlencoded({ // handles the urlencoded bodies
    extended: true
}));
 
// set secret key, which we will use for creating and decoding JWT tokens, keep it safe. 
const myJWTSecretKey = 'my-secret-key'; 
 
app.get('/', (req, res) => {
    // get user object from the data source, Ex: database 
    const user = {
        email: 'imsonujangra@gmail.com',
        id: 1,
        name: 'Sonu Jangra'
    };
    // sign with default (HMAC SHA256) 
    const token = jsonWebToken.sign(user, myJWTSecretKey);
    res.json({
        token: token
    });
});
 
// GET - http://localhost:3000/verify/{token}
app.get('/verify/:token', (req, res) => {
    try {
        const tokenDecodedData = jsonWebToken.verify(req.params.token, myJWTSecretKey);
        return res.json({
            error: false,
            data: tokenDecodedData
        });
    } catch (error) {
        res.json({
            error: true,
            data: error
        });
    }
})
 
app.listen(3000, () => {
    console.log('Server is running at: 3000');


Now start the server using

node server.js and type this address in browser http://localhost:3000.

If everything fine you will see the below output.


{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGhwQGdtYWlsLmNvbSIsImlkIjoxLCJuYW1lIjoiQXJqdW4gQSIsImlhdCI6MTQ5OTM2NjM0NH0.xRJo4je_4QIyqJpyes8ixxekTqI2EQ6v8_zW3YuG_tE"}


You can verify and decode above token, by pointing your browser with token,

http://localhost:3000/verify/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGh

If everything goes well you should able to see below output:


{"error":false,"data":{"email":"imsonujangra@gmail.com","id":1,"name":"Sonu Jangra","iat":1299366344}}



why we need props and states in react js

This “props vs. state” question is pretty common for new frontend developers - they look so similar, but are used differently.

Prop Vs React



The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events or it provides the bindings between UI and logic functions.A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.

Initialize the state:
You can initialize the state into the constructor of component:

import React, { Component } from 'react';
class XYZComponent extends Component {
       constructor(props){
             super(props);
          this.state={
           stateName:''
        }
     }
         render() {
             return (
       <div>
           <p>{{this.state.stateName}}</p>
      </div>
    );
  }
}
export default XYZComponent;

How to use it.

<p>{{this.state.stateName}}</p>

For update the state value use setState() method.

updateState(){
this.setState({stateName: 'something'});
}

Props :

Props are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned.A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.

<XYZComponent propsName='Some Value'/>

Here you can pass props value into the XYZComponent. You can pass any type value like string, object, array etc.

import React, { Component } from 'react';
class XYZComponent extends Component {

render() {
   return (
       <div>
         <p>{{this.props.propsName }}</p>
      </div>
     );
   }
}

export default XYZComponent;


Here you will get props value with the help of this.props.propsName. now it will print the value of props that is “some value”.

You can also set the value of props with the help of state for example:


<MyComponent propsName={{this.state.stateName}} />

It means you can also update the value of props every time with the help of the state.

Laravel Global key-value store in the database

Sometimes we need to store some key value pairs in your project, but where we store the key value? Some of the options should update later in the process so it should be possible to change them as well.ex: check the status from a third party service and store the status.

Global Key Value Pair Laravel



You can use the package : 

composer require appstract/laravel-options

Then add the ServiceProvider to your config/app.php file:

'providers' => [
    Appstract\Options\OptionsServiceProvider::class
]

Alias :

Also add it as alias, so you can use the facade easily in your app.

'aliases' => [
    'Option' => Appstract\Options\OptionFacade::class,
]

Usage :

With the option() helper, we can get and set options :


// Get option
option('someKey');

// Set option
option(['someKey' => 'someValue']);


If you want to check if an option exists, you can use the facade:


use Option;

$check = Option::exists('someKey');

Console:

It is also possible to set options within the console:


php artisan option:set {someKey} {someValue}

More details on installation and usage, check the GitHub repo.

Lightweight PHP Framework for restful api

The first thing require is a lightweight PHP Framework to create a fast and reliable restful service. 
A framework in PHP language is considered as a means to enhance the productivity to deliver faster results without deviating from best standards and practices. Developing the REST APIs using the plain PHP is a very time-consuming process and requires a lot more effort. it is also prone to deviate from the standards and requires extensive testing.

Lightweight PHP Framework


Whereas, using a micro-framework makes the PHP Rest APIs development as smooth as a baby’s bottom. You get ready to use components, separation of logic, libraries, and freedom from security related issues without doing anything much around these areas.

In this article, I will share the information about Top Lightweight PHP Frameworks for REST APIs Development.  



Slim is revered as a one of the best PHP micro-framework that enables the developers to develop the complex web applications and APIs with ease. It provides complete flexibility, full control and enables a developer to create entire PHP web service in a single PHP file. Not only this, a presence of scalable and modular architecture allows the web developers to use exactly what is needed, nothing more and nothing less. It comprises many features like disable or enable the application debugging for debug API, and if true, Slim will display the accurate debugging information for exceptions and errors. Slim supports any PSR-7 HTTP message implementation so that you can easily inspect and manipulate HTTP message method, URI, headers, status, cookies, and more. By using Slim, you can easily build your application with concentric middleware. It will assist you to easily tweak the HTTP request and response objects near your Slim app. Slim also supports dependency injection, it enables you to have complete control of your external tools. Not only this, Slim provides a strikingly fast and powerful HTTP Router that effectively maps the route callbacks to targeted HTTP request methods and URIs.

Top features:
  • RESTful routing
  • Route passing
  • Named routes
  • Route redirects
  • Custom views
  • Route halting
  • Signed cookies
  • Custom 404 page
  • HTTP caching
  • Parameters and pattern matching
  • Custom 500 page



An interesting micro-framework that stands on the shoulder of Symfony, Pimple and is inspired by the philosophy behind Sinatra. It is a creation of Fabien Potencier and Igor Wieldler and is available free to use under the MIT license. Since beginning the concept was to make a design as lightweight as possible, enabling the additional functionality through base extensions. It exists in two forms, the fat version includes Symphony components, a Twig wrapper, template engine and more. The slim version contains the basic routing engine and a number of procedures of trying in the supplementary functionalities through the extensions. With the choice between slim or fat based codebase versions and the option to later expand upon offers a lot of choice for the developers. Silex slim version is predictably fast and is widely utilized by the smaller services or the services that depend on primary large amounts of data processing.


Top features:
  • Intuitive and concise API
  • One step controllers and routers mapping
  • Micro service container Pimple is used to build the Extension System
  • App testing made easy thanks to Request and Response abstraction using the Symfony HTTP Kernel
  • Ultralight, testable and fun to use
  • Easier to tie in third party libraries



Wave is one of the popular lightweight PHP microframeworks which is built on factory method design pattern and model-view-control architecture. It is built around resource management, caching and smart image and a native API architecture. Being a compact framework that does not include the optional libraries, it carries a very small footprint and is developed by keeping the optimizations and speeds in mind. The framework comes with a view controller and a special gateway for the web functionality with clean URLs incorporating an amazing front-end JavaScript controller.
 
Top features:
  • Secure and modern API-centric framework
  • API returns CSV, HTML, JSON, xml and other data formats
  • Licensed under GNU Lesser General Public License Version 3
  • Supports jQuery JavaScript framework
  • Debugging, backup, update and filesystem maintenance tools
  • 256bit Rijndael encrypted data transmission
  • Supports Apache and Nginx servers in Linux and Windows environments



Just like Wave, Limonade is, all about lightweight functionality and simplicity. It is an amazingly lightweight micro network for prototyping and rapid web development. It is inspired by the frameworks like Orbit in Lua, or  Sinatra or Camping in Ruby. The micro framework is relatively simple and easy to implement and use. It is the first choice for the developers who are looking for a straightforward, yet effective implementation. Unfortunately, Limonade is extremely small and cannot be expanded upon. It is self-contained has no “fat” and “slim” versions, unlike Silex. Additionally, it relies heavily on the global functions. It doesn’t contain a class instead defines the functions which can be used. With that said, Limonade offers the functions that complete a basic PHP set, while maintaining the uniformity with the native functions. It is easier to learn and offers everything which is expected from a modern framework including REST and MVC.
 
Top features:
  • Entirely self contained
  • Extremely lightweight
  • MInimalistic and simple
  • Easy to use and flexible




Lumen is stunningly fast micro-framework by the most successful PHP framework of all times - Laravel. It is extensively used to build Laravel based services and APIS. Microservices consists of loosely coupled components that are independently built but are used in a standalone or (conjunction) in a number of projects if required and this is where Lumen scores above all the rest. Lumen works best when it comes to developing the projects or the components that intend to use for Laravel. Since it is powered by the components of Laravel, just dropping a code into a Laravel installation will get the job done. Lumen works best (fastest of all the PHP frameworks including Silex, Phalcon, etc) when it comes to request handling. Download now to use rich features like caching, validation, routing, a powerful Laravel service container, etc with almost zero configuration. Lumen has the similar foundation as that of Laravel. But it is built for microservices and not much for the user-facing applications.
 
Top features:

  • Simple in its syntax
  • Easy to deploy
  • Lightening fast
  • Consist of pre-set range of appliances and extensions
  • Quicker response time
  • A non-measurable entity
  • More sleeker than Laravel

Lightweight frameworks offers the focussed approach to build the REST APIs and  are actively maintained to build and promote modern websites and web applications of varied size and complexities.


How to protect your system from WannaCry Ransomware.

A decade-old form of malicious software known as ransomware has been making headlines after cybercriminals hijacked hundreds of thousands of computers worldwide.Ransomware, which is often transmitted by email or web pop-ups, involves locking up people’s data and threatening to destroy it if a ransom is not paid. The global cyberattack has affected 200,000 Windows computers in more than 150 countries, including China, Japan, South Korea, Germany and Britain.

Ransomware virus


WannaCry Ransomware: How to protect yourself with os updates

Windows 7 : 

May, 2017 Security Monthly Quality Rollup for Windows 7 (KB4019264)
April, 2017 Preview of Monthly Quality Rollup for Windows 7 (KB4015552)
April, 2017 Security Monthly Quality Rollup for Windows 7 (KB4015549)
March, 2017 Security Monthly Quality Rollup for Windows 7 (KB4012215)
March, 2017 Security Only Quality Update for Windows 7 (KB4012212)
If you have any of those patches already installed, you’re golden.
If you have none of those patches, download and install the May, 2017 Security Monthly Quality Rollup for Windows 7 (KB4019264) for 32-bit or 64-bit.
If you’re manually installing Security-only patches in the “Group B” style, you MUST have the March, 2017 Security Only Quality Update for Windows 7 (KB4012212).
Other Security-only patches don’t include the MS17–010 fix.

Windows 8.1:

May, 2017 Security Monthly Quality Rollup for Windows 8.1 (KB4019215)
April, 2017 Preview of Monthly Quality Rollup for Windows 8.1 (KB4015553)
April, 2017 Security Monthly Quality Rollup for Windows 8.1 (KB4015550)
March, 2017 Security Monthly Quality Rollup for Windows 8.1 (KB4012216)
If you have any of those patches, you’re fine.
If you have none of those patches, download and install the May, 2017 Security Monthly Quality Rollup for Windows 8.1 (KB4019215) for 32-bit or 64-bit.
See note above about Security-only patches.

Windows 10 :

Creators Update (version 1703) is OK.
Anniversary Update (version 1607) — Check your build number. If you have Build 14393.953 or later, you’re fine. If you don’t, use Windows Update to install the latest build 14393.1198.
Fall (November) Update (version 1511) — use the steps above to check your build number. You have to be at build 10586.839 or later.
RTM (version 1507) — same procedure, make sure you’re up to or beyond build 10240.17319.

These patches will upgrade windows to the latest builds for each version.
May, 2017 Cumulative Update for Windows 10 (KB4019474) — 10240.17394
May, 2017 Cumulative Update for Windows 10 Version 1511 (KB4019473) — 10586.916
May, 2017 Cumulative Update for Windows 10 Version 1607 (KB4019472) — 14393.1198
May, 2017 Cumulative Update for Windows 10 Version 1703 (KB4016871) — 15063.29 — but this version is ok

I suggest though that you make a plan for updating these systems to 1703 though if you are a enterprise user, otherwise just google the patch number and install it manually.


All you need to know about PHP 7

It’s been 11 years since the inaugural PHP release. And with access to the PHP 7 features in the latest edition racing ever closer, 2015 and 2016 are expected to be big years for one of the world’s most popular programming languages.On November 26, the PHP development team announced the thirteenth pre-release of PHP 7.0.0. In new PHP version fix some security issue and also some functions and features.

All you need to know about php7


PHP 7 updates :

Speed. PHP 7 will be twice as fast as PHP 5.6 now equipped with a new version of the core scripting engine for PHP — Zend Engine. Applications will run much faster and smoother than before.

Performance: It’s top-of-mind for any language update. Here’s how the PHP 7 features in the latest release will stand out.

Memory: The latest release will use approximately two thirds of the memory it previously did. That means three times the throughput as PHP 5.6.

phpng: PHP Next Generation has been merged with the master branch of PHP improving overall performance. PHP 7 will be able to manage twice as many WordPress requests per second.

Support. PHP 7 will offer consistent 64-bit support.

You can handled the exceptions in php7 differently :

Script that would result in a fatal error in past versions of PHP will now be handled as exceptions.Prior to PHP 7, fatal errors and recoverable errors would halt the script execution without throwing an exception.This means that these errors could not be handled like exceptions and presented in any desirable way to the user.In PHP 7, if the script reaches a fatal error, it throws an error exception, which can be handled like a regular exception with the try/catch block and execute the finally block afterwards (if present). This new method allows us to present most fatal and recoverable errors to the users, the way we want. Some type of fatal errors will still halt script execution (like running out of memory, for example).


Breaks in backwards compatibility with new PHP 7 features :
It will be especially important to avoid or rewrite deprecated code with the recommended PHP tag. Our architects compiled the compatibility changes with the potential to be most trouble.

Changes to error and exception handling :
Most of the applications use some kind of error handling. In this case, there might be cases where those custom handlers won’t be triggered because exceptions will be thrown.

Changes to the handling of indirect variables, properties, and methods : 
This update is important for most of the applications and needs to be considered with priority.

Empty list() assignments have been removed. This is also important to keep in mind, because empty lists are usually used.

Changes to Division By Zero:
There might be cases where an error will be thrown instead of a warning. This will affect the production environment where warnings are suppressed.


What was removed from PHP?
GD Type1 functions changes
ASP and script PHP tags
Calls from incompatible context
$HTTP_RAW_POST_DATA

New capabilities in PHP 7 : 

Beyond grooming deprecated functionality out of PHP 7, the team working on PHP 7 included a host of new functionality.

Closure functions. With Closure functions, we are able to use benefits from functional programming. We can use arrow functions (anonymous functions), and we have a new keyword yield.

Error handling and logging. We can create a custom errors, we can add a log of errors and we can error stack trace.

CSPRNG. With CSPRNG, we are able to generate crypto-strong random integers and bytes.

Matching. PCRE Functions::preg_replace_callback_array with this function we can run arrow functions, when we have matching.

Specification. With ZipArchive, developers can specify compression index.

Deflate. Zlib Compression offers four new functions for working with deflate.




what is typescript ?

It is an open-source programming language from Microsoft. It's announced on October 2012. It comes with powerful type checking abilities and object-oriented features.All of the proposed features of ES 2015 and ES 2016 are implemented by TypeScript, or are in the process of being implemented.These features are converted into their ES5 equivalent when the TypeScript files are transpiled, making it possible to use the latest features of JavaScript even when the browsers have not implemented them natively. Angular 2 uses TypeScript as its primary language for application development.

wantcode typescript


Important points of typescript:
  • TypeScript is a typed superset of JavaScript and compiles to plain JavaScript.
  • TypeScript files have the extension .ts.
  • Since TypeScript supports types, it looks very familiar to any other typed OOP's languages like C# and Java.
  • TypeScript is not executed on the browser. Instead, the transpiled code gets executed in the browser.


Example of typescript:


class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

that gets transpiled into plain JavaScript.


var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

You can also use the online transpiler here .In which you can convert your .ts code to .js.

How the TypeScript defines the type of member variables and class method parameters.  This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

Typescript introduction :

Boolean : The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a boolean value.


let isDone: boolean = false;

Number : As in JavaScript, all numbers in TypeScript are floating point values. These floating point numbers get the type number. In addition to hexadecimal and decimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.


let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

String : we use the type string to refer to these textual datatypes. Just like JavaScript, TypeScript also uses double quotes (") or single quotes (') to surround string data.


let color: string = "blue";
color = 'red';

Array :  Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type.


let list: number[] = [1, 2, 3];

The second way uses a generic array type, Array<elemType>:


let list: Array<number> = [1, 2, 3];

Tuple : Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same.For example, you may want to represent a value as a pair of a string and a number.


// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

Enum : A helpful addition to the standard set of datatypes from JavaScript is the enum.


enum Color {Red, Green, Blue}
let c: Color = Color.Green;

ANY : If you are declaring a variable without using a type and without assigning any value to it, the TLS assigns it the any type. Think of any as a supertype of all types, which is used whenever TypeScript is unable to infer a type.You can also assign the any type explicitly, which allows it to assume any value—from a simple string, number, Boolean, or even a complex object.


var x; //implicitly assigned type any 

var y : any; // explicitly assigned type any

VOID : Void signifies that a method does not have a return value.


function showmsg(msg):void {
alert(msg)
}

TypeScript has a number of useful features.To dive deeper into TypeScript, refer to doc

Build native android app in javascript

React Native is a JavaScript framework for writing real, native rendering Android and ios platform applications. Instead of running React in the browser and rendering to div's and span's, React Native run it in an embedded instance of JavaScript.

Android App in javascript react


Requirement :
Node.js should be installed on your machine.

Install global package of react native cli :
npm install -g react-native-cli

Install Android Studio :
Android Studio 2.0 or higher. It will provide you the Android SDK and emulator required to run and test your React Native apps.While installing the android studio choose customize installation and choose Choose Android Virtual Device.

After installation, choose Configure | SDK Manager from the Android Studio welcome window.

In the SDK Platforms window, choose Show Package Details and under Android 6.0 (Marshmallow), make sure that Google APIs, Intel x86 Atom System Image, Intel x86 Atom_64 System Image, and Google APIs Intel x86 Atom_64 System Image are checked.

In the SDK Tools window, choose Show Package Details and under Android SDK Build Tools, make sure that Android SDK Build-Tools 23.0.1 is selected.


Set environment path for  ANDROID_HOME
export ANDROID_HOME=~/Android/Sdk

To do that, add this to your ~/.bashrc, ~/.bash_profile (or whatever your shell uses) and re-open your terminal:

Watchman : Watchman is a tool by Facebook for watching changes in the filesystem. It is recommended you install it for better performance.


git clone https://github.com/facebook/watchman.git
cd watchman
git checkout v4.5.0  # the latest stable release
./autogen.sh
./configure
make
sudo make install

You can create the virtual device to run the app on emulator or you can debug also in android device.

Settings > About Phone > Build number > Tap it 7 times to become developer;
Settings > Developer Options > USB Debugging.

Now install react native using these commands.


react-native init firstNativeApp
cd firstNativeApp
react-native run-android

Note : By default the app will run on port 8081 so please check if some other process will using the 8081 port or not.


This error will happened because in port 8081 i'm running already a nginx server . so your can stop it or change the react default port.

While running the react-native run-android you can also check the status of package is running or not using command react-native start.

if some error will occured while run-android the it must be some sdk problem or avd not started. sometime some gradle or local properties error  also occuring so create settings.gradle in your root project and add this code include ':app'. Under android folder you can create local.properties and add sdk.dir=~/Android/Sdk your sdk path.

Then open your project root file index.android.js and change some content and see the changes in app also if app will not refreshing automatically then check your watchman installation step or your directly refresh you in device by shaking it. I hope you understand the how app will run in android. 







Minimize js and css in custom path yii2 framework

In yii2 we have a lots of css and js files registered to pages. So it will take time to load all files one by one. we have to compress and combine all CSS files into a single file and do the same with JavaScript files.As a result, we serve just two files instead of the whole bunch one for css and other for js. Yii2 has, however, got the helper console command that you can use to simplify the process of compressing your assets and wiring them to your application. The most beautiful part is that you will not need to change any of your view files; all existing *Asset::register() calls can stay the same.

Minimize js and css in custom path in Yii2


The overall idea behind asset compiling in Yii is that you prepare a special asset bundle with just two files: one containing all of the compiled CSS and the other containing all of the compiled JavaScript.
Then, you override the configuration for asset bundles using the components.assetManager.bundles setting (read about it in the documentation) telling Yii to use this special, newly-created asset bundle instead of all of the usual bundles.

The \yii\console\controllers\AssetController class, which provides you with the ./yii asset command, encapsulates and automates the procedure of asset compilation. It even deals with the issue of files referenced from the CSS code for you, which is really amazing.

Before starting to compress the files we have to need yuicompressor.jar and Google Closure compiler should be named compiler.jar.After downloading these two files create a folder named tool(you can change the name also) in root of your project and move both files in this folder. 


After that, we need to create a special configuration file for the compressor. Yii has the console command to help you make a boilerplate template for this configuration. Run the following at the root of code base:


./yii asset/template frontend/web/config.php

After running this command you can see the new file in frontend/web directory.you should see the following code in config.php.

<?php
/**
 * Configuration file for the "yii asset" console command.
 */

// In the console environment, some path aliases may not exist. Please define these:
 Yii::setAlias('@webroot', __DIR__ . '/../web');
 Yii::setAlias('@web', '/');

return [
    // Adjust command/callback for JavaScript files compressing:
    'jsCompressor' => 'java -jar tool/compiler.jar --js {from} --js_output_file {to}',
    // Adjust command/callback for CSS files compressing:
    'cssCompressor' => 'java -jar tool/yuicompressor.jar --type css {from} -o {to}',
    // The list of asset bundles to compress:
    'bundles' => [
         'frontend\assets\main\MyAsset',         'frontend\assets\main\AnotherAsset'        // 'yii\web\YiiAsset',
        // 'yii\web\JqueryAsset',
    ],
    // Asset bundle for compression output:
    'targets' => [
        'myAsset' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot',
            'baseUrl' => '/',
            'js' => 'compress/my-compressed.js',
            'css' => 'compress/my-compressed.css',
            'depends' => [
                'frontend\assets\main\MyAsset'
            ],
        ],
        'anotherAsset' => [
            'class' => 'yii\web\AssetBundle',
            'basePath' => '@webroot',
            'baseUrl' => '/',
            'js' => 'compress/another-compressed.js',
            'css' => 'compress/another-compressed.css',
            'depends' => [
                'frontend\assets\main\AnotherAsset'
            ],
        ],
    ],
    // Asset manager configuration:
    'assetManager' => [
  'basePath' => __DIR__,
        'baseUrl' => '',
        'bundles' => [
            'yii\web\JqueryAsset' => [
               'sourcePath' => null,
               'basePath' => null,
               'js' => ['']
            ]
        ]
    ],
];


The first part of the code is quite simple you should define the list of asset bundles you want to compress together. Note that they are named by their fully qualified names.Please specify the fully qualified names of asset bundles without the leading slashes. otherwise, you will break the mechanics.

In bundles includes the list of your assets . if you have to minified multiple assets the mention all the files in bundles.Targets is used for Asset bundle for compression output. 


'myAsset' => [
  'class' => 'yii\web\AssetBundle',
  'basePath' => '@webroot',
  'baseUrl' => '/',
  'js' => 'compress/my-compressed.js', 
  'css' => 'compress/my-compressed.css',
  'depends' => [
   'frontend\assets\main\MyAsset'
  ],
    ],
in targets you have to mention the depends assets which you have to use for the compression.

So, AllAsset should have the basePath setting equal to @webroot and the baseUrl setting equal to /. The problem is, at the point when frontend/web/config.php will be evaluated, there’ll be no @webroot alias defined, so we are left with paths shown in the following code:


'targets' => [
        'frontend\assets\main\MyAsset' => [
            'basePath' => '@webroot',
            'baseUrl' => '/',
            'js' => 'compiled-assets/all-{hash}.js',
            'css' => 'compiled-assets/all-{hash}.css',
        ],
    ], 

The {hash} token will be replaced by a unique hash for the corresponding file.

Now, run the command at last:

./yii asset frontend/web/config.php common/config/assets_compressed.php    

The first argument to the ./yii asset command is the path to the supplementary configuration file we worked so hard to forge until now. The second argument is the path to the file that will hold the resulting configuration snippet we’ll need to attach to our application. We decided to put it to the assets_compressed.php file near our other main configuration files.

The configuration snippet generated will hold the definitions of all asset bundles listed in bundles with js and css settings cleaned out. All these asset bundles will be made dependent on the newly-created asset bundle containing the compressed CSS and JavaScript files. We need to use the content of this configuration snippet as the value of the components.assetManager.bundles setting in the application configuration, so in our case, we just paste the following into the components section.


'assetManager' => [
            'bundles' => (require __DIR__ . '/assets_compressed.php')
        ],

Now you can see the action in your page view source . The js and css are minified.I hope this lession will help you to minified the css and js files in yii2.        


Improve mysql performance on large data sets

The world of relational database theory is a world dominated by tables and sets, and operations on tables and sets.A database is a set of tables, and a table is a set of rows and columns. When you issue a SELECT statement to retrieve rows from a table, you get back another set of rows and columns that is, another table and it is called abstract notations.

MYSQL performance


Database management systems implement abstract concepts but do so on real hardware bound by real physical constraints. As a result, queries take time—sometimes an annoyingly long time.And we, being impatient creatures, don’t like to wait, so we leave the abstract world of instantaneous mathematical operations on sets and look for ways to speed up our queries. Fortunately, there are several techniques for doing so:

  • Create indexes on tables to enable the database server to look up rows more quickly.
  • Consider how to write queries to take advantage of those indexes to the fullest extent, and use the EXPLAIN statement to check whether the MySQL server really is doing so.
  • Write queries to affect the server’s scheduling mechanism so that queries arriving from multiple clients cooperate better.
  • Tune the server’s configurable operating parameters to get it to perform more efficiently.
  • Analyze what’s going on with the underlying hardware and how to work around its physical constraints to improve performance.

Indexing : There are various techniques to speed up the query but indexing is the basic mechanism to speed up your query. If you are doing proper index of your column so you can easily see the real change in execution time. It’s often true that when a query runs slowly, adding indexes solves the problem immediately.But it doesn’t always work like that, because optimization isn’t always simple.Nevertheless, if you don’t use indexes, in many cases you’re just wasting your time trying to improve performance.So always first you can using indexing first then other technique will be helpful.


Benefits of Indexing :

Let’s consider how an index works, beginning with a table that has no indexes.An unindexed table is simply an unordered collection of rows. When addition of an index on the coloumn in table the index contain an entry for each row in that table.

lets suppose we have a table name student.

id roll_no class
1  11882   10
2  22332   11
3  34432   12
4  23343   9

select roll_no from student where class = 11;

Now, instead of searching through the table row by row looking for items that match, we can use the index.  Suppose we’re looking for all rows for class 10 We begin scanning the index and find values for that class. Then we reach the index value for class 11, which is higher than the one we’re looking for.  Index values are sorted, so when we read the index row containing 11, we know we won’t find any more matches and can quit looking. so where the matching end skip the rest.That way, we can quickly position to the first matching value and save a lot of time in the search.

The MySQL Query Optimizer : 

The MySQL query optimizer takes advantage of indexes, of course, but it also uses other information. For example, if you issue the following query, MySQL will execute it very quickly, no matter how large the table is:

SELECT * FROM tbl_name WHERE FALSE; 

MySQL looks at the WHERE clause, realizes that no rows can possibly satisfy the query, and doesn’t even bother to search the table.

EXPLAIN SELECT * FROM tbl_name WHERE FALSE

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE NULL NULL NULL NULL NULL NULL NULL NULL NULL Impossible WHERE

Normally, EXPLAIN returns more information than that, including values more informative than NULL about the indexes that will be used to scan tables, the types of joins that will be used, and estimates of the number of rows that will need to be examined from each table.

EXPLAIN is to find out whether adding indexes would help the optimizer execute a statement more efficiently.For this example, I will use just two tables that initially are unindexed.This suffices to show the effect of creating indexes. The same principles apply to more complex joins that involve many tables. Suppose that we have two tables t1 and t2 , each with 1,000 rows containing the values 1 to 1000.The query that we’ll examine looks for those rows where corresponding values from the two tables are the same:


SELECT t1.i1, t2.i2 FROM t1 INNER JOIN t2
-> WHERE t1.i1 = t2.i2;

EXPLAIN SELECT t1.i1, t2.i2 FROM t1 INNER JOIN t2
-> WHERE t1.i1 = t2.i2

*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t1
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1000
Extra:
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: t2
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1000
Extra: Using where

Here, ALL in the type column indicates a full table scan that examines all rows. NULL in the possible_keys column indicates that no candidate indexes were found for speeding up the query.(The key , key_len , and ref columns all are NULL as well due to the lack of a suitable index.).Using where indicates that information in the WHERE clause is used to identify qualifying rows.

To make this query more efficient, add an index on one of the joined columns and try the EXPLAIN statement again:

mysql> ALTER TABLE t2 ADD INDEX (i2);
mysql> EXPLAIN SELECT t1.i1, t2.i2 FROM t1 INNER JOIN t2
-> WHERE t1.i1 = t2.i2;

*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t1
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1000
Extra:
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: t2
type: ref
possible_keys: i2
key: i2
key_len: 5
ref: sampdb.t1.i1
rows: 10
Extra: Using where; Using index


  • This is an improvement.The output for t1 is unchanged (indicating that a full scan still will be done on the table), but the optimizer can process t2 differently:
  • type has changed from ALL to ref , meaning t1 ) can be used to perform an index lookup that a reference value (the value from to locate qualifying rows in t2 .
  • The reference value is given in the ref field: sampdb.t1.i1 .


Choosing Right Data Types for Efficient Queries:

Use numeric rather than string operations. Calculations involving numbers generally are faster than those involving strings.

If a string column has a limited number of values, you can use an ENUM or SET type to get the advantages of numeric operations.These types are represented internally as numbers and can be processed more efficiently

choose the smallest type that will hold the required range of values. Don’t use BIGINT if MEDIUMINT will do. Don’t use DOUBLE if you need only FLOAT precision. If you are using fixed-length CHAR columns, don’t make them unnecessarily long. If the longest value you store in a column is 40 characters long, don’t define it as CHAR(255) ; define it as CHAR(40) .

For MyISAM tables, use fixed-length columns rather than variable length columns. For example, make all character columns CHAR rather than VARCHAR .The tradeoff is that your table will use more space, but if you can afford the extra space, fixed length rows can be processed more quickly than variable-length rows.

These are some technique to speed up your mysql performance . There are many other ways to speed up the mysql performance but these above points are basics and must be used . I hope you like the post please comment and share.





Late static binding in PHP

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

Late Static binding


self keyword you use to access static properties and methods Self is resolved at compile time, which means that when class is inherited from another class, self will always relate to the class where it is mentioned not the class which is inheriting it.

so lets look an example of self :

class A {
 
public static function getClass()
{
 echo __CLASS__;
} 

public static function callClass()
{
  //reference of A::getClass here
  self::getClass();
}
  
}

class B extends A{
 
    public static function getClass() {
        echo __CLASS__;
    } 
 
}

//so what will be the output of this code
B::callClass(); //A

As we seen self is reffering to the class A (Base Class) in above example. B::callClass() will call the A::getClass because (self will always relate to the class where it is mentioned A::getClass() not the class which is inheriting it) so to solve this problem we use late static binding  . The late static binding will overcome this problem by using static keyword that  reference the class that was initially called at runtime. so call it statically instead of using self here .


class A {
 
public static function getClass()
{
 echo __CLASS__;
} 

public static function callClass()
{
  //reference of A::getClass here
  static::getClass();
}
}

class B extends A{
    public static function getClass() {
        echo __CLASS__;
    } 
 
}

//so what will be the output of this code
B::callClass(); //B

Read more about late static binding here.

let vs var in ecmascript 6

Let vs var the difference is scoping. let is scoped to the nearest enclosing block and var is scoped to the nearest function block (both are global if outside any block) , which can be smaller than a function block.Also, variables declared with let are not accessible before they are declared in their enclosing block.

ecma 6 let vs var


Global : 

let a = 'hello';  // globally scoped
var b = 'world'; // globally scoped

However, global variables defined with let will not be added as properties on the global window object like those defined with var.


console.log(window.a); // undefined
console.log(window.b); // 'world'

Redeclaration : 

Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.


'use strict';
let a = 'hello';
let a = 'world'; // SyntaxError: Identifier 'a' has already been declared


'use strict';
var a = 'hello';
var a = 'world'; // No problem, `a` is replaced.

ES6 lets you declare variables to belong to individual blocks (pairs of { .. } ), using the let keyword.


function foo() {
  var a = 1;
  if (a >= 1) {
    letb = 2;
    while (b < 5) {
      letc = b * 2;
      b++;
      console.log(a + c);
    }
  }
}
foo();
// 5 7 9

Because of using let instead of var , b will belong only to the if statement and thus not to the whole foo() function’s scope. Similarly, c belongs only to the while loop. Block scoping is very useful for managing your variable scopes in a more fine-grained fashion, which can make your code much easier to maintain over time.

Block:
Here is the difference. let is only visible in the for() loop and var is visible to the whole function.


function somefunctionA() {
    //i is *not* visible out here

    for( let i = 0; i < 5; i++ ) {
        //i is only visible in here (and in the for() parentheses)
        //and there is a separate i variable for each iteration of the loop
    }

    //i is *not* visible out here
}

function somefunctionB() {
    //j *is* visible out here

    for( var j = 0; j < 5; j++ ) {
        //j is visible to the whole function
    }

    //j *is* visible out here
}


I hope you understand the let vs var with above example. please comment and share.

How to catch fatal Errors in PHP

In this tutorial we will see how to catch the fatal errors in PHP.Normally we skip the fatal errors like calling a function which doesn't exist in file.


The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

We can now use it with register_shutdown_function to handle fatal error, log, redirect, html page, instead of the infamous white page.We will use register_shutdown_function function to catch the fatal errors.

Note :  register_shutdown_function will gets executed after your script execution ends either it is successful or ends with any error.

So before performing any action in this function we need to check if really any fatal occurs or not. If occurs then we will show error page else it will continue to run as it is.




<?php
register_shutdown_function( "handle_fatal_error" );

function handle_fatal_error() {
  $errfile = "unknown file";
  $errstr  = "shutdown";
  $errno   = E_CORE_ERROR;
  $errline = 0;

  $error = error_get_last();

  if( $error !== NULL) {
    $errno   = $error["type"];
    $errfile = $error["file"];
    $errline = $error["line"];
    $errstr  = $error["message"];
 echo "file-".$error["file"]. " type ".$error["type"]. " line ".$error["line"]." message ".$error["message"];die;
        
  }
}

//This function is undefined
echo myfunction();die;


It will handle the fatal error and you can pass the error in mail also.

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular