Javascript trick questions

There’s lot tricky test question if you go through interview, here I put some tricky and might be simple but we might not conscience that basic method and lost the point while interview:

Basic concept questions:

What does “use strict” do?

The “use strict” literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example, the following program will throw an error:

function doSomething(val) {
  "use strict"; 
  x = val + 10;
}

once you add “use strict”, it will through an error: x is not declare as a variable even though this will not cause code error once it is show undefined, and follow is correct version:

function doSomething(val) {
  "use strict"; 
  var x = val + 10;
}

What is the difference between == and ===?
The difference is that == performs implicit type conversion to check if values are equal to each other. So it will convert the values to true or false boolean values and then compare them. Below are some weird results of this implicit type conversion using the double equal operator:

"1" == 1 // true
true == 1 // true
[] == false // true
"" == false // true
undefined == null // true

This can really cause some problems when you’re writing JavaScript, so the safe thing to do is use the triple equal operator instead, which checks that the two values are of the same type and does not perform type conversion.

How would you check if a number is an integer?

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

function isInt(num) {
  return num % 1 === 0;
}

console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false

What’s the difference between undefined and not defined in JavaScript

You declare JavaScript variables with the var keyword: var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign var carname=”Volvo”;
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement: var carname;
var hoisting
In JavaScript, a variable can be declared after being used.

var x; // Declaration
typeof x === 'undefined'; // Will return true

What is “closure” in javascript? Can you provide an example?
A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.

The closure has access to the variable in three scopes:

Variable declared in his own scope
Variable declared in parent function scope
Variable declared in the global namespace

function multiply(a) {
  return function(b) {
    return a * b;
  }
}

multiply(5)(6);

How to check if an object is an array or not?

The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype

if(Object.prototype.toString.call(arrayList) === '[object Array]') {
  console.log('Array!');
}

what is function hoisting in JavaScript?
In JavaScript var-declared variables and functions are hoisted. Let’s take function hoisting first. Basically, the JavaScript interpreter looks ahead to find all the variable declaration and hoists them to the top of the function where it’s declared.

foo(); // Here foo is still undefined
var foo = function foo() {
  return 12;
};
var foo = undefined;
foo = function foo() {
  // Some code stuff
}
foo(); // Now foo is defined here

Explain what a callback function is and provide a simple example.
A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

function modifyArray(arr, callback) {
  // do something to arr here
  arr.push(100);
  // then execute the callback function that was passed
  callback();
}

var arr = [1, 2, 3, 4, 5];

modifyArray(arr, function() {
  console.log("array has been modified", arr);
});

And also there’s lot test javascript question quiz on line

ECMAScript 6 new features compare ECMAScript 5

This is to compare the difference between ECMAScript 6 and ECMAScript 5

Use ECMAScript 6 you could reduced lots code , but the core problem is not all the browser support, to resolve this ECMAScript 6 need to use a compiler to transform your ECMAScript 6 code to ECMAScript 5 compatible code, in this purpose you could use Babel which allowed you run in current browsers

As follow is introduced some syntax that I used often in ES5 and it’s completely shorten in ES6

Before you should know the difference between var, let and const

compare to var, let will be more strict but it also changeable in the block scope,

const in the word means it is immutable, try in browser to defined between then you could find the error notice once you had declared with let and const, this could be more easy to debug since it’s more strict compare var

you could get more introduction here

1 Constants

ES5

//  only in ES5 through the help of object properties
//  and only in global context and not in a block scope
Object.defineProperty(typeof global === "object" ? global : window, "PI", {
    value:        3.141593,
    enumerable:   true,
    writable:     false,
    configurable: false
})
PI > 3.0;

ES6

const PI = 3.141593
PI > 3.0

In ES6 you could defined the constant, variables which cannot be re-assigned new content, but in case the content is an object, this means the object itself can still be altered: ( follow as resign value and it show error, but property in object can be added or removed or be changed) :

2  Scoping: Block-scoped Variables

without hoisting, so you do not need to declare variable to the top of the current script or the current function

ES5

var i, x, y;
for (i = 0; i < a.length; i++) {
    x = a[i];
    …
}
for (i = 0; i < b.length; i++) {
    y = b[i];
    …
}

var callbacks = [];
for (var i = 0; i <= 2; i++) {
    (function (i) {
        callbacks[i] = function() { return i * 2; };
    })(i);
}
callbacks[0]() === 0;
callbacks[1]() === 2;
callbacks[2]() === 4;

ES6

for (let i = 0; i < a.length; i++) {
    let x = a[i]
    …
}
for (let i = 0; i < b.length; i++) {
    let y = b[i]
    …
}

let callbacks = []
for (let i = 0; i <= 2; i++) {
    callbacks[i] = function () { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4

3 Arrow Functions, which reduced funtion expressive closure syntax

ES5

odds  = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums  = evens.map(function (v, i) { return v + i; });

ES6

odds  = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums  = evens.map((v, i) => v + i)

and so does statement bodies:
ES5

nums.forEach(function (v) {
   if (v % 5 === 0)
       fives.push(v);
});

ES6

nums.forEach(v => {
   if (v % 5 === 0)
       fives.push(v)
})

Lexical this

ES5

//  variant 1
var self = this;
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        self.fives.push(v);
});

//  variant 2
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}, this);

//  variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
    if (v % 5 === 0)
        this.fives.push(v);
}.bind(this));

ES6

this.nums.forEach((v) => {
    if (v % 5 === 0)
        this.fives.push(v)
})

3 Extended Parameter Handling
ES6 could be like other functional programme lauguage, you could simple and intuitive default values in your function parameters:

ES5

function f (x, y, z) {
    if (y === undefined)
        y = 7;
    if (z === undefined)
        z = 42;
    return x + y + z;
};
f(1) === 50;

ES6

function f (x, y = 7, z = 42) {
    return x + y + z
}
f(1) === 50

And you could use aggregation of remaining arguments into single parameter of variadic functions, aggregation is quiet useful in Reactjs

ES5

function f (x, y) {
    var a = Array.prototype.slice.call(arguments, 2);
    return (x + y) * a.length;
};
f(1, 2, "hello", true, 7) === 9;

ES6

function f (x, y, ...a) {
    return (x + y) * a.length
}
f(1, 2, "hello", true, 7) === 9

Spreading of elements in an array or a string into both literal elements:

ES5

var params = [ "hello", true, 7 ];
var other = [ 1, 2 ].concat(params); // [ 1, 2, "hello", true, 7 ]

ES6

var params = [ "hello", true, 7 ]
var other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ]

Template Literals
String Interpolation for output of defined variables, this is quiet useful once you had lots string to express, for example show error message string in JS:
instead of using “+ card.amount +” , used ${card.amount} is more readable
ES5

var customer = { name: "Foo" };
var card = { amount: 7, product: "Bar", unitprice: 42 };
var message = "Hello " + customer.name + ",\n" +
"want to buy " + card.amount + " " + card.product + " for\n" +
"a total of " + (card.amount * card.unitprice) + " bucks?";

ES6

var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`

Enhanced Object Properties

Property Shorthand:

ES5

var x = 0, y = 0;
obj = { x: x, y: y };

ES6

var x = 0, y = 0
obj = { x, y }

Computed Property Names

ES5

var obj = {
    foo: "bar"
};
obj[ "baz" + quux() ] = 42;

ES6

let obj = {
    foo: "bar",
    [ "baz" + quux() ]: 42
}

Class definition
like other OOP functional language, ES6 could be more intuitive, OOP-style and boilerplate-free classes, if you write php then you will love this point

ES5

var Shape = function (id, x, y) {
    this.id = id;
    this.move(x, y);
};
Shape.prototype.move = function (x, y) {
    this.x = x;
    this.y = y;
};

ES6

class Shape {
    constructor (id, x, y) {
        this.id = id
        this.move(x, y)
    }
    move (x, y) {
        this.x = x
        this.y = y
    }
}

New Built-In Methods

Object Property Assignment: assign()

this will return the value of assign target object
ES5

var dest = { quux: 0 };
var src1 = { foo: 1, bar: 2 };
var src2 = { foo: 3, baz: 4 };
Object.keys(src1).forEach(function(k) {
    dest[k] = src1[k];
});
Object.keys(src2).forEach(function(k) {
    dest[k] = src2[k];
});
dest.quux === 0;
dest.foo  === 3;
dest.bar  === 2;
dest.baz  === 4;

ES6

var dest = { quux: 0 }
var src1 = { foo: 1, bar: 2 }
var src2 = { foo: 3, baz: 4 }
Object.assign(dest, src1, src2)
dest.quux === 0
dest.foo  === 3
dest.bar  === 2
dest.baz  === 4

Array Element Finding
New function for finding an element in an array

ES5

[ 1, 3, 4, 2 ].filter(function (x) { return x > 3; })[0]; // 4
// no equivalent in ES5

ES6

[ 1, 3, 4, 2 ].find(x => x > 3) // 4
[ 1, 3, 4, 2 ].findIndex(x => x > 3) // 2

String Repeating

ES5

Array((4 * depth) + 1).join(" ");
Array(3 + 1).join("foo");

ES6

" ".repeat(4 * depth)
"foo".repeat(3)

String Searching
New specific string functions to search for a sub-string

ES5

"hello".startsWith("ello", 1) // true
"hello".endsWith("hell", 4)   // true
"hello".includes("ell")       // true
"hello".includes("ell", 1)    // true
"hello".includes("ell", 2)    // false

ES6

"hello".indexOf("ello") === 1;    // true
"hello".indexOf("hell") === (4 - "hell".length); // true
"hello".indexOf("ell") !== -1;    // true
"hello".indexOf("ell", 1) !== -1; // true
"hello".indexOf("ell", 2) !== -1; // false

Number Truncation
Truncate a floating point number to its integral part, completely dropping the fractional part.
ES5

function mathTrunc (x) {
    return (x < 0 ? Math.ceil(x) : Math.floor(x));
}
console.log(mathTrunc(42.7)) // 42
console.log(mathTrunc( 0.1)) // 0
console.log(mathTrunc(-0.1)) // -0

ES6

console.log(Math.trunc(42.7)) // 42
console.log(Math.trunc( 0.1)) // 0
console.log(Math.trunc(-0.1)) // -0

React Js Redux: Reducer

Once you had defined your action ( description action type), and still state is not knowing how to change, so here comes to Reducer

Design Your State Case

first you should define how and what you want to change your state

let’s use the most simple demo : increase +1 in Action

{
  type: 'INCREMENT'
}

So in Reducer, it is actually an function, which take care action had dispatch and handle state, you need to pass 2 parameters,
one is initial state, second is the action object:

function counter(state = 0, action) {
  // return state 
}

then you could handle your state inside:

function counter(state = 0, action) {
 switch (action.type) {
   case 'INCREMENT':
   return state + 1;
   default:
   return state;
 }
}

use switch to handle the difference case of state, here you use Increment which return state + 1,  or return default state

Once more example here:  add to do

First define your action:

// actions/TodoActions
export const ADD_TODO = 'ADD_TODO';
export function addTodo(text)
{
  return{
    type: ADD_TODO,
    text
  }
}

here you define action const, and you create Action Creator to return action type

so that send to reducer to change the state:

// reducers/AppReducers
import {ADD_TODO} from 'actions/TodoActions';
export function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ];
    default:
      return state;
  }
}

As you could see once again function todos is an Reducer, and you inject : initial state and action

Then go ahead to return the states by switch case:

first is ADD_TODO, return your todo text, and not completed

else return the default state

Since Reducer is return the state, so keep it simple, remember follow to avoid:

1. change the parameter

2. add any side effect event, like call API or routing change

3. And since reducer is pure function, then you should not called other not pure functions like Date.now() or Math.random()

And you could put as much reducer you want which could separate different object to change, in this way your code will be more reusable and more easy to debug:

function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case TOGGLE_TODO:
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: !todo.completed
          })
        }
        return todo
      })
    default:
      return state
  }
}

function visibilityFilter(state = SHOW_ALL, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return action.filter
    default:
      return state
  }
}

function todoApp(state = {}, action) {
  return {
    visibilityFilter: visibilityFilter(state.visibilityFilter, action),
    todos: todos(state.todos, action)
  }
}

And Redux provide an function called combinereducers() which allowed you combien those reducers :

import { combineReducers } from 'redux'

const todoApp = combineReducers({
  visibilityFilter,
  todos
})

export default todoApp

Here it is the Reducer concept, hope this could help you understand the core concept

React Js Redux: Action

As last note we had said the core of Redux are Action, Store, Reducer

So that’s try to memories what’s those 3  relation between

For example you need to add a click event, the process is follow:

1 in reducers file add file button.js and write an event constant :

const click => (state, action) { switch (action.type) { case 'ADD' : return state + 1; case 'REMOVE' : return state - 1; } }

2 in action file add file button.js add a function like click(), this method is send the const and data to reducer

3 in container file import action function and send to Button component event

4 Button component will send to DOM

So this simple button event need to get through 4 folder, sounds really complicated right?

Again please look at this picture:

I will advice to look through again the diagram and draw yourself before continuer

Action

Action is the object of Javascript:

const ADD_TODO = 'ADD_TODO'
{
  type: ADD_TODO,
  text: 'Build my first Redux app'
}

Action must have type attribute, it’s present what type of operation (action), type should be defined as string

repeat:

An action MUST

be a plain JavaScript object.
have a type property.

An action MAY

have an error property.
have a payload property.
have a meta property.

you could see more definition flux from here

how action work:

For example if we need to check todo list has done then be checked, we could use index point to specific todo:

{
  type: TOGGLE_TODO,
  index: 5
}

and we need to filter all todo list and show only the completed list:

{
  type: SET_VISIBILITY_FILTER,
  filter: SHOW_COMPLETED
}

You could add as much actin type object you want, but try to keep more simple

Action Creator

Action creator == the function which create action, in Redux action creator return one action, this propose to make code more easy to test and portability:

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

In redux you could use dispatch to active the action creator:

dispatch(addTodo(text))
dispatch(completeTodo(index))

follow is the sample code:

/*
 * action type
 */

export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'

/*
 * 其他常數
 */

export const VisibilityFilters = {
  SHOW_ALL: 'SHOW_ALL',
  SHOW_COMPLETED: 'SHOW_COMPLETED',
  SHOW_ACTIVE: 'SHOW_ACTIVE'
}

/*
 * action creator
 */

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

export function toggleTodo(index) {
  return { type: TOGGLE_TODO, index }
}

export function setVisibilityFilter(filter) {
  return { type: SET_VISIBILITY_FILTER, filter }
}

It’s must still confused, if you like to dig more I found this article is great to know the concept

Next :reducer, which  is to change the state

React Js Redux

This is basic my note for learning and understand what exact Redux doing

If you had play with Flux, then yes you had pretty much get 80% concept

If you don’t , like me has no clue about Flux , then we could try to learn the concepts step by step:

Concept:

According to the Auther: Dan Abramov

Redux is a library to range states more easier, less API, but more predictable behaviours, it could be practice logging, hot reloading, time travel and universal application, recording and repeating

If you knew about Flux, it was came from the problem of showing message tab box from Facebook messenger by user read or not read, and mean time show different states in the same time, the core is fix this feature problem by Virtual DOM to make user better experience:
1. Improve data consistancy

2. Point root of a bug

3. More meaning unit test

so this was birth of dispatch and action part:

From view to trigger update data even, action send ddata to dispatcher, and dispatcher send payload to all stores, final View ask Store to get state

Point of Redux:

Make state changes more predictable

Reduc 3 pricipales:
1. Single source of truth ( the only data source from ):
states will all wrapped in one store, where has to dispatch the actions

2. State is read only
you could only change state by action

and action is dispatch by store:

3.  Changes are made with pure functions

pure functions == reducer,  action will send the request to reducer, reducer will received older state and return new state, keep reducer is pure and return value to be predictable, follow has 2 reducer, one is for filter and the other is for todos reducer, then use reducer to create store :

function visibilityFilter(state = 'SHOW_ALL', action) {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter
    default:
      return state
  }
}

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case 'COMPLETE_TODO':
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: true
          })
        }
        return todo
      })
    default:
      return state
  }
}

import { combineReducers, createStore } from 'redux'
let reducer = combineReducers({ visibilityFilter, todos })
let store = createStore(reducer)

This part is still abstract? follow has the concept diagram:

Process of Redux:
Look upper  diagram, as you could see,  view == components, as user has some operation to trigger action from view ( components) , store.dispatch need to change event content, pass to store for reducer to return next state, state tree has update, trigger view re-render

Redux ==> compositions of store, actions , reducer

Some points in Redux:

As you look some sample code upper in Reducer , do you notice that all the function return directly argument value ? which means in Redux it only accept Pure function, so if your function has re-calculate method like Math.random() , date now() or mapping etc it will not be allowed cause it has to stay simple, less side-effect ( well, that’s why it is called reducer)

Reducer that calculates the next state tree based on the previous state tree and the action being dispatched :

this is important because once you understand this is the key procedure in Reducer then it will make you easily to start to code

Learn more? this link is good to learn the basic concept by photo application
or by the Auther which has videos to show more

Docker: Installation

Installation

First you had to decide which version you need to install, like Windows or Mac

Here I will install Mac version:

1 go to docker.com and get the Stable version: https://docs.docker.com/docker-for-mac/install/#download-docker-for-mac

 

2. once download, go to Application, and click docker.dmg, then you will be start running installation

3. Once you see your docker has show on the right top menu bar, yes, that’s how easy it is, you had installed it already

 

4 open terminal, type

$docker –version

 

Once you see the version has been record, yes you are done

5 then go to top right menu Docker, right click to search Preference, here you could have further setting like start Docker as you log in or File Sharing path etc, but with Mac basically you could just leave as default setting

 

6 (Optional but recommend ) Install Kitematic, which is GUI interface allowed you easy to use Docker without typing lots command code

 

login your account docker hub

 

Then you all set, wow you have great interface to get any Docker image, container

 

So you are all done, you could use those command to check your images or containers:

$ docker images

$ docker ps -a

7 Create your first image

go to Kitematic, choice one of your image, here I tried hello-world-nginx

once created, Kitematic will pop to runing page, click web preview part

voila, how easy it is you had create your first page in your localhost:

8 Modified your first container page

stick on Kitematic, under volumes block , click right it will show the file path to running this image:

 

modified your index.html file

<p>Ok, so try out if it is working</p>

Once your process, Docker will stop running, so you just had to restart

then go to the browser check, it is had modified

 

Then type:

$ docker images

REPOSITORY                    TAG                 IMAGE ID            CREATED             SIZE

kitematic/hello-world-nginx   latest              03b4557ad7b9        2 years ago         7.91MB

You will see you had a Repository hello-world-nginx

Next, play how to install nginx web server

 

 

 

Docker introduction

As sometime we need to run the project over the Virtual Machines (server), there’s has VMware, Microsoft or any other cloud VM, for VM introduction you could see more details here, or about what use virtuabox 

And this is our founder Alex who build the dev env for php environment, you could download here and install to play with

So Docker == VM ? yes you could say so, but ! Docker === VM

Why? compare other VM container, Docker could be:

A adapte any environment, either in Windows or MAC ( this is the key point, how many developers sacrificed huge time to play around with !!!), or in cloud, dedicated or any virtue server, so it’s easy to move your project from dedicated to cloud

B Faster deployed, developer could work under the container and it is very faster and easy to deployer your project

C Easy Management, compare traditional vm, for updating job it will take lots of time and configuration, for Docker it become more easier

 

Here is funny image but quick for you to get understand :

Conception of Docker

  • Image:  like vm’s Guest OS or any env like ubuntu ( which includ Apache or any other applications), image could build Docker container

image is R\O, read only

  • Container:  create by image, each image could create serveral different containers , container could be run, start, stop and delete, when container running it will build by container layer and with R\W mode, you could take container as simple Linux env

  • Registry: it is like github, stock images as each repositories, so you could install image from pull or you could make your own image to push

 

next Installation

Cliche but important: optimise your website

Bits busy for those couple days, specially for optimise the E-commerce site which had order row over 450,000 and 6 years customers orders, it is time to optimise the site (opps, would it be too late?)

So today I will try to go through how to optimise a website(E-commerce)

For performance part, I think you guys pretty much know that you could go through follow:
1. Reduced image size, by base64, spirit Image or compressing image

2. Try minify the css, js part, if your site css using Less, Scss, Sass then you could ignore minify part, for Js it will more
be complex, try minify js, or if you write TypeScript or Babel then awesome you could ignore this part

3. Use Cachable for your page files, and the catch html content by desktop or mobile version, there’s some way to do those

4. using optimization rules in .htaccess file
The .htaccess file handles the way your web servers process your site with a lot of rules to improve your site speed
and with ETag, Expires headers, AddOutputFilterByType DEFLATE etc, follow is the simple:

########## Begin - ETag Optimization
## This rule will create an ETag for files based only on the modification
## timestamp and their size. 
## Note: It may cause problems on your server and you may need to remove it
FileETag MTime Size
# AddOutputFilterByType is now deprecated by Apache. Use mod_filter in the future.
AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript
# Enable expiration control
ExpiresActive On
# Default expiration: 1 hour after request
ExpiresDefault "now plus 1 hour"
# CSS and JS expiration: 1 week after request
ExpiresByType text/css "now plus 1 week"
ExpiresByType application/javascript "now plus 1 week"
ExpiresByType application/x-javascript "now plus 1 week"
 
# Image files expiration: 1 month after request
ExpiresByType image/bmp "now plus 1 month"
ExpiresByType image/gif "now plus 1 month"
ExpiresByType image/jpeg "now plus 1 month"
ExpiresByType image/jp2 "now plus 1 month"
ExpiresByType image/pipeg "now plus 1 month"
ExpiresByType image/png "now plus 1 month"
ExpiresByType image/svg+xml "now plus 1 month"
ExpiresByType image/tiff "now plus 1 month"
ExpiresByType image/vnd.microsoft.icon "now plus 1 month"
ExpiresByType image/x-icon "now plus 1 month"
ExpiresByType image/ico "now plus 1 month"
ExpiresByType image/icon "now plus 1 month"
ExpiresByType text/ico "now plus 1 month"
ExpiresByType application/ico "now plus 1 month"
ExpiresByType image/vnd.wap.wbmp "now plus 1 month"
ExpiresByType application/vnd.wap.wbxml "now plus 1 month"
 
ExpiresByType application/smil "now plus 1 month"
# Audio files expiration: 1 month after request
ExpiresByType audio/basic "now plus 1 month"
ExpiresByType audio/mid "now plus 1 month"
ExpiresByType audio/midi "now plus 1 month"
ExpiresByType audio/mpeg "now plus 1 month"
ExpiresByType audio/x-aiff "now plus 1 month"
ExpiresByType audio/x-mpegurl "now plus 1 month"
ExpiresByType audio/x-pn-realaudio "now plus 1 month"
ExpiresByType audio/x-wav "now plus 1 month"
 
# Movie files expiration: 1 month after request
ExpiresByType application/x-shockwave-flash "now plus 1 month"
ExpiresByType x-world/x-vrml "now plus 1 month"
ExpiresByType video/x-msvideo "now plus 1 month"
ExpiresByType video/mpeg "now plus 1 month"
ExpiresByType video/mp4 "now plus 1 month"
ExpiresByType video/quicktime "now plus 1 month"
ExpiresByType video/x-la-asf "now plus 1 month"
ExpiresByType video/x-ms-asf "now plus 1 month"

5. use CDN to load media:
CDN stands for content delivery network, it is an interconnected system of cache servers that use geographical proximity as a criteria for delivering Web content.
CDN is especially well suited for delivering media such as: video, audio, images, etc. So instead of loading those media from server, it loads from CDN, it’s more efficient and reliable.
For CDN, you could apply from your host server or of you have CMS website there’s nice plugin to help you quickly

6. choosing good web hosting

There’s lot choice and here has list you could take reference, for my cas I’m using Dedicated server CentOS Linux which has memory 63 Go, and I use Plesk allow setting your customise php configuration and that could be more flexible then web hosting

Also if you need to reduced Mysql resource running in memory rather than disk (which will run query faster), if you have dedicated serveur then this is the part you could do it

For request query part, this will be more complicated, you had to deal with your database Optimizing Queries with EXPLAIN or Indexes

As for myself understanding, Indexes is just like a book index, that tell you where you could find the chapter or some point articles, and in your database schema, there should be have some part point to help filtre more faster

For example if you do have more then 100,000 rows in table called #orders_list , it will be get very slow to request query to select (read) one of the order list, so you need index to separate those data structure of your table and help query to find out the right information more faster

sample to create index

As you need to find the table called user which has Name, age and address columns, there’s 2000 rows

and you are write a query to find a user name ‘Tess’:

SELECT * FROM User 
WHERE Name = 'Tess'

As there’s 2000 row, the query had to look at every single row and it will take long time, so now you could create a index to get faster:

CREATE INDEX name_index
ON User (Name)

So instead of search all columns Name, age and address, this will allow query search of User name by sorted alphabetically, in this case it will be more faster to get result

7 repaire or optimise your table database

If you use mysql, you could easily to optimise your table database just after selecting the table and click to choose optimise your table:

8. Try to test your web site through some site

https://tools.pingdom.com/

https://smallseotools.com/website-page-size-checker/

and there’s so many way to reduced your website size and get your performance better, it might take lots of work but it will really worth it cause every second as count by user

 

 

 

Symfony: service.yaml

In symfony package, you could find this file under : config directory

This file job is to figure out all of the services that should be in the container when symfony load

Services comes from external bundles, and also inject your own custom service,

Let’s look at service.yaml file:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: false       # Allows optimizing the container by removing unused services; this also means
                            # fetching services directly from the container via $container->get() won't work.
                            # The best practice is to be explicit about your dependencies anyway.

the point here is autowire: true, which means that any services registered in this file should have the autowiring behavior turned on

And look the key point follow:

App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

look at App: resource, that’s means:
Make all classes inside src/ available as services in the container.

that’s why you could put any class inside the src and make it called by symfony

to verify, go to terminal:

$ php bin/console debug:autowiring

as you could see what we had add the controller class before, it has put in autowiring lists

and don’t worry, for better performance:

Services are only Instantiated Once

App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

exclude key: if you know that some classes don’t need to be in the container, you can exclude them for a small performance boost in the dev environment only.

And what happend if you need to configure one service ?

Let’s do it:

Step 1 found out your services Id

Services Ids = Class Name

go to your terminal:
$ php bin/console debug:container –show-private

you could find your service Id, for example, for markdown:

App\Service\MarkdownHelper App\Service\MarkdownHelper

Step 2 inject monolog logger service
and in order to inject this sevice and make it autowiring by service.yaml

track back $ php bin/console debug:autowiring

Psr\Log\LoggerInterface
alias to monolog.logger

go to src/ Service/ MarkdownHelper.php

add use Psr\Log\LoggerInterface;

and inject argument LoggerInterface

public function __construct(AdapterInterface $cache, MarkdownInterface $markdown, LoggerInterface $logger)
{
    $this->cache = $cache;
    $this->markdown = $markdown;
    $this->logger = $logger;
}

add this logger info in parse function :

if (stripos($source, 'Spicy') !== false) {
    $this->logger->info('They are talking about spicy again!');
}

Step 3 find your service Information

go to terminal

$ ./bin/console debug:container monolog.logger

here you find Service ID monolog.logger

Step 4 Creating a new Logger Channel

Go to config/ packages, add monolog.yaml:

monolog:
    channels: ['markdown']

once add, go to terminal to clean catch:

$ ./bin/console cache:clear

$ ./bin/console debug:container log

you could see:
[44] monolog.logger.markdown

then this is said you had a new logger service – monolog.logger.markdown!

Step 5 Fetching this non-standard service to service.yaml

go to service.yaml file

add follow

# setup special, global autowiring rules
bind:
    $markdownLogger: '@monolog.logger.markdown'

 

Step 5 Logger object to your controller

go to src/Service/MarkdownHelper.php

public function __construct(AdapterInterface $cache, MarkdownInterface $markdown, LoggerInterface $markdownLogger)
{
    $this->cache = $cache;
    $this->markdown = $markdown;
    $this->logger = $markdownLogger;
}

notice you made changed LoggerInterface $logger to LoggerInterface $markdownLogger

because you had add bind logger object in your service.yaml

because we added it to _defaults, it applies to all our services.

github commit here

*** Thanks to bind, we can define what values are passed to specific argument names. But, we can go further and control what value should be passed for a specific type hint ***

Symfony: Security Fundamentals

Ok, you might want continue the login and register part
but hold on a second, here what you need to do first is understand the security fundamental in symfony

Actually security is like before you enter a president house, you need to have guardian give a pass card
so in programming, this pass card is an token

the token could assign you : allow go inside, not allow, or where you should go

so that’s hold this basic concept and dig into symfony security fundamental:
Security configuration: security.yml

go to config/packages, open security.yml

line 5

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false

make security: true

then go to your browser:

so you could see the page is not work, cause we set firewalls

move back:

security: false

then you could see the anonymous token from this code:

anonymous: ~

and from debugbar:

profiler:
anonymous: ~

so this is allowed anyone to access page cause so far there’s no any login system yet

but if we comment out this key?

#anonymous: ~

then you should see the page try to redirect to: http://127.0.0.1:8000/login

this is because you required to login to pass the firewall now

uncomment out, the page show up again

so this is very fundamental security part

And one more security part is access_control:

access_control:
    #- { path: ^/admin, roles: ROLE_ADMIN }
    #- { path: ^/profile, roles: ROLE_USER }

this is as you are role admin, you will lead to any /admin path, and if you are user, you will lead to any /profile path

or if you defined as follow:

access_control:
        - { path: ^/new, roles: ROLE_USER }
        - { path: ^/register, roles: ROLE_USER }

this means if you are user, you will go to /new path, or if you are not login yet, you will direct to /register path

with this access_control, you could define lots event and action ( like restric to admin page, blog page allow user to give comments) should go to, the most important thing to know is that only one access_control entry is matched on a request

if your request is not make clear, it will show ou this error:

Here is the doc, if you like to learn more