Skip to main content

39 Best Yii2 Interview Questions and Answers - PHP Frameworks

1: What Is Yii framework? 2: Why Yii Is So Fast?
3: Yii Versions? 4: What Are the Prerequisites Yii?
5: Why Use Yii 2.0 Framework? 6: What Are the Benefits of Yii over other Frameworks?
7: What's New in Yii Release 2.0? 8: What Is The First File That Gets Loaded When You Run A Application Using Yii?
9: What Is The First Function That Gets Loaded From A Controller? 10: What Are the core components of Yii2 framework?
11: What Are the great feature of Yii Framework? 12: What Are The Application Structure of Yii 2.0 Framework?
13: What Are the Naming Convention in Yii 2.0 Framework? 14: What Is Request Life-Cycle of Yii 2.0 framework?
15: What Are Yii helpers? 16: What Are the Core Helper Classes in Yii Framework?
17: What Are The Server Requirements to Install Yii 2.0 Framework? 18: How To Customizing Helper Classes in Yii Framework?
19: What Are The Directory Structure of Yii 2.0 Framework? 20: How To Create Directory Structure of Yii Framework?
21: What Are the Steps to Install Yii 2.0 Framework? 22: How To Configure Yii Application With Database?
23: How to get current controller name? 24: How to get current action name?
25: Which ORM does Yii2 supports? 26: What Is gii in Yii 2.0 and Why It Is used?
27: What Are formatter in Yii 2.0? What Is name of first file the loaded when Yii 2.0 framework starts? 28: What Are Components in Yii 2.0 framework?
29: How you can write a custom component and use it inside your app? 30: What Is CModel Class in Yii 2.0 framework?
31: What Is Active Record (AR) in Yii framework? 32: What Is Another Controller View in Yii?
33: How Can We Use Ajax In Yii? 34: Can we deploy applications to different servers?
35: What Is Required Properties in Yii Application? Why? 36: How to use module components and aliases? How to access module component?
37:How To Set Home Page Url in Yii? 38: How To get the Get Home Page Url in Yii?
39: How to change the existing style of Yii pagination? 40: List of PHP Frameworks Interview Questions

#1 Question

What Is Yii framework?

The Yii is a pure OOP based framework, free, open source, high-performance, component-based PHP framework for rapidly developing modern Web Applications and the name Yii is pronounced as Yee or [ji:]) means "simple and evolutionary" in Chinese.

The Yii is written in PHP and the stable release is 2.0.15.1 at March 21, 2018.
The Yii is a PHP framework for rapidly-developing, modern Web applications.

#2 Question

Why Yii Is So Fast?

The Yii framework is so faster because it is using the lazy-loading technique extensively.

#3 Question

Yii Versions?

The Yii framework currently has two major versions, one is 1.1 and other one is 2.0.

The version 1.0 is old and version 2.0 is a complete rewrite of Yii 1.0

#4 Question

What Are the Prerequisites Yii?

Which PHP version is required to install Yii 2.0?

The Yii 2.0 Framework requires PHP 5.4.0 or above and runs best with the latest versions of PHP 7.

#5 Question

Why Use Yii 2.0 Framework?

The Yii 2.0 Framework helps you to create modern web applications quickly, and make sure they perform well.
  • Easy to Install
  • Utilizes Modern Technologies
  • Highly Extensible
  • Encourages Testing
  • Simplifies Security
  • Shorten Development Time
  • Easy to Tune for Better Performance

#6 Question

What Are the Benefits of Yii over other Frameworks?

How does Yii Compare with Other Frameworks?

  • The Yii framework is a generic Web programming framework and it used for developing all kinds of Web applications quickly using PHP and It also very suitable for developing large-scale applications.
  • The primary goal of Yii or Yii 2.0 framework is - high performance.
  • The Yii framework is a full stack framework and ready-to-use features for both the relational and NoSQL databases.
  • The Yii framework implements the MVC (Model-View-Controller) architectural pattern.
  • The Yii framework is extremely extensible.
  • The Yii framework contains the Larger Community and it also purchased an unlimited license to the beautiful web-based rich text editor and Redactor.

#7 Question

What's New in Yii Release 2.0?

  • The Yii 2.0 framework support for PSR-4 class auto loading, simpler namespaces, faster loading, and improved usability for developers.
  • The Yii 2.0 framework added performance and security improvements.
  • The Yii 2.0 framework added RESTful API integration.
  • The Yii 2.0 framework added improvement on URL handling and processing.
  • Now Yii 2.0 framework, Translations of core messages available in 26 languages.

#8 Question

What Is The First File That Gets Loaded When You Run A Application Using Yii?

index.php: This file loaded first when we Run an Yii application.

#9 Question

What Is The First Function That Gets Loaded From A Controller?

index : This is the first function that gets loaded from a controller.

#10 Question

What Are the core components of Yii2 framework?

  • db: Used for database connection
  • cache: Used for manage caching functionality
  • session: Used for Session management
  • clientScript: Used for manage JavaScript and CSS
  • coreMessages: Used for provides translated core messages
  • errorHandler: Used for manage errors handling
  • assetManager: Used for manage the publishing of private asset files
  • authManager: Used for manage role-based access control
  • themeManager: Used for Manage themes
  • urlManager: Used for URL parsing and creation functionality
  • statePersister: Used for mechanism for persisting global state
  • securityManager: Used for Security Management

#11 Question

What Are the great feature 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 and Yii also support I18N and make it easy to provide localized versions of your applications
  • Authentication and authorization
  • Extension library
  • Detailed documentation
  • Error handling, logging and testing - yes, Yii delivers

#12 Question

What Are The Application Structure of Yii 2.0 Framework?

The most important directories and files in your web application and it looks like:
basic/         : This is the application base path
composer.json  : It used by Composer, describes package information
config/        : It contains application and other configurations
console.php    : It used for configure the console application 
web.php        : It used for configure the Web application
commands/      : It contains console command classes
controllers/   : It contains controller classes
models/        : It contains model classes
runtime/       : It contains files generated by Yii during runtime, such as logs and cache files
vendor/        : It contains the installed Composer packages, including the Yii framework itself
views/         : It contains view files
web/           : The application Web root, contains Web accessible files
assets/        : It contains published asset files (JavaScript and css) by Yii
index.php      : The entry (or bootstrap) script for the application
yii            : The Yii console command execution script

#13 Question

What Are the Naming Convention in Yii 2.0 Framework?

The Yii 2.0 Framework uses a simple standard to set names.

Routes that refer respectively to module, controller, and the action requested take the following format:
ModuleID/ControllerID/ActionID
The ModuleID is an optional. It also looks like format is ControllerID/ActionID
The ModuleID must be specified in the module's configuration property, under the same name.
The ControllerID and ActionID should contain only English characters in lowercase, digits, underscores, dashes, and forward slashes.
URL Conventions: By default, Yii recognizes URLs with the following format:
http://hostname/index.php?r=ControllerID/ActionID
The r : refers to the route.

An example of route is -
http://hostname/index.php?r=site/index
In the above Route URL, the site is the ControllerID and index is the ActionID

#14 Question

What Is Request Life-Cycle of Yii 2.0 framework?

The following diagram shows how an application handles a request.

The Yii application handles a request:
  • A user makes a request to the entry script web/index.php.
  • The entry script loads the application configuration and creates an application instance to handle the request.
  • The application resolves the requested route with the help of the request application component.
  • The application creates a controller instance to handle the request.
  • The controller creates an action instance and performs the filters for the action.
  • If any filter fails, the action is cancelled.
  • If all filters pass, the action is executed.
  • The action loads some data models, possibly from a database.
  • The action renders a view, providing it with the data models.
  • The rendered result is returned to the response application component.
  • The response component sends the rendered result to the user's browser.
Source - https://www.yiiframework.com/doc/guide/2.0/en/start-workflow

#15 Question

What Are Yii helpers?

The Yii Framework provides different types of classes that help you to simplify a common coding task, such as string manipulations, array manipulations or HTML code generation.

In Yii Framework, all helper classes are static classes and all helpers are kept under the 'yii\helpers' namespace.


Example: You use a helper class by directly calling one of its static methods, like the following:
use yii\helpers\Html;
echo Html::encode('Test > test');

#16 Question

What Are the Core Helper Classes in Yii Framework?

The following core helper classes are:
  • ArrayHelper
  • Console
  • FileHelper
  • FormatConverter
  • Html
  • HtmlPurifier
  • Imagine
  • Inflector
  • Json
  • Markdown
  • StringHelper
  • Url
  • VarDumper

#17 Question

What Are The Server Requirements to Install Yii 2.0 Framework?

The Yii 2.0 requires following things:
  • 1. PHP 5.4 or above
  • 2. mbstring extension
  • 3. PCRE-support

#18 Question

How To Customizing Helper Classes in Yii Framework?

To customize a core helper class, we should create a new class extending from the helpers base class.
For example,
< ?php
namespace yii\helpers;

class ArrayHelper extends BaseArrayHelper
{
    public static function merge($x, $y)
    {
        // your custom implementation
    }
}

#19 Question

What Are The Directory Structure of Yii 2.0 Framework?

Below is the directory structure we are using:
/
 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
At the top level, we have four directories:
  • backend
  • frontend
  • console
  • common
The directory structure of each application is very similar. For example, for frontend and backend, they both have these directories:
  • Components: It contains components as like - helpers, widgets that are only used by this application
  • Config: It contains the configuration used by the application
  • Controllers: It contains controller classes
  • Lib: It contains third party libraries that are only used by this application
  • Models: It contains model classes that are specific for the application
  • Runtime: It stores dynamically generated files
  • Views: It stores controller actions view scripts
  • www: The web root for this application
The directory structure is quite different between basic and advanced templates. The following subdirectories:
  • assets
  • config
  • controllers
  • models
  • runtime
  • views
  • web

#20 Question

How To Create Directory Structure of Yii Framework?

We can use the below commands for Creating Directory Structure.
mkdir -p enterprise/{backend/{components,config,controllers,lib,models,runtime,views/{layouts,site},www/{assets,css,js}},common/{components,config,lib/{pear,yii,zend},migrations,models},console/{commands,config,runtime},frontend/{components,config,controllers,lib,models,runtime,views/{layouts,site},www/{assets,css,js}}}
OR if you prefer, you may use the top level directories down approach:
mkdir -p backend/{components,config,controllers,lib,models,runtime,views/{layouts,site},www/{assets,css,js}}
mkdir -p common/{components,config,lib/{pear,yii,zend},migrations,models}
mkdir -p console/{commands,config,runtime}
mkdir -p frontend/{components,config,controllers,lib,models,runtime,views/{layouts,site},www/{assets,css,js}}

#21 Question

What Are the Steps to Install Yii 2.0 Framework?

To install Yii Framework, you need to following below steps. Step 1: Download the Yii code from its official website or github. Step 2: Extract the code into your server root directory. Step 3: Open command line terminal and type the following command.
php path-to-yii-folder/framework/yiic webapp [webapp-name]
Step 4: After execution of above command, it will ask you for the confirmation of creating your application, on selecting yes, this will create a default application.

#22 Question

How To Configure Yii Application With Database?

What Are the database related functions in Yii 2.0 Framework? The database related functions are:
  • find()
  • findAll()
  • insert()
  • delete()
  • deleteAll()
  • save()
  • findByPk()
  • findBy()
For Example, find() method: Using the below query, getting the first record matching with condition
$user = User::find()->where(['name' => 'Anil Singh'])->one();
findAll() Method : Find the users whose primary key value is 20.
$users = User::findAll(20);
Find users whose age is 50 and whose status is active
$users = User::findAll(['age' => 50, 'status' => 'active']);
insert() Method :
$user = new User;
$user->name = $name;
$user->email = $email;
$user->insert();
delete() Method:
$models = User::find()->where('status = 30')->all();
foreach ($models as $model) {
    $model->delete();
}
deleteAll() Method :
User::deleteAll('status = 30');
save() Method :
$user = new User;
$user->name = $name;
$user->email = $email;
$user->save();

#23 Question

How to get current controller name?

//Controller Name
echo Yii::$app->controller->id;

#24 Question

How to get current action name?

echo Yii::$app->controller->action->id;

#25 Question

Which ORM does Yii2 supports?

Active Record, it provides an object-oriented interface for accessing and manipulating data stored in databases.

#26 Question

What Is gii in Yii 2.0 and Why It Is used?

The gii is a web-based code-generator module provided by Yii framework. It helps you create and generate fully customized forms, models, CRUD for database and more

#27 Question

What Are formatter in Yii 2.0? What Is name of first file the loaded when Yii 2.0 framework starts?

The Formatter are Yii application component that is used format view data in readable format for users. Formatter provides a set of commonly used data formatting methods. Formatter is configured as an application component in yii\base\Application by default. You can access that instance via Yii::$app->formatter. You may customize the formatting rules by configuring the formatter component in the application configuration. Configuring Formatter example:
return [
    'components' => [
        'formatter' => [
            'dateFormat' => 'dd.MM.yyyy',
            'decimalSeparator' => ',',
            'thousandSeparator' => ' ',
            'currencyCode' => 'EUR',
       ],
    ],
];
Yii provides a set of other useful formatters for different situations:
  • [[yii\i18n\Formatter::asEmail()|email]] - the value is formatted as a mailto-link.
  • [[yii\i18n\Formatter::asImage()|image]] - the value is formatted as an image tag.
  • [[yii\i18n\Formatter::asUrl()|url]] - the value is formatted as a hyperlink.
  • and so on...

#28 Question

What Are Components in Yii 2.0 framework?

The components are the main building blocks of Yii applications. Components are instances of yii\base\Component, or an extended class. The three main features that components provide to other classes are:
  • Properties
  • Events
  • Behaviors
Separately and combined, these features make Yii classes much more customizable and easier to use. For example for date picker,
use yii\jui\DatePicker;

echo DatePicker::widget([
    'language' => 'ru',
    'name'  => 'country',
    'clientOptions' => [
        'dateFormat' => 'yy-mm-dd',
    ],
]);

#29 Question

How you can write a custom component and use it inside your app?

Step 1: Make a folder named "components" in your project root folder. Step 2: To write your custom component inside components folder e.g. YourComponent.php
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
 
class MyComponent extends Component
{
 public function welcome()
 {
  echo "Hello..Welcome to MyComponent";
 }
 
}
Step 3: Add your component inside the config/web.php file e.g.
'components' => [
         'mycomponent' => [
            'class' => 'app\components\MyComponent',
        ],
    ]
Step 4: Now you can use your component method "welcome" inside any of your app controller actions.
namespace app\controllers;
use Yii;

class TestController extends \yii\web\Controller
{
    public function actionWelcome()
    {
       Yii::$app->mycomponent->welcome();
    }
}

#30 Question

What Is CModel Class in Yii 2.0 framework?

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.

#31 Question

What Is Active Record (AR) in Yii framework?

What Is difference between “render” and “renderpartial” in Yii Framework? The render() is commonly used to render a view that corresponds to what a user sees as a "page" in your application. The render() partial we can add some portion of code in another file. The renderPartial() is commonly used to render a "piece" of a page. The render(‘myview’) will render the file ‘myview’, complete with the $layout that’s specified in your controller. The renderPartial(‘myview’) will render ONLY the contents for ‘myview’. And you can use it with special keys to return result in variable and to echo this html where you want. Render() we can add whole file in another file Example : The render() is used to display page with layout or theme.
$this->render('login',array('model'=>$model));
Example: renderPartial double Slash:
< ?php $this->renderPartial('//controller/view')?>
"//"- will render the view protected/views/controller/view.php renderPartial Single Slash
< ?php $this->renderPartial('/controller/view')?>
"/"- will render the view from current module

#32 Question

What Is Another Controller View in Yii?

By using renderPartial() method, You can call the view of another controller. You can reuse view files. You can call function in view and controller files. Example :
< ?php $this->renderPartial(
    'application.views.user.index',
    array(
        'data'=>'Welcome',
        'model'=>$model,
    )
);?>

#33 Question

How Can We Use Ajax In Yii?

Yes, we can. use ajax helper

#34 Question

Can we deploy applications to different servers?

Yes! We can, because we store each application in a separate directory, if needed, we can deploy them to different servers.

#35 Question

What Is Required Properties in Yii Application? Why?

In any web application, you should at least configure two properties: id and basePath. id: The id property specifies a unique ID that differentiates an application from others. Example for $id public property: An ID that uniquely identifies this module among other modules which have the same parent
public string $id = null
basePath: The basePath property specifies the root directory of an application. Example for $basePath public property: The root directory of the module.
public string getBasePath ( )
public void setBasePath ( $path )

#36 Question

How to use module components and aliases? How to access module component?

If you have placed your components in modules then.
//Current Module object 
  $module = Yii::$app->controller->module;
  $module->component_id

#37 Question

How To Set Home Page Url in Yii?

You can use the below code to set the Home Page Url :
........
'homeUrl'=>array('user/index'),
'components'=>array(
    ........
),
.......

#38 Question

How To get the Get Home Page Url in Yii?

$homeurl=Yii::app()->homeUrl;

//redirect home page
Yii::app()->request->redirect(Yii::app()->homeUrl);

#39 Question

How to change the existing style of Yii pagination?

We can change the existing style of Yii pagination. I followed two steps to create the customized pagination of Yii. Disable Yii Pager.css using the below code,
< ?php
'widgetFactory'=>array(
    'widgets'=>array(
        'CLinkPager'=>array(
            'maxButtonCount'=>5,
            'cssFile'=>false,
        ),
    ),
),
?>
This is full configuration for Pagination in Yii 2.0 as following,
< ?php
LinkPager::widget([
    'pagination' => $pages,
    //Css option for container
    'options' => ['class' => ''],
    //First option value
    'firstPageLabel' => ' ',
    //Last option value
    'lastPageLabel' => ' ',
    //Previous option value
    'prevPageLabel' => ' ',
    //Next option value
    'nextPageLabel' => ' ',
    //Current Active option value
    'activePageCssClass' => 'p-active',
    //Max count of allowed options
    'maxButtonCount' => 8,

    // Css for each options. Links
    'linkOptions' => ['class' => ''],
    'disabledPageCssClass' => 'disabled',

    // Customzing CSS class for navigating link
    'prevPageCssClass' => 'p-back',
    'nextPageCssClass' => 'p-next',
    'firstPageCssClass' => 'p-first',
    'lastPageCssClass' => 'p-last',
]);
By Anil Singh | Rating of this article (*****)

Popular posts from this blog

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from ...

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVA...

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin...

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan ...

.NET Core MVC Interview Questions and Answers

» OOPs Interview Questions Object Oriented Programming (OOP) is a technique to think a real-world in terms of objects. This is essentially a design philosophy that uses a different set of programming languages such as C#... Posted In .NET » .Net Constructor Interview Questions A class constructor is a special member function of a class that is executed whenever we create new objects of that class. When a class or struct is created, its constructor is called. A constructor has exactly the same name as that of class and it does not have any return type… Posted In .NET » .NET Delegates Interview Questions Delegates are used to define callback methods and implement event handling, and they are declared using the "delegate" keyword. A delegate in C# is similar to function pointers of C++, but C# delegates are type safe… Posted In .NET » ASP.Net C# Interview Questions C# was developed by Microsoft and is used in essentially all of their products. It is mainly used for ...