Categories

Top 50 Yii Interview Questions and Answers

The following are the most popular and useful Yii framework interview questions and answers for fresher and experienced candidates. These questions are created specifically to familiarize you with the types of questions you might encounter during your interview. According to our experiences, good interviewers rarely plan to ask any specific topic during the interview.

1. What is Yii?

Yii is an open-source, high-performance, component-based, and object-oriented PHP web application framework. Yii follows the MVC (Model-View-Controller) architectural pattern. This PHP framework is best for Web 2.0 development.

Yii enables maximum reusability in programming and significantly accelerates the process of web application development.

2. Why Use Yii 2.0 Framework?

The Yii 2.0 Framework helps to create modern web applications quickly and make sure they perform well. Yii 2.0 framework is:

1) Easy to Install

2) Utilizes Modern Technologies

3) Highly Extensible

4) Encourages Testing

5) Simplifies Security

6) Shorten Development Time

7) Easy to Tune for Better Performance

3. What is Yii best for?

Yii is a generic Web programming framework that can be used for developing virtually any type of Web application. Because it is lightweight and equipped with sophisticated caching mechanisms, it is especially suited to high-traffic applications, such as portals, forums, content management systems (CMS), e-commerce systems, etc.

4. Why is Yii so fast?

Yii is so much faster because it is using the lazy loading technique extensively. For example, it does not include a class file until the class is used for the first time. And it does not create an object until the object is accessed for the first time. Other frameworks suffer from the performance hit because they enable functionality (e.g., DB connection, user session) no matter if it is used or not during a request.

5. What are Yii Versions?

The Yii framework currently has two major versions, one is 1.1, and another one is 2.0. Version 1.0 is old, and version 2.0 is a complete rewrite of Yii 1.0

6. What are the server requirements to install Yii?

Yii framework requires the following things, such as:

1) PHP 5.4 or above

2) mbstring extension

3) PCRE-support

7. What are the core components of Yii?

Here are the following core components of Yii, such as:

1) db- database connection.

2) assetManager - manage the publishing of private asset files

3) authManager - manage role-based access control

4) cache- manage to cache functionality

5) clientScript- manage javascript and CSS

6) coreMessages- provides translated core messages

7) errorHandler- manage errors handling.

8) themeManager- Manage themes

9) urlManager- URL parsing and creation functionality

10) statePersister- a mechanism for persisting global state

11) session- Session management

12) securityManager- Security Management

8. What are Components in Yii?

Components are an independent set of code written to perform a specific task in controllers. Yii applications are built upon components which are objects written to a specification.

A component is an instance of a 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.

9. What's new in Yii version 2.0?

The following things are newly added in Yii version 2.0:

1) The Yii 2.0 framework supports PSR-4 class autoloading, simpler namespaces, faster loading, and improved usability for developers.

2) The Yii 2.0 framework added performance and security improvements.

3) The Yii 2.0 framework added RESTful API integration.

4) The Yii 2.0 framework added improvement on URL handling and processing.

5) Now Yii 2.0 framework, Translations of core messages available in 26 languages.

10. What are the main features of the Yii framework?

Yii framework has the following main features, such as:

1) Model-View-Controller (MVC) design pattern

2) Database Access Objects (DAO), Query Builder, Active Record, and DB Migration

3) Form input and validation

4) AJAX-enabled widgets

5) Yii provides a skinning and theming mechanism

6) Web Service available for Apps like android

7) Internationalization and localization translation for multilingual

8) Caching to speed up the application

9) Error handling and logging for tracking

10) It provides cross-site scripting (XSS), cross-site request forgery (CSRF) protection.

11) PHPUnit and Selenium for testing

12) Automatic code generation help us to fast development

13) Authentication and authorization

14) Friendly with third-party code

15) Extension library

11. What are Views in Yii?

1) Views should mainly contain presentational code, such as HTML and simple PHP code to traverse, format, and render data.

2) It should avoid containing code that performs explicit DB queries. Such code is better placed in models.

3) This is the controller's job. It should avoid direct access to $_GET, $_POST, or other similar variables representing the end-user request. The view should be focused on the display and layout of the data provided to it by the controller or model, but not attempting to access request variables or the database directly.

4) It may access properties and methods of controllers and models directly. However, It should be done only for presentation.

12. What is Model in Yii?

Models represent the underlying data structure of a Web application. Models are often shared among different sub-applications of a Web application. For example, a LoginForm model may be used by both the front end and the back end of an application. A New model may be used by the console commands, Web APIs, and the front or back end of an application. Therefore,

1) Models should contain properties to represent specific data.

2) It should contain business logic (e.g., validation rules) to ensure the represented data fulfills the design requirement.

3) It may contain code for manipulating data.

13. What is Controller in the Yii framework?

Controllers are the glue that binds models, views, and other components together into a runnable application. Controllers are responsible for dealing directly with end-user requests. Therefore,

1) Controllers may access $_GET, $_POST, and other PHP variables representing user requests.

2) It may create model instances and manage their life cycles. Note that the actual implementation of saving a model should be located in the model instead of the controller.

3) It should avoid containing embedded SQL statements, which are better kept in models.

4) It should avoid containing any HTML or any other presentational markup, which is better kept in views.

14. How to install the Yii framework?

You can install Yii2 by running these commands via composer:

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

15. What is the directory structure of the Yii framework?

/  

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  

16. What are the benefits of Yii over other frameworks?

Yii has the following benefits over other frameworks of PHP:

1) The Yii framework is a generic Web programming framework used for developing all kinds of Web applications quickly using PHP. It is also very suitable for developing large-scale applications.

2) The primary goal of the Yii or Yii 2.0 framework is - high performance.

3) The Yii framework is a full-stack framework and ready-to-use features for both the relational and NoSQL databases.

4) The Yii framework implements the MVC (Model-View-Controller) architectural pattern.

5) The Yii framework is extremely extensible.

6) The Yii framework contains the Larger Community, and it also purchased an unlimited license to the beautiful web-based rich text editor and Redactor.

17. What is Active Record (AR) in Yii?

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.

18. What are Yii Helpers?

Helpers are static classes in Yii that simplify common coding tasks, such as string or array manipulations, HTML code generation, etc. In Yii, all helpers are kept under the yii\helpers namespace.

You use a helper class in Yii by directly calling one of its static methods, as the following:

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

19. What is Formatter in Yii?

Formatter is a 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 as the following,

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

// output: January 1, 2021  

echo $formatter->asDate('2021-01-01', 'long');     

// output: 12.50%  

echo $formatter->asPercent(0.125, 2);    

// output: jtp@example.com  

echo $formatter->asEmail('jtp@example.com');     

// output: Yes  

echo $formatter->asBoolean(true);   

// it also handles display of null values:   

// output: (not set)

echo $formatter->asDate(null);   

20. What is Gii in Yii2?

Gii is a web-based code-generator module provided by the Yii framework. It helps to create and generate fully customized forms, models, CRUD for databases, and more.

We can enable Gii by configuring it in the modules property of the application. Depending upon how we created our 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',  

    ];  

}  

21. Explain request Life Cycle in Yii2 framework?

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()

a) Register application behaviors;
b) Load static application components;

6) Raise an onBeginRequest event;

7) Process the user request.

a) Collect information about the request;
b) Create a controller;
c) Run the controller;

8) Raise an onEndRequest event;

22. What is CModel class in Yii?

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 extend CModel class.

23. What is the naming convention in Yii Framework?

In the latest version of Yii Framework uses a simple standard to set names.

1) You can define the table prefix when using Gii. In your case, you need to set it to tbl_. Then it should generate UserController instead of TblUserController.

2) 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.

3) Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged. A dot (.) is only permitted in place of the path separator.

ModuleID/ControllerID/ActionID

The ModuleID is optional. 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:

24. What is the first function that is loaded from a Controller?

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

25. What are the benefits of Yii over other frameworks?

Yii has the following benefits over other frameworks of PHP:

1) The Yii framework is a generic Web programming framework used for developing all kinds of Web applications quickly using PHP. It is also very suitable for developing large-scale applications.

2) The primary goal of the Yii or Yii 2.0 framework is - high performance.

3) The primary goal of the Yii or Yii 2.0 framework is - high performance.

4) The Yii framework is a full-stack framework and ready-to-use features for both the relational and NoSQL databases.

5) The Yii framework implements the MVC (Model-View-Controller) architectural pattern.

6) The Yii framework is extremely extensible.

7) The Yii framework contains the Larger Community, and it also purchased an unlimited license to the beautiful web-based rich text editor and Redactor.

26. What is the first file that loaded when you run an application using Yii?

index.php is the first file that loaded when we run an application using the Yii application. It will create 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();  

27. What are the Core Helper Classes in the Yii framework?

The following core helper classes are:

1) ArrayHelper

2) Console

3) FileHelper

4) FormatConverter

5) Html

6) HtmlPurifier

7) Imagine

8) Inflector

9) Json

10) Markdown

11) StringHelper

12) Url

13) VarDumper

28. How to configure the Yii application with a database?

In the default application of Yii, open the main.php file that exists in protected/config/main.php and search for a parameter named db, there you can add host-name, database name, username, and password of your database server.

29. How to generate CRUD code?

After creating a model class file, we shall generate the code that implements the CRUD operations for user data. We choose the Crud Generator in Gii. In the model class field, we enter 'User'. In the Controller ID field, we enter 'user' in lower case. Then press the preview button followed by the Generate button. Now we are done with the CRUD code generation.

30. How can you create and work with the different modules in Yii?

To create a module, access the gii url, and there you can create a module. After creating a module, you need to add it to the main configuration file of your Yii application.

31. How to customizing Helper Classes in the Yii framework?

To customize a core helper class, we should create a new class extending from the helper base class. For example,

< ?php  

namespace yii\helpers;  

  

class ArrayHelper extends BaseArrayHelper  

{  

    public static function merge($x, $y)  

    {  

        // your custom implementation  

    }  

}  

32. How to get the current url in Yii?

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

33. What is CActiveRecord in the Yii framework?

Active Record (AR) is a design pattern used to abstract database access in an object-oriented fashion. Each AR object is an instance of CActiveRecord or a subclass of that class, representing a single row in a database table.

The fields in the row are represented as properties of the AR object. All AR details are found in Active Record.

34. What is CFormModel in Yii framework?

In Yii, CFormModel represents a data model that collects HTML form inputs. The data collected by CFormModel are stored in memory only instead of a database. Therefore to collect user inputs, you may extend CFormModel and define the attributes whose values are collected from user inputs.

35. How to get and set session in Yii?

To set session variables, you will need to apply a global PHP $_SESSION variable. Whereas to access the data stored in a session, you can do the following:

$session = Yii::$app->session; // get a session variable.

36. How to convert debug mode to production mode on the Yii project?

Just define YII_DEBUG as false on the entry script (root/index.php).

// remove the following line when in production mode  

defined('YII_DEBUG') or define('YII_DEBUG',false);  

  

// include Yii bootstrap file  

require_once('path/to/yii/framework/yii.php');  

  

// create application instance and run  

$configFile='path/to/config/file.php';  

Yii::createWebApplication($configFile)->run();  

37. How to set or change the default controller in Yii?

You can set or change the default controller in Yii by using the default yii2 advanced template that redirects to URL:

Add below code on backend main/config.php user component:

'components' => [  

        'user' => [  

            'identityClass' => 'common\models\User',  

            'enableAutoLogin' => true,  

        'loginUrl' => [ 'yourcontroller/youraction' ],  

        ],  

Yii2 advanced template default controller is controllers/siteController. You can change it to your module or controller name by putting the below configuration in main/config.php:

'defaultRoute' => 'yourcontroller',

38. What is a Yiibase?

YiiBase is a helper class that serves functionalities of a common framework. It would be best if you did not use YiiBase directly. Instead, have to use its child class where we can customize the methods of YiiBase.

39. What is meant habtm?

Habtm means HasAndBelongsToMany. It is a kind of association defined in models for retrieving related data across different entities.

40. What is the difference between render, renderPartial and renderfile in the Yii framework?

Habtm means HasAndBelongsToMany. It is a kind of association defined in models for retrieving related data across different entities.

Render()

renderPartial()

renderFile()

render() is commonly used to render a view corresponding to what a user sees as a "page" in your application.
It first renders the view you have specified and then renders the layout for the current controller action (if applicable), placing the result of the first render into the layout. It then performs output processing and finally outputs the result. i.e.) render with a theme.

renderPartial() is commonly used to render a "piece" of a page. The main difference from render() is that this method does not place the render results in a layout.
By default, it also does not perform output processing, but you can override this behavior using the $processOutputparameter. i.e.) render without a theme.

renderFile() is a low-level method that does the grunt work of rendering: it extracts the data variables in the current scope and then runs the view code.
The other two methods internally call this one, but you should practically never need to call it yourself. If you do, keep in mind that you need to pass in a file path (not a view path).

41. What are the types of models available in the Yii framework?

Yii implements two kinds of models. And they both extend from the same base class, CModel.

1) Form models

2) Active records.

42. Which ORM does Yii2 supports?

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

43. What is the use of the renderFile() function in Yii?

In Yii, the renderFile() function is usually used in response to AJAX Web requests. It renders a view specified in terms of a view file path or alias.

44. How many types of table relations are supported by Yii?

Yii supports almost every type of table relations that are used all across its platform.

45. How to get the current url in Yii?

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

46. What is the difference between Yii & Yii2?

The difference between Yii & Yii2 is explained as:

Yii

Yii2

Yii requires PHP 5.2.

Yii 2.0 requires PHP 5.4.0 or higher, which makes use of the latest features of PHP.

In Yii, prefix C was used, and the classes were in global namespaces.

In Yii2, prefix C is not used in namespaces. And classes based on the directory structure.

Yii uses the On-event method, where custom event names are not allowed to use.

In Yii 2.0, any name can be used for the event with a handler attached to it, and event handling can be done using J-query.

47. What is a filter on the Yii framework?

The filter is a piece of code that is configured to be executed before or after a controller action executes.

An action can have multiple filters. The filters are executed in the order that they appear in the filter list. A filter can prevent the execution of the action and the rest of the unexecuted filters.

A filter can be defined as a controller class method. The method name must begin with a filter.

public function filterAccessControl($filterChain)  

{  

 // call $filterChain->run() to continue filter and action execution  

}  

48. 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. For example,

< ?php $this->renderPartial(  

    'application.views.user.index',  

    array(  

        'data'=>'Welcome',  

        'model'=>$model,  

    )  

);?>  

49. 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(  

    ........  

),  

.......  

50. How to get current action name?

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