CakePHP

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',
]);
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^