Most frequently asked yii framework Interview Questions and Answers specially for freshers and experienced PHP developer.


 

1. What is Yii ?

Ans:

Yii is a high-performance, component-based PHP framework for developing large-scale Web applications rapidly. It enables maximum reusability in Web programming and can significantly accelerate your Web application development process.

2. What are the requirements need for use Yii framework?

Ans:

you need a Web server that supports PHP 5.1.0.
You also have knowledge on object-oriented programming (OOP).

3. What is Yii best for?

Ans:

Yii is a generic Web programming framework that can be used for developing virtually any type of Web application. Because it is light-weight 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. How to install Yii framework ?

Ans:

Installation of Yii mainly involves the following two steps:

  • Download Yii Framework from yiiframework.com.
  • Unpack the Yii release file to a Web-accessible directory.

5. What command used to create new Yii project ?

Ans:

% YiiRoot/framework/yiic webapp WebRoot/testdrive

6. How you can remove index.php from your application URL ?

Ans:

Steps to remove index.php from your application url.
Step 1: First configure your Yii-application configuration file like below code

.....
'urlManager'=>array(
'urlFormat'=>'path', //mandatory
'showScriptName'=>false, //mandatory
'urlSuffix'=>'.html', //not mandatory
......
),
....

Step 2: Enable apache rewrite engine. To enable rewrite engine type the following command in your terminal (Ubuntu ).

a2enmod rewrite // to enable rewrite engine
#Restart apache2 after
/etc/init.d/apache2 restart
OR
service apache2 restart

Step 3: Then, if you’d like, you can use the following .htaccess file in your application folder where index.php exists

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

7. How to connect database on Yii Project?

Ans:

To use a database, we need to tell the application how to connect to it. This is done in the application configuration fileWebRoot/testdrive/protected/config/main.php, highlighted as follows,

return array(
......
'components'=>array(
......
'db'=>array(
'connectionString'=>'sqlite:protected/data/testdrive.db',
),
),
......
);

8. How to configure gii web based code generator tool on Yii Project?

Ans:

In order to use Gii, we first need to edit the file WebRoot/testdrive/protected/config/main.php, which is known as the application configuration file:

return array(
......
'import'=>array(
'application.models.*',
'application.components.*',
),

‘modules’=>array(
‘gii’=>array(
‘class’=>’system.gii.GiiModule’,
‘password’=>’pick up a password here’,
),
),
);

9. What is MVC ? Why need to use MVC?

Ans:

MVC (Model – View- Controller ) is a design pattern., which is widely adopted in Web programming.
MVC aims to separate business logic from user interface considerations, so that developers can more easily change each part without affecting the other. In MVC, the model represents the information (the data) and the business rules; the view contains elements of the user interface such as text, form inputs; and the controller manages the communication between the model and the view.

10. How to change debug mode to production mode on yii project ?

Ans:

Just define YII_DEBUG is false on 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();



 

11. How to set default controller on Yii Project ?

Ans:

We can set on configuration file (protected/config/main.php).

array(
'name'=>'Yii Framework',
'defaultController'=>'site',
)

12. How to access application components on Yii Project ?

Ans:

To access an application component, use Yii::app()->ComponentID, where ComponentID refers to the ID of the component (e.g. Yii::app()->cache).

13. What are the core application components available on Yii?

Ans:

Yii predefines a set of core application components to provide features common among Web applications. For example, the request component is used to collect information about a user request and provide information such as the requested URL and cookies. By configuring the properties of these core components, we can change the default behavior of nearly every aspect of Yii.
Here is a list the core components that are pre-declared by CWebApplication:
• assetManager: CAssetManager – manages the publishing of private asset files.
• authManager: CAuthManager – manages role-based access control (RBAC).
• cache: CCache – provides data caching functionality. Note, you must specify the actual class (e.g.CMemCache, CDbCache). Otherwise, null will be returned when you access this component.
• clientScript: CClientScript – manages client scripts (javascript and CSS).
• coreMessages: CPhpMessageSource – provides translated core messages used by the Yii framework.
• db: CDbConnection – provides the database connection. Note, you must configure its connectionStringproperty in order to use this component.
• errorHandler: CErrorHandler – handles uncaught PHP errors and exceptions.
• format: CFormatter – formats data values for display purpose.
• messages: CPhpMessageSource – provides translated messages used by the Yii application.
• request: CHttpRequest – provides information related to user requests.
• securityManager: CSecurityManager – provides security-related services, such as hashing and encryption.
• session: CHttpSession – provides session-related functionality.
• statePersister: CStatePersister – provides the mechanism for persisting global state.
• urlManager: CUrlManager – provides URL parsing and creation functionality.
• user: CWebUser – carries identity-related information about the current user.
• themeManager: CThemeManager – manages themes.

14. Application Life Cycle of Yii framework ?

Ans:

When handling a user request, an application will undergo the following life cycle:
1. Pre-initialize the application with CApplication::preinit();
2. Set up the class autoloader and error handling;
3. Register core application components;
4. Load application configuration;
5. Initialize the application with CApplication::init()
• Register application behaviors;
• Load static application components;
6. Raise an onBeginRequest event;
7. Process the user request:
• Collect information about the request;
• Create a controller;
• Run the controller;
8. Raise an onEndRequest event;

15. How to get current controller id in Yii ?

Ans:

$controllerid = Yii::app()->controller->id;

16. How to get current action id in Yii ?

Ans:

$actionid = Yii::app()->controller->action->id;

17. What is filter on Yii framework ?

Ans:

Filter is a piece of code that is configured to be executed before and/or after a controller action executes. For example, an access control filter may be executed to ensure that the user is authenticated before executing the requested action; a performance filter may be used to measure the time spent executing the action.
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 filter. For example, a method named filterAccessControl defines a filter named accessControl. The filter method must have the right signature:

public function filterAccessControl($filterChain)
{
// call $filterChain->run() to continue filter and action execution
}

18. What are the type of models available in Yii framework ?

Ans:

Yii implements two kinds of models: Form models and active records. They both extend from the same base class,CModel.

19. What is CFormModel in Yii framework ?

Ans:

A form model is an instance of CFormModel. Form models are used to store data collected from user input. Such data is often collected, used and then discarded. For example, on a login page, we can use a form model to represent the username and password information that is provided by an end user. For more details, please refer to Working with Forms.

20. What is CActiveRecord in Yii framework ?

Ans:

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 of 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. Details about AR can be found in Active Record.




 

21. What is the differences between render , renderPartial and renderfile in yii framework ?

Ans:

render() is commonly used to render a view that corresponds 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 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 results of the render 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 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).

22. How to use widget on Yii framework ?

Ans:

To use a widget, do as follows in a view script:

beginWidget('path.to.WidgetClass'); ?>
...body content that may be captured by the widget...
endWidget(); ?>
or
widget('path.to.WidgetClass'); ?>

23. How to defining a component property in Yii ?

Ans:

There are two different ways of defining a component property. First way is to simply declare a public member variable in the component class like the following:

class Document extends CComponent
{
public $textWidth;
}

Another way is to use getters and setters. It is more flexible since additionally to normal properties you can declare a read only or write only property.

class Document extends CComponent
{
private $_textWidth;
protected $_completed=false;

public function getTextWidth()
{
return $this->_textWidth;
}
public function setTextWidth($value)
{
$this->_textWidth=$value;
}
public function getTextHeight()
{
// calculates and returns text height
}
public function setCompleted($value)
{
$this->_completed=$value;
}
}

The component above can be used like the following:

$document=new Document();
// we can write and read textWidth
$document->textWidth=100;
echo $document->textWidth;
// we can only read textHeight
echo $document->textHeight;
// we can only write completed
$document->completed=true;

24. Why do Yii run so FAST?

Ans:

Yii is so much faster because it uses sluggish loading technique widely. Like it doesn’t include a class file until the class is used initially and it doesn’t create object until it is accessed for the first time. Some of the frameworks get problems because of the performance hit because they would enable functionality no matter it is used or not during its request.

25. What about the naming convention in Yii?

Ans:

The Yii Framework employees a class naming convention whereby the names of the classes directly plot to the directories in where they are stored. The root level directory of the Yii Framework is the “framework/” directory, where all classes are stored hierarchically. Class names contain alphanumeric characters.

26. what is the component, uses, how can we do and what is the better way?

Ans:

A component is a piece of code written for specific task is used by calling controllers, helper is used for helping Yii in rendering the data to be shown to user with views, these adds to modularity in code or else same coding will be implemented in controllers.

27. What is the first function that gets loaded from a controller?

Ans:

Index function. i.e) actionIndex()

28. What is meant habtm?

Ans:

Habtm means HasAndBelongsToMany. The” has and belongs to many” is a kind of associations that defined in models for retrieving related data across different entities.

29. How to use ajax in Yii?

Ans:

We use by calling ajax helper, then using it in controller for rendering.

30. What are the possible ways to validate a registrations module for a user in Yii?

Ans:

This can be done in two ways by

  • submission in controller, or
  • using javascript/ajax while user is still filling the data. But, comparatively Second option will be better

 

31. List out some database related functions in Yii?

Ans:

Query, find, findAll , findByPk , find By

32. How to include a javascript menu through a site?

Ans:

We can include by adding the javascript files in webroot and then call them in default views if they are needed everywhere or in the related views.

33. Who was the developer of the Yii and when was it build?

Ans:

The developer of the Yii is Yii Software LLC. It was started in the year 2008 in December 3, with the version of 1.0 and continued to 1.1.13. in PHP language.

34. How does Yii Compare with Other Frameworks?

Ans:

Comparatively to most of PHP frameworks, Yii is a MVC framework. Yii bests PHP frameworks for its efficient, feature-rich and clearly-documented. Yii is designed to be fit for serious Web application development. It is neither a consequence of some project nor a corporation of third-party work.

35. How do we extend Yii?

Ans:

Extending Yii is a common action during web development. Like when we write a new controller, we extend Yii by inheriting its CController class; when we write a new widget, we will extend CWidget or an existing class. If the code is designed to be reused by third-party then we call it an extension.

36. What is a Yiibase?

Ans:

YiiBase is a helper class that serves functionalities of common framework. We should not use YiiBase directly. Instead, have to use its child class where we can customize the methods of YiiBase.

37. How to generate CRUD code?

Ans:

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.

38. What is Yii 2 ? Please Explain?

Ans:

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

39. Which PHP version is required to install Yii 2.0 ?

Ans:

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

40. What is latest version Yii 2 Framework ?

Ans:

The latest version of Yii 2 is 2.0.12, released on June 5, 2017.



 

41. Explain directory structure of Yii 2 Framework ?

Ans:

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

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

42. Provide steps to install Yii 2 Framework ?

Ans:

You can install Yii2 by running below commands via composer:

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

43. List some features Yii 2 Framework ?

Ans:

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

44. List some database related functions in Yii 2 Framework ?

Ans:

Below are list of some database related functions used in Yii 2 Framework
find(): Creates an yii\db\ActiveQueryInterface instance for query purpose.Usages:
//Getting first record matching with condition
$user = User::find()->where([‘name’ => ‘Abc’])->one();

findAll(): Returns a list of active record models that match the specified primary key value(s) or a set of column values.Usages:
// find the customers whose primary key value is 10
$customers = Customer::findAll(10);
// find customers whose age is 30 and whose status is active
$customers = Customer::findAll([‘age’ => 30, ‘status’ => ‘active’]);

insert() :Inserts a row into the associated database table using the attribute values of this record.Usages:
$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();

delete() :Deletes the table row corresponding to this active record.Usages:
$models = Customer::find()->where(‘status = 3’)->all();
foreach ($models as $model) {
$model->delete();
}
deleteAll() :Deletes rows in the table using the provided conditions.Usages:
Customer::deleteAll(‘status = 3’);
save() :Saves the current record.Usages:
$customer = new Customer; // or $customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->save();

45. Please list basic server requirements to install Yii 2 Framework ?

Ans:

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

46. What is “gii” in Yii 2 and for what it is used ?

Ans:

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

$config = [ ... ];

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

47.What is name of first file the loaded when yii framework starts ?

Ans:

index.php is first file that is called yii framework starts.In turn it will creates a new object of new yii\web\Application and start the application.
require(__DIR__ . ‘/../vendor/autoload.php’);
require(__DIR__ . ‘/../vendor/yiisoft/yii2/Yii.php’);

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

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

48.Explain naming convention in Yii 2 Framework ?

Ans:

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

49. Explain request Life Cycle in Yii2 framework .

Ans:

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

Pre-initialize the application with CApplication::preinit();
Set up the error handling;
Register core application components;
Load application configuration;
Initialize the application with CApplication::init()
Register application behaviors;
Load static application components;
Raise an onBeginRequest event;
Process the user request.
Collect information about the request;
Create a controller;
Run the controller;
Raise an onEndRequest event;

50. What are Yii helpers?

Ans:

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




 

51. What are formatter in Yii2 ?

Ans:

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

// output: January 1, 2014
echo $formatter->asDate(‘2014-01-01’, ‘long’);

// output: 12.50%
echo $formatter->asPercent(0.125, 2);

// output: cebe@example.com
echo $formatter->asEmail(‘cebe@example.com’);

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

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

52. What are Components in Yii 2 ?

Ans:

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

53. Benifits of Yii over other Frameworks ?

Ans:

Like most PHP frameworks, Yii implements the MVC (Model-View-Controller) architectural pattern and promotes code organization based on that pattern.
Yii takes the philosophy that code should be written in a simple yet elegant way. Yii will never try to over-design things mainly for the purpose of strictly following some design pattern.
Yii is a full-stack framework providing many proven and ready-to-use features: query builders and ActiveRecord for both relational and NoSQL databases; RESTful API development support; multi-tier caching support; and more.
Yii is extremely extensible. You can customize or replace nearly every piece of the core’s code. You can also take advantage of Yii’s solid extension architecture to use or develop redistributable extensions.
High performance is always a primary goal of Yii.
Larger Community.

54. What is Active Record(AR) in yii ?

Ans:

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.

55. What is difference between “render” and “renderpartial” in Yii ?

Ans:

Render function is used to render a view in Yii with specified layout whereas renderpartial is used to render only view layout is not included in view.
Renderpartial is basically used when we have to update a portion of page via AJAX.
Usage
render(‘yourviewname’);
renderpartial(‘yourviewpartial’);

56. How to get current url in Yii?

Ans:

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

57. What Is Yii Framework?

Ans:

Yii is a high-performance component-based PHP framework best for Web 2.0 development.

58. What Yii Is So Fast?

Ans:

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 would enable a functionality (e.g. DB connection, user session) no matter it is used or not during a request.

59. Can You Remember What Is Directory Structure When You Downloaded Yii?

Ans:

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

60. What Is Model,view,controller?

Ans:

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 News model may be used by the console commands, Web APIs, and the front/back end of an application. Therefore, models

    • should contain properties to represent specific data;
    • should contain business logic (e.g. validation rules) to ensure the represented data fulfills the design requirement;
    • may contain code for manipulating data. For example, a SearchForm model, besides representing the search input data, may contain a search method to implement the actual search.

Views are responsible for presenting models in the format that end users desire. In general, views

    • should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data;
    • should avoid containing code that performs explicit DB queries. Such code is better placed in models.
    • should avoid direct access to $_GET, $_POST, or other similar variables that represent the end user request. This is the controller’s job. The view should be focused on the display and layout of the data provided to it by the controller and/or model, but not attempting to access request variables or the database directly.
    • may access properties and methods of controllers and models directly. However, this should be done only for the purpose of presentation.

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, controllers

    • may access $_GET, $_POST and other PHP variables that represent user requests;
    • may create model instances and manage their life cycles. For example, in a typical model update action, the controller may first create the model instance; then populate the model with the user input from$_POST; after saving the model successfully, the controller may redirect the user browser to the model detail page. Note that the actual implementation of saving a model should be located in the model instead of the controller.
    • should avoid containing embedded SQL statements, which are better kept in models.
    • should avoid containing any HTML or any other presentational markup. This is better kept in views.

 

61. What Is The Naming Convention Inyii?

Ans:

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

62. What Is The Component,helper And Why Are They Used,is There Other Way We Can Do Same Thing,what Is Better?

Ans:

A component is an independent piece of code written for specific task that can be used by calling in controllers (example : email component), helper is used for helping yii in rendering the data to be shown to user with views, these only adds to modularity in code otherwise same coding can be implemented in controllers.

63. How Do You Proceed When You Have To Use Yii For Any Application?

Ans:

Take the framework either from Yii site or if you have changed according to your needs start from there. Proceed with basic software engg. concepts as requirement gathering etc..

This is a basic Understanding Concept in yii

    • Yii-based apps are driven by data logic. When I build an app, I always start by making sure that my database schemes are well-designed and optimised to fit the business flow of the app. Therefore, my codes are automatically generated based on my database design. And, yes…
    • Yii can generate the whole shebang of PHP codes for you automatically! Just define which database you want to use, and with a few clicks it will create a CRUD (create-read-update-delete) app for you. It looks so cute, I tell you! Speaking of automatic…
    • Yii can generate a skeleton app for you automatically. This skeleton app include a view page, a login page, contact page and basic navigation, all wrapped within a completely organized folder tree based on the standard MVC programming model.
    • The extensive choice of Yii functions makes sense. As a self-taught web programmer, I was able to map out its functions to all of the RESPONSE and REQUEST tasks I most often use when building webapps within a matter of minutes. It also doesn’t hurt that the Yii community has kindly provided cheat sheets for the functions so that I can do a quick reference when I need to.
    • The Definitive Guide to Yii document that comes with the Yii install is actually quite easy to go through, at least for me. I don’t know why, though. I thought CakePHP docs were more user-friendly and attractive, but surprisingly I was able to go through Yii documentation and tutorial in just two hours and not get cross-eyed by the end of it.
    • Yii uses MySQL and SQLite as its choice database types. Of course, you can run any other type of databases as long as you have its PDO enabled in your php.ini file. I develop using MySQL most of the time, but my fondness for SQLite is increasing, due to the fact that SQLite is so darn lightweight and easy to use.
    • Yii is integrated with jQuery, which means that many of the necessary validation functions I use can easily be plugged within the Yii function calls itself, which is usually only a line of code or two.
    • Yii is open-source, and it’s free. Open-source products turn me on.

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

Ans:

index

65. What Is Habtm?

Ans:

HasAndBelongsToMany
has and belongs to many is a kind of associations that can be defined in models for retrieving associated data across different entities

66. How Can We Use Ajax In Yii?

Ans:

By calling ajax helper and then using it in controller for rendering.

67. If You Have To Validate A Registrations Module For A User, What All Can Be Possible Ways, Which One Is The Best?

Ans:

Can be done on submission in controller, or using javascript/ajax while user is still filling the data. Second option is better.

68. Can You List Some Database Related Functions In Yii?

Ans:

find, findAll , findByPk , find By ,query

69. How Can You Include A Javascript Menu Throught The Site? Give Steps?

Ans:

By adding the javascript files in webroot and call them in default views if needed everywhere or just in the related views.

70. How To Install Or Setup Yii-framework In Your Local System ?

Ans:

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



 

71. How To Configure Yii Aplication With Database ?

Ans:

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

72. How You Can Create And Work With Different Module In Yii ?

Ans:

To create a module access gii url and there you can create a module. after creating a module from gii you need to add it the mai configuration file of your yii application.
localhost/your-app/index.php?r=gii // utl to access gii

....
'modules' => array(
'module-name',
'other-module',
'user' => array(
'activeAfterRegister' => false,
),
.....

73. What Is “gii” And Why It Is Used ?

Ans:

Gii is a module that provides Web-based code generation capabilities. To work with gii, you need to change the main configuration file of your application like following.
change the main configuration file of your application like following.

return array(
......
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>[*choose a password*]
),
),
)

To access gii in your local system, hit the url on your browser localhost/your-app/index.php?r=gii. You need to type the password that you have set in the main configuration of your app. to proceed further.

74. How You Can Remove Index.php From Your Application Url ?

Ans:

Steps to remove index.php from your application url.
Step 1: First configure your Yii-application configuration file like below code
…..
‘urlManager’=>array(
‘urlFormat’=>’path’, //mandatory
‘showScriptName’=>false, //mandatory
‘urlSuffix’=>’.html’, //not mandatory
……
),
….
Step 2: Enable apache rewrite engine. To enable rewrite engine type the following command in your terminal (Ubuntu ).
a2enmod rewrite // to enable rewrite engine
#Restart apache2 after
/etc/init.d/apache2 restart
OR
service apache2 restart
Step 3: Then, if you’d like, you can use the following .htaccess file in your application folder where index.php exists
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
Thats all the 3 steps to remove index.php from the URL.

75. What Is The Difference Between “render” And “renderpartial” ?

Ans:

render() is commonly used to render a view that corresponds 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 (which at this time means automatically inserting any necessary

76. How to install or setup Yii-framework in your local system ?

Ans:

To install Yii you need to

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

77. How to configure yii aplication with database ?

Ans:

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

78. How you can create and work with different module in yii ?

Ans:

To create a module access gii url and there you can create a module. after creating a module from gii you need to add it the mai configuration file of your yii application.

localhost/your-app/index.php?r=gii // utl to access gii

....
'modules' => array(
'module-name',
'other-module',
'user' => array(
'activeAfterRegister' => false,
),
.....

79. What is “gii” and why it is used ?

Ans:

Gii is a module that provides Web-based code generation capabilities. To work with gii, you need to change the main configuration file of your application like following.

return array(
......
'modules'=>array(
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>[*choose a password*]
),
),
)

To access gii in your local system, hit the url on your browser localhost/your-app/index.php?r=gii. You need to type the password that you have set in the main configuration of your app. to proceed further.

80. What is the first file that gets loaded when you run a application using Yii?

Ans:

index.php gets loaded when you run a application.




 

81. What is the naming convention inYii ?

Ans:

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

The Yii Framework employs a class naming convention whereby the names of the classes directly map to the directories in which they are stored. The root level directory of the Yii Framework is the framework/ directory, under which all classes are stored hierarchically.

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

82. What is component in yii? and why it is used ?

Ans:

A component is an independent piece of code written for specific task that can be used by calling in controllers (example : email component).

83. What is helper and why it is used ?

Ans:

Helper is used for helping yii in rendering the data to be shown to user with views, these only adds to modularity in code otherwise same coding can be implemented in controllers.

84. What is habtm?

Ans:

habtm refers to HasAndBelongsToMany. It is a kind of associations that can be defined in models for retrieving associated data across different entities.

85. How you can work with different layouts in your application ?

Ans:

By overriding/setting the $this->layout in your controller, you can change the layout to different one. See the following example:

class Controller extends CController
{
public $layout='//layouts/column2' ; / / change the layouts here with column2 or others

public function actionIndex(){
$this->layout=”//layouts/column3″; / / change the layouts here with column3 or others
// your code goes here
}
……
}

86. What is the difference between “render” and “renderpartial” ?

Ans:

render() is commonly used to render a view that corresponds 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 (which at this time means automatically inserting any necessary

87. What is CModel Class in Yii2?

Ans:

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.

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

Ans:

index.php