Wednesday, 29 March 2017

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.        


Sunday, 12 March 2017

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.





Friday, 10 March 2017

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.

Wednesday, 1 March 2017

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.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts