Home | About | Web Stories | View All Posts

26 Feb 2022

Best Questions Answers How To Prepare Yii2 framework Interview

Yii is a fast, secure and high-performance component based PHPframework for developing large-scale Web applications rapidly. Below are the list of frequently asked TOP 25+, Yii2 framework interview questions and answers for freshers and experienced.

Yii2 - Interview - Questions and Anaswers

  1. What is Yii?
  2. What do you know about Yii Versions?
  3. What is the latest version of Yii?
  4. What are the server requirements for Yii 2.0 installation?
  5. How to establish connection with database in Yii2?
  6. Can you tell me five features of Yii2 framework?
  7. What is the path alias in yii2?
  8. What do you know about route in Yii2?
  9. How to implement the pretty URL or SEO Friendly URL structure in Yii2?
  10. How can you disable or remove index.php from URL in Yii2?
  11. How to run sql in controller file and passing the array into view file?
  12. What is Gii in Yii2?
  13. What do you know about Active Record(AR) in Yii2 framework?
  14. Why Yii2 framework is called faster loading application?
  15. What is widgets in Yii2
  16. What are Yii2 helpers?
  17. What are components in Yii2?
  18. What is module in Yii2?
  19. What are extensions in Yii2?
  20. What are formatter in Yii2 ?
  21. What is difference between 'render' and 'renderpartial' in Yii?
  22. What is renderFile() method or function in Yii2 framework?
  23. What is CModel Class in Yii2?
  24. What is CFormModel in Yii2?
  25. How can you display or flash various kind of messages - error, notice etc in Yii2?
  26. How to get current url in Yii2?
  27. What is difference between baseUrl and homeUrl in Yii2?
  28. How to change the default controller in Yii2 framework?
  29. How to change the default action in Yii2 framework?
  30. What do you know about directory structure of the Yii2 application?
  31. What is the use of "common" directory in the Yii2 application?
  32. How to get current controller name in Yii2?
  33. How to get current action name in Yii2?
  34. How to enable maintenance mode in Yii2?
  35. How to get and set session in Yii?
  36. What is the difference between Yii1.0 & Yii2.0?
  37. Can you list method names for database related functions in Yii2?


Q. - What is Yii?
Ans. - Yii is MVC architecture based object oriented PHP web application framework. It can be an acronym for "Yes It Is!" and pronounced as "Yee". It is very fast, secure and component based efficient PHP framework and is used for making wide range of Web applications like – CMS, ERP, eCommerce projects, RESTful Web services, blog, forums etc.

You can check the MVC architecture involvement and explanation in Yii 2.0 framework at "Understanding Yii2 model view and controller functionality in simplest way".

Q. - What do you know about Yii Versions?
Ans. - The Yii structure as of now has two significant versions - 1.1 and 2.0. Yii 2.0 is a complete rewrite of Yii, adopting the most recent technologies and protocols, including Composer, PSR, namespaces, traits, and so on. As we know namespaces and traits is the latest features of PHP. Yii most recent version is 2.0.45

Q. - What is the latest version of Yii?
Ans. - Version 2.0.40(released in December 2020)

Q. - What are the server requirements for Yii 2.0 installation?
Ans. - It requires PHP 5.4 or higher version, mbstring extension, and PCRE-support. You can run the Yii 2.0 inbuilt requirement checker at http://hostname/yii2projectname/requirements.php

For example using xampp server -
http://localhost/yii2cms/requirements.php

You can check the Yii 2.0 framework installation process at "Yii2 Installation using composer method".

Q. - How to establish connection with database in Yii2?
Ans. - You can edit or update the database connection in the component configuration file in Yii2. Below is the configuration file path(xampp server localhost) and code. You can edit or update the host, database name(dbname), database username and password in this file.

File path - C:\xampp\htdocs\yii2project\common\config\main-local.php

Connection code -
<?php

return [
    'components' => [
      
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2project_db', // host, dbname - change here
            'username' => 'root', // db username change here
            'password' => '', // db password change here
            'charset' => 'utf8',
        ],
        -------------------------
        -------------------------
        ?>

Q. - Can you tell me few best features of Yii2 framework?
Ans. - Below are few best features -
  1. Gii module for automatic code generation and fast development
  2. MVC architecure with easy installation
  3. Error handing and form validation
  4. Highly extensible and unit testable
  5. Lazy loading feaure for fast and high performance
  6. RESTful API development support
  7. Ready-to-use features for query builders and ActiveRecord(AR)
Q. - What is the path alias in yii2?
Ans. - Yii provides a set of aliases to easily reference commonly used file paths and URLs. You can get the path of a 'path alias' using the codes at any view file in frontend or backend using the codes as like - "echo Yii::getalias('@app');", "echo Yii::getalias('@web');"

Below are the list of predefined path aliases list in Yii2 -

  • @app: Your application root directory (either frontend or backend or console depending on where you access it from)
      <?php  echo Yii::getalias('@app'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\frontend
  • @vendor: Your vendor directory on your root app install directory
      <?php  echo Yii::getalias('@vendor'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\vendor
  • @runtime: Your application files runtime/cache storage folder
      <?php  echo Yii::getalias('@runtime'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\frontend\runtime
  • @web: Your application base url path
      <?php  echo Yii::getalias('@web'); ?>
      //It will produce - /yii2projectname/frontend/web
  • @webroot: Your application web root
      <?php  echo Yii::getalias('@webroot'); ?>
      //It will produce - C:/xampp/htdocs/yii2projectname/frontend/web
  • @common: Alias for your common root folder on your root app install directory
      <?php  echo Yii::getalias('@common'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\common
  • @frontend: Alias for your frontend root folder on your root app install directory
      <?php  echo Yii::getalias('@frontend'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\frontend
  • @backend: Alias for your backend root folder on your root app install directory
      <?php  echo Yii::getalias('@backend'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\backend
  • @console: Alias for your console root folder on your root app install directory
      <?php  echo Yii::getalias('@console'); ?>
      //It will produce - C:\xampp\htdocs\yii2projectname\console
  • @yii, the directory where the BaseYii.php file is located (also called the framework directory).
      <?php  echo Yii::getalias('@yii'); ?>
      //It will produce - C:\xampp\htdocs\yii2cms2022\vendor\yiisoft\yii2
  • @bower, the root directory that contains bower packages. Defaults to @vendor/bower.
      <?php  echo Yii::getalias('@bower'); ?>
      //It will produce - C:\xampp\htdocs\yii2cms2022/vendor/bower-asset
  • @npm, the root directory that contains npm packages. Defaults to @vendor/npm.
      <?php  echo Yii::getalias('@npm'); ?>
      //It will produce - C:\xampp\htdocs\yii2cms2022/vendor/npm-asset
Custom definition for path alias -
We can also create custom aliases in Yii2. We can define our own alias for a file path or URL by calling Yii::setAlias(). For examples -
// an alias of a file path
Yii::setAlias('@foo', '/path/to/foo');

// an alias of a URL
Yii::setAlias('@bar', 'http://www.example.com');

// an alias of a concrete file that contains a \foo\Bar class
Yii::setAlias('@foo/Bar.php', '/definitely/not/foo/Bar.php');

Q. - What do you know about route in Yii2?
Ans. -
Yii2 application “index.php” file determines which module, controller and action need to call for defining the appliction page route, when a browser request is triggered. Thus, Yii routes refers to module, controller and the action requested, like below -

ModuleID/ControllerID/ActionID
http://hostname/index.php?r=ModuleID/ControllerID/ActionID
Here, the ModuleID is optional, so generally the format is ControllerID/ActionID

Example route :
http://hostname/index.php?r=site/index, where site is the ControllerID and index is the ActionID.

Here,
"site" points to SiteController class.
"index" points to function actionIndex() in the SiteController class.
SiteControler file Path - yiiproject\frontend\controllers\SiteController.php

You can also check the interviews questions for PHP, JavaScript, WordPress, Drupal, Windows Server etc. at Interviews Questions and Answers Collections

Q. - How to implement the pretty URL or SEO Friendly URL structure in Yii2?
Ans. - We need to configure two things for implementing the SEO freiendly URL in Yii2 application -
  1. Creating htaccess file -
    We enable mod_rewrite using below code in htaccess file so that all requests are rewritten to web/index.php in yii2 application.
    RewriteEngine on
    
    # Use it directly, if a directory or a file exists 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # Otherwise forward it to index.php
    RewriteRule . index.php 
    
    Place this .htaccess file in the web folder at below sample path -
    For backend app - C:\xampp\htdocs\yii2project\backend\web\.htaccess
    For frontend app - C:\xampp\htdocs\yii2project\frontend\web\.htaccess

    One more .htaccess file is used for avoiding the directory and files lisitng of the Yii2 app root. It also forward the app root url(http://localhost/yii2project/) to frontend application url(http://localhost/yii2project/frontend/web/).

    File path - C:\xampp\htdocs\yii2project\.htaccess

    Below is the htaccess code for this purpose -
      # Disable directory listing
      Options +Indexes
    
      RewriteEngine on
      RewriteCond %{REQUEST_URI} !^public
      
      # Forward it to frontend/web/, change 'backend' if you want to forward to backend application
      RewriteRule ^(.*)$ frontend/web/$1 [L]
  2. urlManager component configuration
    Add the urlManger component in your Yii2 application components list in the configuration file at the path below -
    File path - C:\xampp\htdocs\yii2project\common\config\main-local.php

    You need to set 'enablePrettyUrl' as true for disabling the route parameter r=routes. You need to set 'showScriptName' as false for disabling "index.php". You can also add ".html" in the url. You need to set suffix is equal to ".html" for this.
    Below is the setting code for urlManger component -
    <?php
    return [
        'components' => [
        	------------------------
            ------------------------
          	'urlManager' => [
            	'class' => 'yii\web\UrlManager',
            
            	// Disable index.php
            	'showScriptName' => false,
            
            	// Disable r= routes
            	'enablePrettyUrl' => true,
            
            	// Add .html eg. login.html, about.html
           		'suffix' => '.html',
    
          		'rules' => [
                    "home" => "site/index",
                    "about-us" => "site/about",
                    "contact-us" => "site/contact",
    			],
            	],
        ],
    ];
    After setting and editing above codes, scriptname based url will be converted into pretty or SEO freindly url.
    Below are the sample urls before and after coverstion -

    http://localhost/yii2project/frontend/web/index.php?r=site%2Findex
    into
    http://localhost/yii2project/frontend/web/home.html

    http://localhost/yii2project/frontend/web/index.php?r=site%2Fabout
    into
    http://localhost/yii2project/frontend/web/about-us.html

    http://localhost/yii2project/frontend/web/index.php?r=site%2Fcontact
    into
    http://localhost/yii2project/frontend/web/contact-us.html

    http://localhost/yii2project/frontend/web/index.php?r=site%2Fsignup
    into
    http://localhost/yii2project/frontend/web/site/signup.html

    http://localhost/yii2project/frontend/web/index.php?r=site%2Flogin
    into
    http://localhost/yii2project/frontend/web/site/login.html
You can check the more detail for Yii2 routing and URL creation at "Routing and URL creation in Yii2

Q. - How can you disable or remove index.php from URL in Yii2?
Ans. - You need to set - 'showScriptName' property to false in the urlManager component configuration for removing the index.php in the Yii URLs. You also need to set 'true' to 'enablePrettyUrl' property in the urlManager component configuration.

Configuration file sample path - C:\xampp\htdocs\yii2project\common\config\main-local.php

Below is the urlManager component setting code -
<?php
return [
    'components' => [
    	------------------------
        ------------------------
      	'urlManager' => [
        	'class' => 'yii\web\UrlManager',
        
        	// Disable index.php
        	'showScriptName' => false,
        
        	// Disable r= routes
        	'enablePrettyUrl' => true,
        
        	// Add .html eg. login.html, about.html
       		'suffix' => '.html',

      		'rules' => [
                "home" => "site/index",
                "about-us" => "site/about",
                "contact-us" => "site/contact",
			],
        	],
    ],
];
You can check the more detail for Yii2 routing and URL creation at "Routing and URL creation in Yii2

Q. - How to run sql in controller file and passing the array into view file?
Ans. - We can also call and run sql query at controller file. You can check it by testing the sample code. Below are the controller and view file code :
namespace app\controllers;
use Yii;
use yii\web\Controller;

class YourController extends Controller
{
public function actionIndex()
{
$sql = 'SELECT * FROM tablename ORDER BY id ASC';
$db = Yii::$app->db;
$output = $db->createCommand($sql)->queryAll();
// same of
// $output = Yii::$app->db->createCommand($sql)->queryAll();
return $this->render('index', [ 'output' => $output ]);
}
}

View File code -
foreach($outputs as $item) {
echo $item['column1'] 
echo $item['column2']
---------
-------
------

Q. - Why Yii2 framework is called faster loading application?
Ans. - Yii2 framework uses "Lazy Loading" approach for faster application loading while doing the relational query to database. Yii2 framework does not approach to class if until they are needed and it will not create an object of the class unitl the object is called for the first time.

The lazy loading is a type of programming technique that delays loading resources(eg. showing rows of data of a table) until they are really needed. In other words, this technique splits the app or resource into various parts and loads them part by part.

You can check more about Yii2 lazy loading with example at "Yii2 - lazy loading technique for faster application performance"

Q. - What is Gii in Yii2?
Ans. - Yii2 has inbuilt extension named as - Gii, which is used for generating models, forms, modules, CRUD(Create, Read, Update, Delete) etc. code snippets for accelerating application development speed.

One can access Gii extension at the below sample URL (‘yii2giitesting’ is project name) -http://localhost/yii2giitesting/backend/web/index.php?r=gii
All default (Model Generator, CRUD Generator, Controller Generator, Form Generator, Module Generator, Extension Generator) available generators are available at above url.

You can check the detail process for Gii application at "How to generate CRUD files in Yii2 using Gii?".

Q. - What do you know about Active Record(AR) in Yii2 framework?
Ans. - Yii2 framework uses a base class - "ActiveRecord" for dealing the relational data in terms of objects. We donot need to write the raw SQL statements while working with database in Yii2 framework. We can easily access and manage the data using "AtiveRecord" attributes and methods.

For example - we have 'employ' table that is associated with "Employ" ActiveRecord class. There is "employ_name" is a column in the 'employ' table. We can write the below code for inserting a new record or row into the 'employ' table -
$employ = new Employ();
$employ->employ_name = 'Saraswati';
$employ->save();

Q. - What is widgets in Yii2
Ans. - Widgets are reusable code blocks in object-oriented way and it is used mainly in views as UI - user interface elements(client-side code : containing JavaScript, CSS, and HTML with minimal logic). For example - Date picker widget, Progress bar widget etc. One can create custom widget by using and extending the yii\base\Widget.
 <?php
/*Date picker widget - using yii2-jui (composer require --prefer-dist yiisoft/yii2-jui) -*/
use yii\jui\DatePicker;
echo DatePicker::widget(['name' => 'date', 'dateFormat' => 'php:Y-m-d',]);
?>
<?php
/*Progress bar widget*/
use yii\bootstrap\Progress;
// standard progress bar
echo Progress::widget(['percent' => 80, 'label' => 'Test Progress 40%']);
// striped animated
echo Progress::widget(['percent' => 70,
'barOptions' => ['class' => ['bg-success', 'progress-bar-animated', 'progress-bar-striped']]
?>
You can check Yii2 widget creation process at "How to create custom widget in Yii2". Some widgets can also take a block of content - enclosed between the yii\base\Widget::begin() and yii\base\Widget::end().

For example - Login form widget code as below -
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<?php $form = ActiveForm::begin(['id' => 'app-login-form']); ?>
<?php $form->field($model, 'app-login-username') ?>
<?php $form->field($model, 'app-login-password')->passwordInput() ?>
 <div class="form-group"><?= Html::submitButton('Log In') ?></div>
<?php ActiveForm::end(); ?>
You can check the real implementaion of login form widget code at "Writing the form for login page using login page view file".

Q. - What are Yii2 helpers?
Ans. - Yii2 has inbuilt static classes found under - yii\helpers that help for simplifying coding tasks for example - HTML code(eg. anchor tag, image tag, button tag etc.) generation, string or array manipulation etc.

Example of Yii2 core helper classes are -
  • Html helper(yii\helpers\Html)
  • Url helper(yii\helpers\Url)
  • File helper(yii\helpers\FileHelper)
  • String helper(yii\helpers\StringHelper)
  • Array helper(yii\helpers\ArrayHelper)
  • Json helper(yii\helpers\Json)
<?php
//Yii2 Helper class – Html
use yii\helpers\Html;

//Output as page title text - "My Yii Application"
$this->title = Yii::t('app', 'My Yii Application');
echo Html::encode($this->title);?>

//Output as - "Create Pages" anchor tag button with link "index.php?r=site/create"
<?= Html::a(Yii::t('app', 'Create Pages'), ['create'], ['class' => 'btn btn-success'])?>
//Output as - "<img src="/themes/abcrealestate/img/undraw_profile_2.jpg" alt="..." class="rounded-circle" />" <?= Html::img('@web/themes/abcrealestate/img/undraw_profile_2.jpg', ['alt'=>'...', 'class'=>'rounded-circle']);?>
You can check the real implementation of Yii2 HTML image and anchor tag helper code at Yii2 HTML helper image code
<?php
//Yii2 Helper class – Url
use yii\helpers\Url;

//Output as - index.php?r=product/view&id=42
echo Url::toRoute(['product/view', 'id' => 42]);

//Output as - index.php?r=site/index
echo Url::to(['site/index']);
?> For example - <a href="<?= Url::to(['site/aboutpdf']); ?>" target="_blank" rel="noopener, noreferrer, and nofollow" class="btn btn-info">Print it in PDF</a>
You can check the real implementation of Yii2 URL helper for anchor tag at Yii2 framework URL helper code

Q. - What are components in Yii2?
Ans. - Component is the base class that implements the property, event and behavior features. Yii2 is based on Components that is whay it is called building blocks of Yii2 application. Components are instances of yii\base\Component or an extended class.

In simple words - A component is a reusable object that should contain only logic, and it is callable from every point of the app.

Example of Yii2 inbuilt core components are -
  • Asset Manager component (yii\web\AssetManager)
  • Error Handler component (yii\web\ErrorHandler)
  • Formatter component (yii\i18n\Formatter)
  • Internationalization-i18n-(message translation) component (yii\i18n\I18)
  • Log targets component (yii\log\Dispatcher)
  • Session component (yii\web\Session)
  • User component (yii\web\User)
  • View component (yii\web\View)
  • Cache component (yii\caching\CacheInterface)
  • Bootstrap component (yii\base\BootstrapInterface)
  • Swift Mailer component (yii\swiftmailer\Mailer)
  • Mailing Component (yii\mail\BaseMailer)
  • GridView component (yii\grid\GridView)
  • Theme component (yii\base\Theme)
  • db component (yii\db\Connection)

Q. - What is module in Yii2?
Ans. - Modules are independent programming units that uses its own models, views, controllers, and other modules too. Modules cannot be deployed alone and must reside within applications that is why it is called mini application.

It is best way for organising and reusing code for common features like - user management, comment management, can all be developed in terms of modules so that they can be reused effectively in new projects. Real world example for Yii2 module - Forum, Blog etc.

You can also check the interviews questions for PHP, JavaScript, WordPress, Drupal, Windows Server etc. at Interviews Questions and Answers Collections

Q. - What are extensions in Yii2?
Ans. - Yii2 extensions gives ready-to-use functionality which is available as redistributable software packages. It helps to accelerate the development process of the project. There are two types of extensions -
  1. User contributed extensions - which is maintained by public users which is part of Yii2 community.
    Below are Yii2 user contributed extensions -
    • kartik-v/yii2-number - For number control and format mask input
    • kartik-v/yii2-bootstrap4-dropdown - dropdown widget for Yii2 framework with nested submenu support
  2. Yii2 official or core extensions - which is maintained by Yii developer team.
    Below are Yii2 official extensions example -
    • yiisoft/yii2-debug
    • yiisoft/yii2-gii
    • yiisoft/yii2-imagine
    • yiisoft/yii2-captcha
    • yiisoft/yii2-jquery
    • yiisoft/yii2-rest
Q. - What are formatter in Yii2 ?
Ans. - The formatter is Yii2 inbuilt application component relates to class "yii\i18n\Formatter". It is used for formatting values for displaying to end users using different data formatting methods in different languages, time zone for a specific country.

For example -
Showing the date in different format - "short, medium, long, and full"
$formatter = \Yii::$app->formatter;

// will give output as -  4/14/22
echo $formatter->asDate(date('Y-m-d'), 'short');

// will give output as - Apr 14, 2022
echo $formatter->asDate(date('Y-m-d'), 'medium');

// will give output as -  April 14, 2022
echo $formatter->asDate(date('Y-m-d'), 'long');

// will give output as -  Thursday, April 14, 2022
echo $formatter->asDate(date('Y-m-d'), 'full');
Showing the date in different locales or for a specific country -
$formatter = \Yii::$app->formatter->locale = 'de-RU';

// will give output as -   Четверг, 14 апреля 2022 г.
echo Yii::$app->formatter->asDate(date('Y-m-d'), 'full');
Showing numbers in different format −
$formatter = \Yii::$app->formatter;

// will give output as - 999.00
echo Yii::$app->formatter->asDecimal(999);

// will give output as - 87%
echo Yii::$app->formatter->asPercent(0.87);

// will give output as - $ 2309
echo Yii::$app->formatter->asCurrency(2309, "$");
Q. - What is difference between 'render' and 'renderpartial' in Yii?
Ans. - Both the render() and renderPartial() method is part of Class yii\web\View and is used to render or display the view content in Yii2 framework.

The render() method is used to render the view page content in the layout or theme with header, navigation, body and footer content.

The renderPartial() method is used to render or show the view page content only excluding header, navigation, body and footer content. So no css, js and script is parsed or render in the view page. Below is the action code in a controller file -

   public function actionAbout()
    {
        return $this->render('about');
    }

   public function actionAboutPartial()
    {
        return $this->renderPartial('about');
    }
 
You can check more detail about view content rendering at "View rendering process in Yii2 framework".

Q. - What is renderFile() method or function in Yii2 framework?
Ans. - It is used in the response to AJAX Web requests. It generally renders a view specified in terms of a view file path as per below API reference code -
 public string renderFile($viewFile, $params = [], $context = null )
Here $viewFile - either an absolute file path or an alias of it

Q. - What is CModel Class in Yii2?
Ans. - CModel is the base class in Yii2 applicaiton architure for data model definition. All models are the extended part of the CModel class. Yii2 uses two types of data model - form model(CFormModel) and active record(CActiveRecord).

CFormModel is used where the model data doesn’t come from an active record or database. It is used to keep data collected from user inputs via form. They are generally collected, validated, used and then discarded. Thus, the data is stored in memory temporarily only instead of a database.

CActiveRecord is used to abstract database access in an object-oriented way.

Q. - What is CFormModel in Yii2?
Ans. - Yii CFormModel is one of the data models(Form Model and Active Record) that extend the base class CModel. It is used to collects the user input via HTML form. These data are generally collected, validated, used and then discarded. Thus, the data is stored in memory temporarily only instead of a database.

For example - login page of the applicaion . We use a form model to collect the username and password which is provided by an end user at the login page.

Q. - How can you display or flash various kind of messages - error, notice etc in Yii2?
Ans. - In Yii2 we can display or flash different conditional - "notice, success or error" - message using the setFlash() method. This method use a key(identifying the flash message) and value(flash message) pair entry. By default, the message is removed from session after it has been flashed or displayed to the user once. Below is the example code for setting flash message -
Yii::app()->user->setFlash('notice', "You should take care for this tag.");
Yii::app()->user->setFlash('success', "You have successfully saved the data");
Yii::app()->user->setFlash('error', "Data saving failed!");
Yii2 provides the hasFlash() method for checking the flash message using key and the getFlash() method for obtaining the flash message. Below is the example code in view of Yii2 for making a flash message with the key 'success' visible to the end user withing a div of class "info".
<?php if(Yii::app()->user->hasFlash('success')):?>
    <div class="info">
        <?php echo Yii::app()->user->getFlash('success'); ?>
    </div>
<?php endif; ?>
Below is the example code in the Yii2 controller for informing the user that changes were successfully saved -
<?php
Yii::app()->user->setFlash('success', "You have successfully saved the data");
$this->redirect(array('site/success'));
?>
You can also set and access flash data through the session application component as below code -
$session = Yii::$app->session;

// set a flash message named as "articleDeleted"
$session->setFlash('articleDeleted', 'You have successfully deleted your article.');

Q. - How to get current url in Yii2?
Ans. - You can get current url using the below code -
<?= Yii::$app->request->absoluteUrl; ?>
It will give(after using in 'about' view) below output as sample url -
http://localhost/yii2project/frontend/web/index.php/about-us.html

Related information -
Yii2 request component(instance of yii\web\Request) gives the detail information for the currently requested URL. It uses "Yii::$app->request->method" expression for request method info. Below are more info using that you can get more information about current requested URL -
<?php
echo Yii::$app->request->url; 
echo Yii::$app->request->hostInfo;
echo Yii::$app->request->pathInfo;
echo Yii::$app->request->queryString;
echo Yii::$app->request->baseUrl;
echo Yii::$app->request->scriptUrl;
echo Yii::$app->request->serverName;
echo Yii::$app->request->serverPort;
echo Yii::$app->request->userHost;
echo Yii::$app->request->userIP;
?>  

Q. - What is difference between baseUrl and homeUrl in Yii2?
Ans. - The baseUrl denotes the relative url of the Yii2 application whereas the homeUrl denotes the homepage url of the applicaiton. Below is the example that differentiate between these two -

Example Url - http://localhost/yii2project/frontend/web/index.php?r=news/detail&id=1

Base Url - "/yii2project/frontend/web"
Home Url - "/yii2project/frontend/web/index.php"

You can get both url using the below code in the view of a Yii2 application -
<?php
echo Yii::$app->homeUrl;
echo Yii::$app->request->baseUrl;
?> 
Q. - How to change the default controller in Yii2 framework?
Ans. - The Yii2 framework uses "site/index" for the default route in the application which refers to the index action of the site controller in the default Yii2 application.

We can use our own or custom route as per requirement by using the "defaultRoute" property of the application in the application configuration like the following entry code :
<?php
return [
   // "news" is controller name, "index" is action name
    'defaultRoute' => 'news/index',
    'components' => [
       ---------------
       ---------------
];
With the above coniguration the browser will show the index action of the news controller when you open the site domain. Below is the sample urls -

Site domain URL -
http://localhost/yii2project/frontend/web/

Default page URL after hitting the above site URL -
http://localhost/yii2project/frontend/web/index.php?r=news/index

You can also check the interviews questions for PHP, JavaScript, WordPress, Drupal, Windows Server etc. at Interviews Questions and Answers Collections

Q. - How to change the default action in Yii2 framework?
Ans. - The Yii2 uses a default action which is mentioned in the property of yii\base\Controller::$defaultAction. When you browse the page using controller ID only, the default action is triggered for given controller.

In the Yii2 framework - the default action is set to "index" or the function actionIndex(). We can use our own or custom action by using the property "defaultAction" in the controller as like following code -
<?php
namespace frontent\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
    public $defaultAction = 'welcome';

    public function actionWelcome()
    {
        return $this->render('welcome');
    }
}

Q. - What do you know about directory structure of the Yii2 application?
Ans. - Yii2 framework uses following subdirectories as the top level directories in the root of the application -
  1. backend: it is used to manage the whole application system as site administrators
  2. frontend: it is used to show the main interfaces to end users.
  3. console: it consists of the console commands needed by the application system.
  4. common: whose content or files are shared among the above applications i.e. files common to all applications.
  5. environments: represents environment configs eg. development or production mode related.
  6. vendor: represents place for third party modules and Yii2 source files itself.
The frontend and backend both have these directories -
  1. components: contains components (e.g. helpers, widgets) that are only used by this application
  2. config: contains the configuration used by the application
  3. controllers: contains controller classes
  4. lib: contains third-party libraries that are only used by this application
  5. models: contains model classes that are specific for the application
  6. runtime: stores dynamically generated files
  7. views: stores controller actions view scripts
  8. web: the web root for this application
You can check for full directory structure at "Yii2 framework - the directory structure".

Q. - What is the use of "common" directory in the Yii2 application?
Ans. - Some files may need to share among applications, we place those files in the common directory in the Yii2 framework to avoid duplication of the code.

For example - every application may need to access the database using ActiveRecord. So, we place the AR model classes code in the common directory.

Q. - How to get current controller name in Yii2?
Ans. - We can get the current controller name using below code -
<?php echo Yii::$app->controller->id; ?>

Q. - How to get current action name in Yii2?
Ans. - We can get the current action name using below code -
<?php echo Yii::$app->controller->action->id; ?>

Q. - How to enable maintenance mode in Yii2?
Ans. - We can enable the maintenance mode in the Yii2 using "catchAll" property in the application configuration file. The following is the config file path and code -

File Path(sample) - C:\xampp\htdocs\yii2default\common\config\main-local.php
<?php
return [
   // site is controller name, offline is action name
    'catchAll' => ['site/offline'],
    'components' => [
       ---------------
       ---------------
];
With the above configuration we can pass the maintenance views content into the action function "actionOffline" in the controller "site" using the code below -

    public function actionOffline()
    {
        return $this->render('maintenance');

    }
You can check more detail for maintenance mode activation in Yii2 at "The simplest way for showing the maintenance mode in the Yii2 framework".

Q. - How to get and set session in Yii?
Ans. - We can set the session as below code -
// for importing session class
use  yii\web\Session;
  
// sets or stores the session
$session = Yii::$app->session;
$session->set('name', 'Aashutosh');
We can get or show the session value as below code -
// for importing session class
use  yii\web\Session;
// gets or shows the session value
echo Yii::$app->session->get('name');

Q. - What is the difference between Yii1.0 & Yii2.0?
Ans. - Yii 2.0 is completely different from Yii 1.0. Below are the major diffeences between Yii 1.0 and Yii 2.0 -

Yii 1.0Yii 2.0
Server requires PHP 5.2Server requires PHP 5.4 or above
It uses C prefix in class namesThe C prefix is no longer used in class names. Classes based on directory structure. For example, yii\web\Request indicates that the corresponding class file is web/Request.php
CController was used.Yii 2.0 uses yii\web\Controller as the base controller class
CComponent class in 1.1Yii 2.0 breaks the CComponent class in 1.1 into two classes: yii\base\BaseObject and yii\base\Component.
The script package concept for assets handlingIt introduces a new concept called asset bundle
Several classes for query buildingIt uses a DB query(Class yii\db\Query) in terms of a Query object
PHP as a primary template languageIt is now with TWIG and SMARTY template engine including PHP

Q. - Can you list method names for database related functions in Yii2?
Ans. - The following inbuilt methods(Class yii\db\ActiveRecord) are available for database interaction in Yii2 -
  1. delete() - Deletes the table row corresponding to this active record. For example -
    // deletes an existing customer record
    $customer = Customer::findOne($id);
    $customer->delete();
  2. deleteall() - Deletes rows in the table using the provided conditions. For example -
    // deletes multiple customers whose age is greater than 40 and gender is 'M'
    Customer::deleteAll('age > :age AND gender = :gender', [':age' => 40, ':gender' => 'M']);
  3. find() - Creates an yii\db\ActiveQueryInterface instance for query purpose. For example -
    //Showing first record matching with 'name' field as condition
    $customer = Customer::find()->where(['name' => 'Thomas'])->one();
  4. findAll() - Returns a list of active record models that match the specified primary key value(s) or a set of column values. For example -
    //finding customers whose age is 66 and whose status is active
    $customers = Customer::findAll(['age' => 66, 'status' => 'active']);
    
    //finding the customers whose primary key value is 10
    $customers = Customer::findAll(10);
  5. findOne() - Returns a single active record model instance by a primary key or an array of column values. For example -
    // find a single customer whose primary key value is 55
    $customer = Customer::findOne(55);
  6. insert() - Inserts a row into the associated database table using the attribute values of this record. For example -
    // inserts the name, email, age and gender entries into database
    $customer = new Customer;
    $customer->name = $name;
    $customer->email = $email;
    $customer->age = $age;
    $customer->gender = $gender;
    $customer->insert();
  7. save() - Saves the current record. For example -
    // saves the customer name, email, age and gender entries into database
    $customer = Customer::findOne($id);
    $customer->name = $name;
    $customer->email = $email;
    $customer->age = $age;
    $customer->gender = $gender;
    $customer->save();
  8. update() - Saves the changes to this active record into the associated database table. For example -
    // updates the customer email into customer record database
    $customer = Customer::findOne($id);
    $customer->email = 'thomasnew@gmail.com';
    $customer->update();
  9. updateAll() - Updates the whole table using the provided attribute values and conditions. For example -
    // changes the status to be 1 for all customers whose status is 2
    Customer::updateAll(['status' => 1], 'status = 2');
  10. refresh() - Repopulates this active record with the latest data
You can check more detail for working with database at "Yii2 framwork - working with databases - using inbuilt database related methods".


Below is the Pdf version of the Yii2 Interview Questions and Answers pdf file -



You can download the Yii2 Interview Quesitons and Answers at "Yii2 Interviews Questions and Answers pdf file".
Tags : ,
Aashutosh Kumar Yadav

By Aashutosh Kumar Yadav

He is a PHP-based UI/Web designer and developer by profession and very interested in technical writing and blogging. He has been writing technical content for about 10 years and has proficient in practical knowledge and technical writing.
@www.infotokri.in

0 comments:

Post a Comment