Yii 2 Interview Questions

Yii 2 Interview Questions

Following are the list of Top 20 Yii2 Interview Questions and answers for freshers and Experienced. If you have any Yii 2 Interview Questions that are asked to you in Yii interview then please post it in the comment section.

Best Yii 2 Interview Questions

Download Yii 2 Interview Questions PDF

Below are the list of Best Yii 2 Interview Questions and Answers

Yii 2 is one of the most popular Web programming framework written in PHP language.It can be used for developing all kinds of Web applications from blogs to e-commerce websites and ERP’s. Yii implements the MVC (Model-View-Controller) architectural pattern.

Helpers are static classes in Yii that simplify common coding tasks, such as string or array manipulations, HTML code generation, and so on.In Yii all helpers are kept under yii\helpers namespace.
You use a helper class in Yii by directly calling one of its static methods, like the following:

use yii\helpers\Html;
echo Html::encode('Test > test');

Formatter are Yii application component that is used format view data in readable format for users. By default the formatter is implemented by yii\i18n\Formatter which provides a set of methods to format data as date/time, numbers, currencies,and other commonly used formats. You can use the formatter like the following,

$formatter = \Yii::$app->formatter;

// output: January 1, 2014
echo $formatter->asDate('2014-01-01', 'long');
 
// output: 12.50%
echo $formatter->asPercent(0.125, 2);
 
// output: cebe@example.com
echo $formatter->asEmail('cebe@example.com'); 

// output: Yes
echo $formatter->asBoolean(true); 
// it also handles display of null values:

// output: (not set)
echo $formatter->asDate(null); 

Components are an independent set of code written to perform specific task in controllers.Yii applications are built upon components which are objects written to a specification. A component is an instance of CComponent or its derived class. Using a component mainly involves accessing its properties and raising/handling its events. The base class CComponent specifies how to define properties and events.

Also, Read Core PHP Interview Questions

Yii CModel is the base class that provides the common features needed by data model objects.CModel defines the basic framework for data models that need to be validated.All Models in Yii extends CModel class.

Active Record provides an object-oriented interface for accessing and manipulating data stored in databases. An Active Record class is associated with a database table, an Active Record instance corresponds to a row of that table, and an attribute of an Active Record instance represents the value of a particular column in that row. Instead of writing raw SQL statements, you would access Active Record attributes and call Active Record methods to access and manipulate the data stored in database tables. Read more from http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

Yii::app()->request->getUrl() method is used to get current url in Yii framework.

The latest version of Yii 2 is 2.0.15, released on March 20, 2018.

Yii 2.0 requires PHP 5.4.0 or above and runs best with the latest version of PHP 7 too.


   /
    backend/
    common/
        components/
        config/
            params.php
            params-local.php *
        lib/
            Pear/
            yii/
            Zend/
        migrations/
        models/
            Comment.php
            Extension.php
            ...
    console/
        commands/
            SitemapCommand.php
            ...
        config/
            main.php
            main-local.php *
            params.php
            params-local.php *
        runtime/
        yiic.php *
    frontend/
        components/
        config/
            main.php
            main-local.php *
            params.php
            params-local.php *
        controllers/
            SiteController.php
            ...
        lib/
        models/ 
            ContactForm.php
            SearchForm.php      
        runtime/
        views/
            layouts/
            site/
        www/
            assets/
            css/
            js/
            index.php *
    yiic
    yiic.bat

Source: http://www.yiiframework.com/wiki/155/the-directory-structure-of-the-yii-project-site/

You can install Yii2 by running below commands via composer:


composer global require "fxp/composer-asset-plugin:^1.3.1"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic

Features of Yii Framework

  • Model-View-Controller (MVC) design pattern
  • Form input and validation
  • Skinning and theming mechanism
  • Layered caching scheme
  • Unit and functionality testing
  • Automatic code generation
  • Error handling and logging
  • Database Access Objects (DAO), Query Builder, Active Record, DB Migration
  • AJAX-enabled widgets
  • Internationalization and localization
  • Authentication and authorization
  • Extension library
  • Detailed documentation

Below are list of some database related functions used in Yii 2 Framework

  • find(): Creates an yii\db\ActiveQueryInterface instance for query purpose.

    Usages:
    //Getting first record matching with condition
    $user = User::find()->where(['name' => 'Abc'])->one();
    
  • findAll(): Returns a list of active record models that match the specified primary key value(s) or a set of column values.

    Usages:
    // find the customers whose primary key value is 10
    $customers = Customer::findAll(10);
    // find customers whose age is 30 and whose status is active
    $customers = Customer::findAll(['age' => 30, 'status' => 'active']);
    
  • insert() :Inserts a row into the associated database table using the attribute values of this record.

    Usages:
    $customer = new Customer;
    $customer->name = $name;
    $customer->email = $email;
    $customer->insert();
    
  • delete() :Deletes the table row corresponding to this active record.

    Usages:
    $models = Customer::find()->where('status = 3')->all();
    foreach ($models as $model) {
        $model->delete();
    }
  • deleteAll() :Deletes rows in the table using the provided conditions.

    Usages:
    Customer::deleteAll('status = 3');
  • save() :Saves the current record.Usages:
    $customer = new Customer; // or $customer = Customer::findOne($id);
    $customer->name = $name;
    $customer->email = $email;
    $customer->save();

Read Best Codeigniter interview questions

Yii 2 requires PHP 5.4 or above with mbstring extension and PCRE-support.

Gii is module powerful module provided by Yii framework. It helps you create and generate fully customized forms, models, CRUD for database and more.You can enable Gii by configuring it in the modules property of the application. Depending upon how you created your application, you may find the following code is already provided in the config/web.php configuration file:

$config = [ ... ];

if (YII_ENV_DEV) {
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

index.php is first file that is called yii framework starts.In turn it will creates a new object of new yii\web\Application and start the application.

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

// load application configuration
$config = require(__DIR__ . '/../config/web.php');

// instantiate and configure the application
(new yii\web\Application($config))->run();

Yii follows below naming conventions

  • You can define table prefix when using Gii. In your case, you need to set it to tbl_. Then it should generate UserController instead of TblUserController.
  • The Yii Framework employs a class naming convention whereby the names of the classes directly map to the directories in which they are stored. The root level directory of the Yii Framework is the “framework/” directory, under which all classes are stored hierarchically.
  • Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged. Dot (.) is only permitted in place of the path separator.

When handling a user request, Yii 2.0 application will undergo the following stages:

  1. Pre-initialize the application with CApplication::preinit();
  2. Set up the error handling;
  3. Register core application components;
  4. Load application configuration;
  5. Initialize the application with CApplication::init()
    • Register application behaviors;
    • Load static application components;
  6. Raise an onBeginRequest event;
  7. Process the user request.
    • Collect information about the request;
    • Create a controller;
    • Run the controller;
  8. Raise an onEndRequest event;
  • Like most PHP frameworks, Yii implements the MVC (Model-View-Controller) architectural pattern and promotes code organization based on that pattern.
  • Yii takes the philosophy that code should be written in a simple yet elegant way. Yii will never try to over-design things mainly for the purpose of strictly following some design pattern.
  • Yii is a full-stack framework providing many proven and ready-to-use features: query builders and ActiveRecord for both relational and NoSQL databases; RESTful API development support; multi-tier caching support; and more.
  • Yii is extremely extensible. You can customize or replace nearly every piece of the core’s code. You can also take advantage of Yii’s solid extension architecture to use or develop redistributable extensions.
  • High performance is always a primary goal of Yii.
  • Larger Community.

Render function is used to render a view in Yii with specified layout whereas renderpartial is used to render only view layout is not included in view.

Renderpartial is basically used when we have to update a portion of page via AJAX.

Usage

render('yourviewname');
renderpartial('yourviewpartial');