Thursday, July 20, 2017

New Features In PHP 7 That You Should Have A Look At

Now a days PHP is the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.

New Features In PHP 7

But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven't missed anything. Just to avoid the confusion with a dead project, PHP's latest release was named to PHP 7.

Let's take a deeper dive. Let's check out what new features PHP 7 has to offer. And what improvements those features will bring forth.

  • Performance (Speed Improvement)
  • Scalar Type Declarations
  • Return Type Declarations
  • Combined Comparison Operator
  • Null Coalesce Operator
  • Anonymous Classes
  • Unicode Codepoint Escape Syntax
  • Closure call() Method
  • Filtered unserialize()
  • IntlChar Class
  • Expectations
  • Group use Declarations
  • Generator Return Expressions
  • Generator Delegation
  • Integer Division with intdiv()
  • session_start() Options
  • preg_replace_callback_array() Function
  • CSPRNG Functions
  • Support for Array Constants in define()
  • Reflection Additions

Let's take a look on every feature in details:

Performance (Speed Improvement)


The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. This is a result of refactoring the Zend Engine to use more compact data structures and less heap allocations/deallocations. The performance gains on real world applications will vary, though many applications seem to receive a ~100% performance boost - with lower memory consumption too! After it's release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase in server response times with PHP 7. For further details on benchmarks 


Scalar Type Declarations


PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.
By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.

Non-Strict Example

[code]
function getSum(float $a, float $b) {
   return $a + $b;
}

getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string "7 week" changed to float(7.0)
//with a "Notice: A non well formed numeric value encountered"

//returns float(13)
getSum(1.1, "2.2");

//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)

getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)
[/code]

Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.

Strict Example

PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding "strict_types=1" on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.
While using a strict type-declaration, if a mismatch occurs, a "Fatal Error" occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let's just cut the talk and take a look at an example with strict types turned on.

declare(strict_types=1);
function getSum(float $a, float $b) {
    return $a + $b;
}

getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given

getSum(1.8,  "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given

getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)

Setting "declare strict_type" to "1", the first two calls that pass a string produces a Fatal error: "Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given". With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “widening”, which includes adding .0 at the end of the integer value. This returns (5.1).

Return Type Declaration


The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.

function getSum(float $a, float $b) : float {

}

Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.

Non-Strict Integer Example

Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.

function getSum(float $a, float $b) : int {
    return $a + $b;
}

getSum(6, "7 week");
// changes int(6) to float(6.0) & string("7 week") to float(7.0)
// returns int(13);

getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)

getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)


Strict Integer Example

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.

declare(strict_types=1);
function getSum(float $a, float $b) : int {
    // return $a + $b;
    // The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
    return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)

Benefits
These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.

Combined Comparison Operator


The combined comparison operator (or spaceship operator) is a shorthand notation for performing three-way comparisons from two operands. It has an integer return value that can be either:


  • a positive integer (if the left-hand operand is greater than the right-hand operand)
  • 0 (if both operands are equal)
  • a negative integer (if the right-hand operand is greater than the left-hand operand)


The operator has the same precedence as the equality operators (==, !=, ===, !==) and has the exact same behaviour as the other loose comparison operators (<, >=, etc). It is also non-associative like them too, so chaining of the operands (like 1 <=> 2 <=> 3) is not allowed.

// compares strings lexically
var_dump('PHP' <=> 'Node'); // int(1)

// compares numbers by size
var_dump(123 <=> 456); // int(-1)

// compares corresponding array elements with one-another
var_dump(['a', 'b'] <=> ['a', 'b']); // int(0)
Objects are not comparable, and so using them as operands with this operator will result in undefined behaviour.

Null Coalesce Operator


The null coalesce operator (or isset ternary operator) is a shorthand notation for performing isset() checks in the ternary operator. This is a common thing to do in applications, and so a new syntax has been introduced for this exact purpose.

// Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';


// compares corresponding array elements with one-another
var_dump(['a', 'b'] <=> ['a', 'b']); // int(0)
Objects are not comparable, and so using them as operands with this operator will result in undefined behaviour.

Null Coalesce Operator

The null coalesce operator (or isset ternary operator) is a shorthand notation for performing isset() checks in the ternary operator. This is a common thing to do in applications, and so a new syntax has been introduced for this exact purpose.

// Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';

Anonymous Classes


Anonymous classes are useful when simple, one-off objects need to be created.

// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }

    use SomeTrait;
});

/** Output:
object(class@anonymous)#1 (1) {
  ["Command line code0x104c5b612":"class@anonymous":private]=>
  int(10)
}
*/
Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class' protected properties or methods, the anonymous class can extend the outer class. To use the private or protected properties of the outer class in the anonymous class, they must be passed through its constructor:

<?php

class Outer
{
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1()
    {
        return 3;
    }

    public function func2()
    {
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop)
            {
                $this->prop3 = $prop;
            }

            public function func3()
            {
                return $this->prop2 + $this->prop3 + $this->func1();
            }
        };
    }
}

echo (new Outer)->func2()->func3(); // 6

Unicode Codepoint Escape Syntax


This enables a UTF-8 encoded unicode codepoint to be output in either a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

echo "\u{aa}"; // ª
echo "\u{0000aa}"; // ª (same as before but with optional leading 0's)
echo "\u{9999}"; // 香

Closure call() Method


The new call() method for closures is used as a shorthand way of invoking a closure whilst binding an object scope to it. This creates more perfomant and compact code by removing the need to create an intermediate closure before invoking it.

class A {private $x = 1;}

// Pre PHP 7 code
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX(); // 1

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A); // 1

Filtered unserialize()


This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar Class


The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

printf('%x', IntlChar::CODEPOINT_MAX); // 10ffff
echo IntlChar::charName('@'); // COMMERCIAL AT
var_dump(IntlChar::ispunct('!')); // bool(true)
In order to use this class, the Intl extension must be installed.

BC Breaks

Classes in the global namespace must not be called IntlChar.

Expectations


Expectations are backwards compatible enhancement to the older assert() function. They enable for zero-cost assertions in production code, and provide the ability to throw custom exceptions on error.

The assert() function's prototype is as follows:

void assert (mixed $expression [, mixed $message]);
As with the old API, if $expression is a string, then it will be evaluated. If the first argument is falsy, then the assertion fails. The second argument can either be a plain string (causing an AssertionError to be triggered), or a custom exception object containing an error message.

ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
With this feature comes two PHP.ini settings (along with their default values):


  • zend.assertions = 1
  • assert.exception = 0

zend.assertions has three values:


  • 1 = generate and execute code (development mode)
  • 0 = generate code and jump around at it at runtime
  • -1 = don't generate any code (zero-cost, production mode)

assert.exception means that an exception is thrown when an assertion fails. This is switched off by default to remain compatible with the old assert() function.

Group use Declarations


This gives the ability to group multiple use declarations according to the parent namespace. This seeks to remove code verbosity when importing multiple classes, functions, or constants that come under the same namespace.

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Generator Return Expressions


This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finishing yielding values.

// IIFE syntax now possible - see the Uniform Variable Syntax subsection in the Changes section
$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

// output:
// 1
// 2
// 3
Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator Delegation


Generator delegation builds upon the ability of being able to return expressions from generators. It does this by using an new syntax of yield from <expr>, where can be any Traversable object or array. This will be advanced until no longer valid, and then execution will continue in the calling generator. This feature enables yield statements to be broken down into smaller operations, thereby promoting cleaner code that has greater reusability.

function gen()
{
    yield 1;
    yield 2;

    return yield from gen2();
}

function gen2()
{
    yield 3;

    return 4;
}

$gen = gen();

foreach ($gen as $val)
{
    echo $val, PHP_EOL;
}

echo $gen->getReturn();

// output
// 1
// 2
// 3
// 4

Integer Division with intdiv()


The intdiv() function has been introduced to handle division where an integer is to be returned.

var_dump(intdiv(10, 3)); // int(3)

session_start() Options


This feature gives the ability to pass in an array of options to the session_start() function. This is used to set session-based php.ini options:

session_start(['cache_limiter' => 'private']); // sets the session.cache_limiter option to private
This feature also introduces a new php.ini setting (session.lazy_write) that is, by default, set to true and means that session data is only rewritten if it changes.

preg_replace_callback_array() Function


This new function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function (second parameter of preg_replace_callback()) to be polluted with lots of branching (a hacky method at best).

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

Function Signature:

string preg_replace_callback_array(array $regexesAndCallbacks, string $input);
$tokenStream = []; // [tokenName, lexeme] pairs

$input = <<<'end'
$a = 3; // variable initialisation
end;

// Pre PHP 7 code
preg_replace_callback(
    [
        '~\$[a-z_][a-z\d_]*~i',
        '~=~',
        '~[\d]+~',
        '~;~',
        '~//.*~'
    ],
    function ($match) use (&$tokenStream) {
        if (strpos($match[0], '$') === 0) {
            $tokenStream[] = ['T_VARIABLE', $match[0]];
        } elseif (strpos($match[0], '=') === 0) {
            $tokenStream[] = ['T_ASSIGN', $match[0]];
        } elseif (ctype_digit($match[0])) {
            $tokenStream[] = ['T_NUM', $match[0]];
        } elseif (strpos($match[0], ';') === 0) {
            $tokenStream[] = ['T_TERMINATE_STMT', $match[0]];
        } elseif (strpos($match[0], '//') === 0) {
            $tokenStream[] = ['T_COMMENT', $match[0]];
        }
    },
    $input
);

// PHP 7+ code
preg_replace_callback_array(
    [
        '~\$[a-z_][a-z\d_]*~i' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_VARIABLE', $match[0]];
        },
        '~=~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_ASSIGN', $match[0]];
        },
        '~[\d]+~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_NUM', $match[0]];
        },
        '~;~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_TERMINATE_STMT', $match[0]];
        },
        '~//.*~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_COMMENT', $match[0]];
        }
    ],
    $input
);

CSPRNG Functions


This feature introduces two new functions for generating cryptographically secure integers and strings. They expose simple APIs and are platform-independent.

Function signatures:

string random_bytes(int length);
int random_int(int min, int max);
Both functions will emit an Error exception if a source of sufficient randomness cannot be found.

Support for Array Constants in define()


The ability to define array constants was introduced in PHP 5.6 using the const keyword. This ability has now been applied to the define() function too:

define('ALLOWED_IMAGE_EXTENSIONS', ['jpg', 'jpeg', 'gif', 'png']);

Reflection Additions


Two new reflection classes have been introduced in PHP 7. The first is ReflectionGenerator, which is used for introspection on generators:

class ReflectionGenerator
{
    public __construct(Generator $gen)
    public array getTrace($options = DEBUG_BACKTRACE_PROVIDE_OBJECT)
    public int getExecutingLine(void)
    public string getExecutingFile(void)
    public ReflectionFunctionAbstract getFunction(void)
    public Object getThis(void)
    public Generator getExecutingGenerator(void)
}
The second is ReflectionType to better support the scalar and return type declaration features:

class ReflectionType
{
    public bool allowsNull(void)
    public bool isBuiltin(void)
    public string __toString(void)
}
Also, two new methods have been introduced into ReflectionParameter:

class ReflectionParameter
{
    // ...
    public bool hasType(void)
    public ReflectionType getType(void)
}
As well as two new methods in ReflectionFunctionAbstract:

class ReflectionFunctionAbstract
{
    // ...
    public bool hasReturnType(void)
    public ReflectionType getReturnType(void)

}

These were the new features in PHP 7.

Wednesday, May 3, 2017

Top Laravel Interview Questions with Answers

Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax. Now a days Laravel is very popular PHP framework so mostly companies works on this framework. Here we are listing top Laravel interview questions with answers.



1. What is Laravel?
Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax.

2. What are Advantages of Laravel?

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel
3. Explain about Laravel Project?
Laravel is one of the most popular PHP frameworks used for Web Development.
This framework is with expressive, elegant syntax.
It is based on model–view–controller (MVC) architectural pattern.

4. What are the feature of Laravel 5.4?
  • Introducing Laravel Dusk
  • Introducing Laravel Mix 
  • New Markdown Mail in Laravel 5.4 
  • Slots and Components in Laravel 5.4
  • Real-time (automatic) Facades in Laravel 5.4
  • TrimStrings and ConvertEmptyStringsToNull middleware in Laravel 5.4
  • JSON localization files in Laravel 5.4
  • Binding method calls in the service container in Laravel 5.4 
  • The --model flag for creating better resourceful controllers in Laravel 5.4
  • Laravel Collections' updates--higher order messaging and new methods--in Laravel 5.4 
5. Compare Laravel with Codeigniter?
        Laravel                                                                                        Codeigniter
Laravel is a framework with expressive, CodeIgniter is a powerful PHP                       elegant syntax                                                                    framework
Development is enjoyable, creative                                 Simple and elegant toolkit to create full-         experience                                                                         featured web applications.
Laravel is built for latest version of PHP                         Codeigniter is an older more mature                                                                                                         framework
It is more object oriented compared                                 It is less object oriented compared to               to CodeIgniter.                                                                  Laravel.
Laravel community is still small, but it is                        Codeigniter community is large.
growing very fast.

6. What are Bundles,Reverse Routing and The IoC container ?

Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.

Also Read: PHP Interview Questions with Answers

7. How to set Database connection in Laravel?
Database configuration file path is : config/database.php
Following are sample of database file

[code]  'mysql' => [
    'read' => [
        'host' => 'localhost',
    ],
    'write' => [
        'host' => 'localhost'
    ],
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
], [/code]

8. How to enable the Query Logging?
[code] DB::connection()->enableQueryLog();[/code]

9. How to use select query in Laravel?
[code] $users = DB::select('select * from users where city_id = ?', 10);
if(!empty($users)){
    foreach($users as $user){

    }
} [/code]

9. How to use Insert Statement in Laravel?
[code] DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]); [/code]

10. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]); [/code]

11. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]);[/code]

12. How to use delete Statement in Laravel?
[code] DB::delete('delete from  users where id = ?', [1015]); [/code]

13. Does Laravel support caching?
Yes, Its provides.

Also Read: Top Zend Framework Interview Questions with Answers

14. I've already created a database table that I want to use with Laravel's ORM. How would I setup a class to do that?
Laravel's ORM is called Eloquent. There are two main ways to go about doing this. The first one would be to physically write a class:
[code] <?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'students';
}[/code]

And the second one would be to use the artisan CLI, which generates a class:
[code] php artisan make:model students [/code]

15. Laravel comes with a PHP CLI called artisan. What is your favorite artisan command?
There are so many things that the CLI does out of the box. Even if they don't have a favorite command, they should be able to explain what some of them do. Here's a sample of available top-level commands:
Available commands:
  •   clear-compiled      Remove the compiled class file
  •   down                Put the application into maintenance mode
  •   env                 Display the current framework environment
  •   help                Displays help for a command
  •   inspire             Display an inspiring quote
  •   list                Lists commands
  •   migrate             Run the database migrations
  •   optimize            Optimize the framework for better performance
  •   serve               Serve the application on the PHP development server
  •   tinker              Interact with your application
  •   up                  Bring the application out of maintenance mode
16. Laravel 5 has built in CSRF protection on every route. How would I go about turning that off?
  Hopefully they mention that CSRF protection is important, but since we're asking them to turn it off they might not mention it which is OK. You'd easily turn it off by going into Kernel.php and removing it from the middleware stack that is ran on every route.

This is also a good place to ask about middleware in general and make sure they both understand what middleware is and why it's important.

17. List out some benefits of Laravel over other Php frameworks.
  • Setup and customization process is  easy and fast as compared to others.
  • Inbuilt Authentication System.
  • Supports multiple file systems
  • Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  • Eloquent ORM (Object Relation Mapping) with PHP active record implementation. 
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.
Also Read: WordPress Interview Questions And Answers

18. What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.

19. How to install laravel via composer ?

 composer create-project laravel/laravel your-project-name version

 20. How to check laravel current version ?
 You can check the current version of your Laravel installation using the --version option of artisan command Usages:
 [code] php artisan --version [/code]

21. What is php artisan. List out some artisan command ?

PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command:
  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan --versian
  • php artisan make modal modal_name
  • php artisan make controller controller_name 
22. Explain Events in laravel ?

An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation,that allow us  to subscribe and listen for events in our application.
Below are some events examples in laravel :
A new user has registered
A new comment is posted
User login/logout
New product is added.

23. How to enable query log in laravel?

Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();

Also Read: Most Popular Codeigniter Interview Questions with Answers

24. How to turn off CRSF protection for a route in Laravel?

In "app/Http/Middleware/VerifyCsrfToken.php"
 //add an array of Routes to skip CSRF check
  private $exceptUrls = ['controller/route1', 'controller/route2'];
 //modify this function

[code]public function handle($request, Closure $next) {
 //add this condition foreach($this->exceptUrls as $route) {
 if ($request->is($route)) {
  return $next($request);
 }
}
return parent::handle($request, $next);
}[/code]

25. How can you get users IP address  in Laravel ?

[code] public function getUserIp(Request $request){
          // Getting ip address of remote user

            return $user_ip_address=$request->ip();
}[/code]

26. How to use custom table in Laravel Modal We can use custom table in laravel by overriding protected $table property of Eloquent. Below is sample uses

[code] class User extends Eloquent{
 protected $table="my_user_table";

}[/code]

27. How to define Fillable Attribute in Laravel Modal ?
You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses

[code] Class User extends Eloquent{

protected $fillable =array('id','first_name','last_name','age');


}[/code]

28. In which directory controllers are located in Laravel ?

We kept all controllers in
app/http/Controllers directory

29. What does PHP compact function do ?
PHP compact function takes each key and tries to find a variable with that same name.If variable is found , them it builds an associative array.

30. Define ORM ?
Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

Also Read: Apache Solr Interview Questions and Answers

31. How to create a record in Laravel using eloquent? 

To create a new record in the database using laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage

[code] public function saveProduct(Request $request )
 $product = new product;
 $product->name = $request->name;
 $product->description = $request->name;
 $product->save(); [/code]

 32. What is the purpose of the Eloquent cursor() method in laravel?

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage. Example Usage

[code] foreach (Product::where('name', 'bar')->cursor() as $flight) { //do some stuff } [/code]

33. How to get Logged in user info in laravel ?

Auth::User() function is used to get Logged in user info in laravel. Usage:

[code] if(Auth::check()){

$loggedIn_user=Auth::User();
dd($loggedIn_user);

} [/code]


34. What are Closures in laravel ?
Closures is an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.


Tuesday, May 2, 2017

Most Popular Codeigniter Interview Questions with Answers

CodeIgniter is an open-source software rapid development web framework, for use in building dynamic web sites with PHP. CodeIgniter is popular model–view–controller (MVC) development pattern. CodeIgniter is most often noted for its speed when compared to other PHP frameworks. Today mostly web development happens in CodeIgniter framework. In PHP interview a lot of questions are asked from CodeIgniter. Here we are listing most popular CodeIgniter Interview Questions with Answers.


1. What is Codeigniter?

Codeigniter is the most popular open source PHP framework. It is very simple and lightweight. It can be used to develop any kind of web project from small website to large scale of application.

2. What are the most prominent features of CodeIgniter?

A list of most prominent features of CodeIgniter:

It is an open source framework and free to use.
It is extremely light weighted.
It is based on Model View Controller (MVC) pattern.
It has full featured database classes and support for several platforms.
It is extensible. You can easily extend system by using your own libraries, helpers etc.
Excellent documentation.
Security and XSS Filtering
File uploading, session management, pagination, data encryption
Flexible URI Routing
Zip encoding class
Error logging
Full page caching
Localization

3. Explain the folder structure of CodeIgniter.

If you download and unzip CodeIgniter, you will get the following file structure/folder structure:


Application     
cache
Config
Controllers
core
errors
helpers
hooks
language
libraries
logs
models
thirdparty
views

system

core
database
fonts
helpers
language
libraries

4. How to access config variable in codeigniter? 

[code] $this->config->item('variable name'); [/code]

5. How to unset session in codeigniter?

[code] $this->session->unsetuserdata('somename');  [/code]

6. How do you get last insert id in codeigniter? 

 [code]  $this->db->insertid(); [/code]


7. Why use Hooks in Codeigniter

Hooks are the special feature of Codeigniter that allows to change the inner functionality of framework without making any change in core files of framework. The Hooks are defined in application/config/hooks.php.

8. What are different types of hook points in CodeIgniter?

A list of different types of hook points in CodeIgniter:

post_controller_constructor
pre_controller
post_sytem
pre_system
cache_override
display_override
post_controller

9. How can you load a view in CodeIgniter?

View can't be accessed directly. It is always loaded in the controller file. Following function is used to load a view page:

[code]  $this->load->view('page_name');  [/code]


10. What is routing in Codeigniter?

Instead of accessing files directly from browser, Routing enables to serve files differently. Routing is an important part of Codeigniter that enables to customize default URL pattern according to requirement to use your own and it redirect automatically to matched URL pattern by specified controller and function.

11. How to load Model in CodeIgniter?

Models are PHP classes that are designed to work with information in your database. In CodeIgniter, Model classes are stored in your application/models/ folder. The models will typically be loaded and called from within your controller functions. To load a model you will use the following function:
[code] $this->load->model('Model_name'); [/code]

12. What are the Helpers in CodeIgniter?

The Helpers are the group of functions in a specific category that helps to perform particular functions. There are many helpers in CodeIgniter that you can use according to your requirement. The major CodeIgniter helpers are URL Helpers that assist in creating link, Form Helpers that help you create form elements, Text Helpers to perform various text formatting routines, Cookie Helpers to set and read cookies, File Helpers to help you deal with files etc.

13. List out different types of hook point in Codeigniter?

Different types of hook point in Codeigniter includes
post_controller_constructor
pre_controller
post_sytem
pre_system
cache_override
display_override
post_controller

14. Mention what are the security parameter for XSS in CodeIgniter?

Codeigniter has got a cross-site scripting hack prevention filter. This filter either runs automatically or you can run it as per item basis, to filter all POST and COOKIE data that come across.  The XSS filter will target the commonly used methods to trigger JavaScript or other types of code that attempt to hijack cookies or other malicious activity. If it detects any suspicious thing or anything disallowed is encountered, it will convert the data to character entities.

15. Explain how you can link images/CSS/JavaScript from a view in code igniter?

In HTML, there is no Codeigniter way, as such it is a PHP server side framework. Just use an absolute path to your resources to link images/CSS/JavaScript from a view in CodeIgniter
/css/styles.css

/js/query.php

/img/news/235.gpg

16. Explain what is inhibitor in CodeIgniter?

For CodeIgniter, inhibitor is an error handler class, using the native PHP functions like set_exception_handler, set_error_handler, register_shutdown_function to handle parse errors, exceptions, and fatal errors.

17. Mention what is the default URL pattern used in Codeigniter framework?

Codeigniter framework URL has four main components in default URL pattern.  First we have the server name and next we have the controller class name followed by controller function name and function parameters at the end. Codeigniter can be accessed using the URL helper. For example http://servername/controllerName/controllerFunction/parameter1/parameter2.

18. Explain how you can extend the class in Codeigniter?

To extend the native input class in CodeIgniter, you have to build a file named application/core/MY_Input.php and declare your class with
[code] Class MY_Input extends CI_Input {

} [/code]

19.How can you load multiple helper files?

To load multiple helper files, specify them in an array,
[code] $this->load->helper(  
array('helper1', 'helper2', 'helper3')  
);  [/code]

20. Explain how you can prevent CodeIgniter from CSRF?

There are several ways to protect CodeIgniter from CSRF, one way of doing is to use a hidden field in each form on the website.  This hidden field is referred as CSRF token; it is nothing but a random value that alters with each HTTP request sent. As soon as it is inserted in the website forms, it gets saved in the user’s session as well.  So, when the form is submitted by the users, the website checks whether it is the same as the one saved in the session. If it is same then, the request is legitimate.

21. Explain how you can enable CSRF (Cross Site Request Forgery) in CodeIgniter?

You can activate CSRF (Cross Site Request Forgery) protection in CodeIgniter by operating your application/config/config.php file and setting it to
[code] $config [ 'csrf_protection'] = TRUE; [/code]
If you avail the form helper, the form_open() function will insert a hidden csrf field in your forms automatically


22. What are CodeIgniter drivers?

These are special type of library that has a parent class and many child classes. These child classes have access to the parent class, but not to their siblings. Drivers are found in system/libraries folder.

23. How to initialize a driver in CodeIgniter?

To initialize a driver, write the following syntax,
[code] $this->load->driver('class_name');  [/code]

Thursday, March 2, 2017

WordPress Interview Questions And Answers

I am going to provide the most frequent queries you can expect to be asked while going for the Wordpress job interview. These questions are asked by many popular companies in the interview round to the candidates applying for the job of CMS developer or WordPress Developer. Many queries in this post are really tricky and can confuse even the professional developers so if you are going for the job interview then I highly recommend you to check these latest WordPress CMS interview questions and answers.



What is WordPress?

Word press is a best Open Source CMS which allows it to be used free of cost.  You can use it on any kind of personal or commercial website without have to pay a single penny for it. It is built on PHP/MySQL (which is again Open Source) and licensed under GPL.

How safe is website on WordPress?

 The word press is safe to operate but still it is suggested to keep updating with the latest version of WordPress to avoid hacking.

Are there any limitations to a WordPress web site?

You can use WordPress for e-commerce sites, membership sites, photo galleries and any other type of site you can think of. The web site is created using the same html code as any other site so there are no limitations there either.

Do you need to have a blog in order to use WordPress for site?

WordPress was originally used as blogging software though it has since become popular for website also.  It is not necessary to have a blog to use wordpress.  Still having blog is commendable as it will help in search engine optimization.

From SEO point of view is wordpress helpful? Will it show the website on Google?

 It is one of the benefit of using wordpress, it has inbuilt SEO search engine. Also, you can have an additional plug-in in wordpress to help with SEO and rank on a popular search engine like Google.

What is the current version of wordpress?

You need to quote the current version of WordPress available in market along with the release date.

What are the types of hooks in WordPress and mention their functions?

There are two types of hooks 1) Action hooks 2) Filter hooks

Hooks allow user to create WordPress theme or plugin with shortcode without changing the original files. Action hooks allow you to insert an additional code from an outside resource, whereas, Filter hooks will only allow you to add a content or text at the end of the post.


What do you mean by custom field in wordpress?

Custom field is a meta-data that allows you to store arbitrary information to the wordpress post. Through custom field extra information can be added to the post.

What are the positive aspects of wordpress?

Few positive aspects of wordpress are

Easy installation and upgrade
In-built SEO engine
Easy theme system
Flexibility
Multilingual- available in more than 70 languages
Own data- no unwanted advert on your website
Flexibility and Easy publishing option

What are the rules that you have to follow for wordpress plugin development?

Create a unique name
Create the plugin’s folder
Create a sub-folder for PHP files,  translations and assets
Create the main plug-in file and fill in header information
Create activation and de-activation functions
Create an uninstall script
Create a readme.txt file
To detect paths to plugin file use proper constants and functions
11) What is the prefix of wordpress tables by default?

By default, wp_ is the prefix for wordpress.

Why does WordPress use MySQL?

MySQL is widely available database server and is extremely fast.  It is an open source and it is available at no cost also it is supported by many low-cost Linux hosts so its easy for anyone to host their website.

Is it possible to rename the WordPress folder?

Yes, it is possible to rename the WordPress folder.  If WordPress is already installed you have to login to the weblog as the administrator and then change the settings

WordPress address (URI)  :

Blog address( URI) :

After making the changes, you can rename the folder or directory with the WordPress file in it.

How many tables are there in WordPress by default?

There are about 11 tables in WordPress by default. Note: With succeeding releases of WordPress this number will change. You need to check phpMyAdmin to determine the number of tables in a vanilla version of latest WordPress installation.

What is WordPress loop?

To display post WordPress use PHP code, this code is known as loop.

How you can disable the WordPress comment?

If you go on dashboard under options-discussion there is a comment “ Allow people to post comment” try unchecking the comment.

What are the steps you can take if your WordPress file is hacked?

Install security plug-ins like WP security
Re-install the latest version of WordPress
Change password and user-ids for all your users
Check your themes and plug-ins are up to date

What are the template tags in WordPress?

In WordPress template tags is a code that instructs WordPress to "do" or "get" something.

Does WordPress have cookies?

Yes, WordPress have cookies and WordPress uses cookies for verification of users while logged in.

Also Read: html5 Interview Questions and Answers for Freshers

In what case you don’t see plugin menu?

You can’t see your plugin menu when the blog is hosted on free wordpress.com as you cannot add plugin there.  Also, if you do not have an account of an administrator level on your WordPress is not possible to see plugin.

At what instance you get locked out of your WordPress admin and see your website as a blank screen?

This would likely happen when you have pasted a code from a website with wrong formats, also when you have pasted a code in a wrong location. It may also happen when your IP is banned

Why you use a static front page in wordpress?

Some WordPress users wants their WordPress installation to be more than a blog site. To give their page a look more like a real website page some users use static front page.

What are the plugins you can use to create contact form in WordPress?

To create a contact form in WordPress you can use plugin like Gravity forms or also you can use a free plugin contact form 7.

Why widget does not show up in the sidebar?

While using widget you have to ensure whether your theme supports the widget and if it does then it must show the sidebar.  If in any case if it happens that you don’t see the sidebar then it might be missing the “function.php” file or file similar to that.  This can also happen if you have forgot to save the changes in the widget or refreshing the older display of the page.

Is there any limitation for using WordPress?

No, there is no limitation for using WordPress.  WordPress can be used for innumerable purpose membership site, e-commerce site, photo-gallery and many more.

How is creating a site on wordpress.org different from wordpress.com?

Most of the things are similar in both except the choices of themes and the usage of plugins.

Why wordpress.com is considered more secure than wordpress.org?

WordPress.com is considered more secure than wordpress.org because they limit the themes and also does not allow installing plugin’s.  However the security is more dependable on how the hosting company is hosting your website(wordpress.org) & also what are the steps they are taking to prevent the security problems.

Does de-activated plugins slow down a WordPress site?

No, de-activated plugins cannot slow down the WordPress site.  Wordpress only loads the active plugins and ignores everything else.

In what case we cannot recommend WordPress to our client?

We cannot recommend WordPress on following situation:

If client is working on non-CMS base project
If site wants complex or innovative e-commerce
In case of enterprise intranet solution
Sites requiring custom scripting solutions.

What are the essential features you look for a theme?

Theme selection differs according to the requirement, but an ideal theme would be something that would not restrict to use the number of pages, plugins or static homepage.

How Custom theme is different than Normal theme?

Custom theme allows for SEO search, but with a SEO plugin available it would not make much difference to normal theme. One benefit using the Custom theme is that it allows to make the changes without going much into the coding part.

How you can create a static page with WordPress?

To create a static page in wordpress, in the page section  you have to upload a php files to the server in the theme folder, and then select that as your template.  This allows you to add any page and look that you wanted for your blog and it will remain static.

Is there any other CMS better WordPress?

WordPress is no doubt a good CMS, but Drupal and Joomla are among the best CMS you can work with.

Which is the best multi-lingual plugin for wordpress?

Keeping all the limitations in mind, WPML would be the best multi-lingual plugin for wordpress .

Can you update your own content on the site?

It depends on the type of the site or project, but yes one can update their own content on the site.

Also Read: jQuery Interview Questions and Answers for Freshers

What are meta-tags?

Meta-tags are keywords and description used to display website or page information.

What should one use for plugin development - custom post types or custom database tables?

There is no specific preference for plugin development; it depends on what type of plugin’s one has to develop. Though few recommend custom post type, as it has few benefits comparison to custom database table.

Can you host WordPress using  Amazon web services such as EC2, RDS, EBS etc?

Yes, you can host using Amazon web services.

Is there any way to write series in WordPress?

You can use organize series plugin to write series in wordpress.

What are the reasons why one should not hack WordPress core file?

The best reason not to hack the core files is that whatever you might be doing has to be reworked as a patch.

Saturday, February 25, 2017

html5 Interview Questions and Answers for Freshers

HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It is the fifth and current version of the HTML standard.
It was published in October 2014 by the World Wide Web Consortium (W3C) to improve the language with support for the latest multimedia, while keeping it both easily readable by humans and consistently understood by computers and devices such as web browsers, parsers, etc. HTML5 is intended to subsume not only HTML 4, but also XHTML 1 and DOM Level 2 HTML.



Here are we study some popular and frequently asked interview questions for HTML5.

What is HTML5?
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.

New Semantic Elements − These are like <header>, <footer>, and <section>.

Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag.

Persistent Local Storage − To achieve without resorting to third-party plugins.

WebSocket − A a next-generation bidirectional communication technology for web applications.

Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE).

Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript.

Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins.

Geolocation − Now visitors can choose to share their physical location with your web application.

Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics.

Drag and drop − Drag and drop the items from one location to another location on a the same webpage.

Which browsers support HTML5?
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.

The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.

Is HTML5 backward compatible with old browsers?
Yes! HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers.

It is suggested to detect support for individual HTML5 features using a few lines of JavaScript.

Are HTML tags case sensitive?
No!

What is the purpose of 'section' tag in HTML5?
This tag represents a generic document or application section. It can be used together with h1-h6 to indicate the document structure.

is the purpose of 'article' tag in HTML5?
This tag represents an independent piece of content of a document, such as a blog entry or newspaper article.

What is the purpose of 'aside' tag in HTML5?
This tag represents a piece of content that is only slightly related to the rest of the page.

What is the purpose of 'header' tag in HTML5?
This tag represents the header of a section.

What is the purpose of 'footer' tag in HTML5?
This tag represents a footer for a section and can contain information about the author, copyright information, et cetera.
What is the purpose of ‘nav’ tag in HTML5?
This tag represents a section of the document intended for navigation.

What is the purpose of ‘dialog’ tag in HTML5?
This tag can be used to mark up a conversation.

What are custom attributes in HTML5?
A custom data attribute starts with data- and would be named based on your requirement. Following is the simple example−

<div class=”example” data-subject=”physics” data-level=”complex”>

</div>
The above will be perfectly valid HTML5 with two custom attributes called data-subject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes.

What is Web Forms 2.0?
Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and remove a great deal of the need for tedious scripting and styling that was required in HTML4.

What is the purpose of datetime input control in Web form 2.0?
It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC.

What is the purpose of datetime-local input control in Web form 2.0?
It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with no time zone information.

What is the purpose of date input control in Web form 2.0?
It represents a date (year, month, day) encoded according to ISO 8601.

What is the purpose of month input control in Web form 2.0?
It represents a date consisting of a year and a month encoded according to ISO 8601.

What is the purpose of week input control in Web form 2.0?
It represents a date consisting of a year and a week number encoded according to ISO 8601

What is the purpose of time input control in Web form 2.0?
It represents a time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601.

What is the purpose of email input control in Web form 2.0?
This accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in email@example.com format.

What is the purpose of url input control in Web form 2.0?
This accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format.

What is the purpose of ‘output’ tag in HTML5?
HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script.

What is the purpose of ‘placeholder’ attribute in HTML5?
HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provides a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds.

What is the purpose of ‘autofocus’ attribute in HTML5?
This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field.

What is the purpose of 'required' attribute in HTML5?
HTML5 introduced a new attribute called required which would insist to have a value in an input control.
Yes! HTML5 allows embeding SVG directly using <svg>…</svg> tag.

Can you use MathML tags directly in HTML5 without any plugin?
Yes! The HTML syntax of HTML5 allows for MathML elements to be used inside a document using <math>…</math> tags.

What are the drawbacks of cookies?
Cookies have following drawbacks−
Cookies are included with every HTTP request, thereby sending data unencrypted over the internet.

Cookies are limited to about 4 KB of data . Not enough to store required data.
What do you mean by session storage in HTML5?
HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window i.e. session and as soon as you close the window, session would be lost.

What do you mean by local storage in HTML5?
HTML5 introduces the localStorage attribute which would be used to access a page’s local storage area without no time limit and this local storage will be available whenever you would use that page.

When a session storage data gets deleted?
The Session Storage Data would be deleted by the browsers immediately after the session gets terminated.

When a local storage data gets deleted?
local storage data has no time limit. To clear a local storage setting you would need to call localStorage.remove(‘key’); where ‘key’ is the key of the value you want to remove. If you want to clear all settings, you need to call localStorage.clear() method.

What is Server Side Events in HTML5?
Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you can push DOM events continously from your web server to the visitor’s browser.

The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling.

Server-sent events standardizes how we stream data from the server to the client.

How to utilize a server-sent event in HTML5?
To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document.

The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events.

The URL would point to a PHP, PERL or any Python script which would take care of sending event data consistently.

What are the steps of server side scripts for SSE?
server side script should send Content-type header specifying the type text/event-stream as follows−

print "Content-Type: text/event-stream\n\n”;
After setting Content-Type, server side script would send an Event − tag followed by event name. Following example would send Server-Time as event name terminated by a new line character.

print "Event: server-time\n”;
Final step is to send event data using Data − tag which would be followed by integer of string value terminated by a new line character as follows−

$time = localtime();
print "Data: $time\n";

What are web sockets?
Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

Following is the API which creates a new WebSocket object.

var Socket = new WebSocket(url, [protocal] );
Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.
What is the purpose of Socket.readyState atribute of WebSocket?
The readonly attribute readyState represents the state of the connection. It can have the following values:

A value of 0 indicates that the connection has not yet been established.

A value of 1 indicates that the connection is established and communication is possible.

A value of 2 indicates that the connection is going through the closing handshake.

A value of 3 indicates that the connection has been closed or could not be opened.

What is the purpose of ‘canvas’ tag in HTML5?
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.

What is the purpose of ‘audio’ tag in HTML5?
HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document. The current HTML5 draft specification does not specify which audio formats browsers should support in the audio tag. But most commonly used audio formats are ogg, mp3 and wav.

You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format.

What is the purpose of ‘video’ tag in HTML5?
HTML5 supports <video> tag which is used to embed a video file in an HTML or XHTML document.The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most commonly used video formats are−

Ogg − Ogg files with Thedora video codec and Vorbis audio codec.

mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec.

You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format.
What is Geolocation API in HTML?
HTML5 Geolocation API lets you share your location with your favorite web sites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.

Today most of the browsers and mobile devices support Geolocation API. The geolocation APIs work with a new property of the global navigator object ie. Geolocation object which can be created as follows:

var geolocation = navigator.geolocation;
The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.

What is purpose of getCurrentPosition() method of geolocation object of HTML5?
This method retrieves the current geographic location of the user.

What is purpose of watchPosition() method of geolocation object of HTML5?
This method retrieves periodic updates about the current geographic location of the device.

What is purpose of clearPosition() method of geolocation object of HTML5?
This method cancels an ongoing watchPosition call.

What are Web Workers?
Web Workers do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads.

Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
What is the purpose of datetime-local input control in Web form 2.0?
It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with no time zone information.




Thursday, February 23, 2017

Apache Solr Interview Questions and Answers

Solr is an open source enterprise search platform, written in Java, from the Apache Lucene project. Its major features include full-text search, hit highlighting, faceted search, real-time indexing, dynamic clustering, database integration, NoSQL features and rich document (e.g., Word, PDF) handling. Providing distributed search and index replication, Solr is designed for scalability and fault tolerance.Solr is the second-most popular enterprise search engine after Elasticsearch.


Solr is very popular now a days for web development. Here we are listing most popular and frequently asked Solr interview questions with answers:

What is Apache Solr?
Apache Solr is a standalone full-text search platform to perform searches on multiple websites and index documents using XML and HTTP. Built on a Java Library called Lucence, Solr supports a rich schema specification for a wide range and offers flexibility in dealing with different document fields. It also consists of an extensive search plugin API for developing custom search behavior.

What file contains configuration for data directory?
Solrconfig.xml file contains configuration for data directory.

What file contains definition of the field types and fields of documents?
schema.xml file contains definition of the field types and fields of documents.

What are the features of Apache Solr?
• Allows Scalable, high performance indexing Near real-time indexing
• Standards-based open interfaces like XML, JSON and HTTP
• Flexible and adaptable faceting
• Advanced and Accurate full-text search
• Linearly scalable, auto index replication, auto failover and recovery
• Allows concurrent searching and updating
• Comprehensive HTML administration interfaces
• Provides cross-platform solutions that are index-compatible

What is Apache Lucene?
Supported by Apache Software Foundation, Apache Lucene is a free, open-source, high-performance text search engine library written in Java by Doug Cutting. Lucence facilitates full-featured searching, highlighting, indexing and spellchecking of documents in various formats like MS Office docs, HTML, PDF, text docs and others.

What is request handler?
When a user runs a search in Solr, the search query is processed by a request handler. SolrRequestHandler is a Solr Plugin, which illustrates the logic to be executed for any request.Solrconfig.xml file comprises several handlers (containing a number of instances of the same SolrRequestHandler class having different configurations).

What is the use of field type?
Field type defines how Solr would interpret data in a field and how that field can be queried.

What all information is specified in field type?
A field type includes four types of information:
• Name of field type
• Field attributes
• An implementation class name
• If the field type is Text Field , a description of the field analysis for the field type.

Explain Faceting in Solr.
As the name suggests, Faceting is the arrangement and categorization of all search results based on their index terms. The process of faceting makes the searching task smoother as users can look for the exact results.

Also Read: PHP Interview Questions for Freshers with Answers

What are the advantages and disadvantages of Standard Query Parser?
Also known as Lucence Parser, the Solr standard query parser enables users to specify precise queries through a robust syntax. However, the parser’s syntax is vulnerable to many syntax errors unlike other error-free query parsers like DisMax parser.

Define Dynamic Fields?
Dynamic Fields are a useful feature if users by any chance forget to define one or more fields. They allow excellent flexibility to index fields that have not been explicitly defined in the schema.
analyzing of input text is performed at the time of searching or indexing and at query time. Most Solr applications use Custom Analyzers defined by users. Remember, each Analyzer has only one Tokenizer. You can define an analyzer in the application using the below syntax:

What is the use of tokenizer?
It is used to split a stream of text into a series of tokens, where each token is a subsequence of characters in the text. The token produced are then passed through Token Filters that can add, remove or update the tokens. Later,that field is indexed by the resulting token stream.

What is phonetic filter?
Phonetic filter creates tokens using one of the phonetic encoding algorithms in the org.apache.commons.codec.language package.

What is SolrCloud?
Apache Solr facilitates fault-tolerant, high-scalable searching capabilities that enable users to set up a highly-available cluster of Solr servers. These capabilities are well revered as SolrCloud.

What is copying field?
It is used to describe how to populate fields with data copied from another field.

What is Highlighting?
Highlighting refers to the fragmentation of documents matching the user’s query included in the query response. These fragments are then highlighted and placed in a special section, which is used by clients and users to present the snippets. Solr consists of a number of highlighting utilities having control over different fields. The highlighting utilities can be called by Request Handlers and reused with standard query parsers.

Name different types of highlighters?
There are 3 highlighters in Solr:
• Standard Highlighter: provides precise matches even for advanced queryparsers.
• FastVector Highlighter: Though less advanced than Standard Highlighter, it works better for more languages and supports Unicode breakiterators.
• Postings Highlighter: Much more precise, efficient and compact than the above vector one but inappropriate for a more number of query terms.

What is the use of stats.field?
It is used to generate statistics over the results of arbitrary numeric functions.

What command is used to see how to use the bin/Solr script?
Execute $ bin/Solr –helpto see how to use the bin/Solr script.

Also Read: jQuery Interview Questions and Answers for Freshers

Which syntax is used to stop Solr?
$ bin/solr stop -p 8983 is used to stop Solr.

Which command is used to start Solr in foreground?
$ bin/solr start –f is used to start Solr in foreground.

$ bin/solr status is used to check Solr running status.

Give the syntax to start the server.
$ bin/solr start is used to start the server.

How to shut down Apache Solr?
Solr is shut down from the same terminal where it was launched. Click Ctrl+C to shut it down.

What data is specified by Schema?
Schema declares –
• how to index and search each field
• what kinds of fields are available
• what fields are required
• what field should be used as the unique/primary key

Name the basic Field types in Solr.
• date
• long
• double
• text
• float

How to install Solr?
The three steps of Installation are:
1. Server-related files, e.g. Tomcat or start.jar (Jetty)
2. Solr webapp as a .war
3. Solr Home which comprises the data directory and configuration files

What are the important configuration files of Solr?
Solr supports two important configuration files
1. solrconfig.xml
2. schema.xml

What are the most common elements in solrconfig.xml?
The most common elements in solrconfig.xml are:
1. Search components
2. Cache parameters
3. Data directory location
4. Request handlers