YiiFramework on cloud

1-click AWS Deployment    1-click Azure Deployment

Overview

Yii framework is an open-source component-based framework best suited for the web application and is great for rapidly developing modern web applications. Yii is built around the Model-View-Controller composite pattern that is easier to use. Yii provides secure and professional features to build robust projects faster. Yii Framework is very helpful and easy to use. It is the latest PHP framework that came into the market to make web application development more accessible and convenient for the developers. Hire credible Yii developers who will help you get the best customizable solutions for your requirements. Yii framework has a component-based architecture and full solid caching support. It is fit for developing all kinds of web applications.

What is Yii:

Yii is a component-based, high-performance PHP framework that is used for the development of modern web applications. The name Yii means Simple and Evolutionary which pronounced as “Yee or Ji” in Chinese. The acronym of Yii is YES IT IS!

Why the Yii framework best:

The best part of the Yii framework is fast, secure, efficient, and flexible, yet it deals very sensibly and realistic. It is used for all kinds of web applications as it is a universal web programming framework. Large-scale applications use this component-based architecture and sophisticated caching support for developing applications like e-commerce, forums, CMS(Content Management System), portals, and many others.

Why do we compare the Yii framework with other frameworks:

Yii framework is not a show for a single person; it has a strong core developer team and also experts contributing to Yii development. These developers are always in touch with the latest web development trends, features, and best practices in other frameworks. What all the new features found will be incorporated into the core framework and makes it a simple and elegant interface.

  • The performance of the Yii framework is very high.
  • Yii has the advantage of robust extension architecture; by this, we can customize or replace every core code.
  • Yii framework is a full-scale framework that has reusable features like query builders and active records for relational and NoSQL databases. It also supports RESTful API development, multi-tier caching, and many more.
  • Yii never overly designs things majorly because it follows some design patterns.
  • Yii code is elegant and straightforward.
  • Yii framework is implemented on the MVC(Model-View-Controller) architecture pattern and thus promotes code organization.

History

Qiang Xue founded Yii project on January 1, 2008. It overcomes the slow handling process of complex pages, difficulty to customize many controls and steep learning curve.On December 3, 2008, after almost one year’s development Yii 1.0 version was released for the public.On October 2014, Yii 2.0.0 was released which is a complete rewrite of the earlier version by keeping the original simplicity and feasibility while adopting the latest technologies to make it better.

Yii Licensing

Yii is released under New BSD License under which it can be freely used to develop a web application.Yii documentation is licensed under GNU Free Documentation License (GFDL) which means it can be copied, redistributed or modified before its next version is released.Yii logo is licensed under Creative Commons Attribution.

Yii Version

Yii has released Yii 1.0, Yii 1.1 and Yii 2.0 with their extensions.

    • Yii 1.0 was released on December 3, 2008. Many other extended versions of 1.0 came into existence. It supported PHP 5.1.0 or above and it is no longer used. It’s maintenance stopped in December 31, 2010.
    • Yii 1.1.0 was released in January 10, 2010. Many other extended versions of 1.1.0 came into existence. It supports PHP 5.1.0 or above and is still used. It’s maintenance stopped in December 31, 2016.
    • Yii 2.0.0 was released in October 12, 2014. Some extended versions of this version are also released and it also supports PHP 5.1.0 or above.

Yii 2 is the current and updated version of Yii. It’s last release was Yii 2.0.10 in October 20, 2016

Prerequisites

Yii is a powerful console tool. Hence it is recommended to have a command line access to develop an application.

Following things are required to use Yii:

  • PHP 5.4+
  • Web server

Yii – Installation:

The most straightforward way to get started with Yii2 is to use the basic application template provided by the Yii2 team. This template is also available through the Composer tool.

Step 1 − Find a suitable directory in your hard drive and download the Composer PHAR (PHP archive) via the following command.

curl -sS https://getcomposer.org/installer | php

Step 2 − Then move this archive to the bin directory.

mv composer.phar /usr/local/bin/composer

Step 3 − With the Composer installed, you can install Yii2 basic application template. Run these commands.

composer global require "fxp/composer-asset-plugin:~1.1.1" 
composer create-project --prefer-dist yiisoft/yii2-app-basic helloworld 

The first command installs the composer asset plugin, which manages npm and bower dependencies. The second command installs Yii2 basic application template in a directory called helloworld.

Step 4 − Now open the helloworld directory and launch the web server built into PHP.

php -S localhost:8080 -t web

Step 5 − Then open http://localhost:8080 in your browser. You can see the welcome page.

Welcome Page

Yii Structure

Yii2 has a new and improved application structure. It uses composer to manage its dependencies. Yii1 has only a basic application structure. While Yii2 has basic as well as advanced application structure.

Yii2 divides the entire application into following sections:

  • Backend : For backend web development
  • Common : Include common files for all the application
  • Console : Console application
  • Environments : Environment configurations
  • Frontend : For frontend web development

Yii2 Directory Structure

  1. ROOT
  2.     /                   contains the frontend entry script and web resources
  3.     /assets             contains the frontend web assets
  4. common
  5.     config/             contains shared configurations
  6.     mail/               contains view files for e-mails
  7.     models/             contains model classes used in both backend and frontend
  8.     tests/              contains various tests for objects that are common among applications
  9. console
  10.     config/             contains console configurations
  11.     controllers/        contains console controllers (commands)
  12.     migrations/         contains database migrations
  13.     models/             contains console-specific model classes
  14.     runtime/            contains files generated during runtime
  15.     tests/              contains various tests for the console application
  16. backend
  17.     assets/             contains application assets such as JavaScript and CSS
  18.     config/             contains backend configurations
  19.     controllers/        contains Web controller classes
  20.     models/             contains backend-specific model classes
  21.     runtime/            contains files generated during runtime
  22.     tests/              contains various tests for the backend application
  23.     views/              contains view files for the Web application
  24.     web/                contains the entry script and Web resources
  25. frontend
  26.     assets/             contains application assets such as JavaScript and CSS
  27.     config/             contains frontend configurations
  28.     controllers/        contains Web controller classes
  29.     models/             contains frontend-specific model classes
  30.     runtime/            contains files generated during runtime
  31.     tests/              contains various tests for the frontend application
  32.     views/              contains view files for the Web application
  33. vendor/                 contains dependent 3rd-party packages
  34. environments/           contains environment-based overrides

assets

Asset bundles are used to include JavaScript and style sheets. Lot of assessment and caching is done through the assets.There is one more asset folder inside the web directory. Yii uses this folder to cache the assets. It will have a .gitignore in this folder.If JavaScript or CSS files are need to be updated, all the folders in this directory need to be deleted. They can be deleted any time and can be auto-generated by Yii as cache files.

commands

This directory allows you to create Yii management scripts to run. These commands can be executed on command line by going on Yii root directory and typing php yii or ./yii. It will display a by default available commands list .

config

The config folder includes configuration settings which include e-mail sending, database connection, etc.

controllers

Controllers manage data traffic in MVC framework. When request is made, it is controller that processes that request.

mail

It stores templates that Yii uses to construct a mail.

models

Models manage all the database work in MVC. Any type of coding related to database is written in model.

runtime

This folder is used during processing of a web requests.

tests

This folder checks the functionality.

vendor

Yii source files reside in this directory. Third party installed module will be stored here. During upgradation, codes in this folder are overwritten hence code alteration in this directory should be avoided.

views

Views in MVC contains the pages which are displayed upon a web request. All the HTML coding is done in view directory.

web

This is the document root directory that the web server points to. The index.php file launches the Yii process when called. In this file, debugging code can be turned on or off. Debug bar is viewable at the bottom of the page.Here you can put any files, images or anything else which needs web accessibility. Files placed in this folder only will be accessed.Inside this web directory a subdirectory named asset is also present. This directory is used to respond web requests.

Yii Entry Scripts

It is the first step in application handling process and responsible to start a request handling cycle. An application has a single entry script. Request made by end users comes to entry script which initialize the application and forward the request to them.

These scripts are stored under web application directories to make them accessible by the end users. By default, they are named as index.php but can also be given other names.

For a console application, entry scripts are stored in base path and named as yii.php. They should be made executable for users to run on console application.

Entry scripts perform following work:

  • Define global constants
  • Register Composer autoloader
  • Include Yii class file
  • Load application configuration
  • Create and configure an application instance
  • Call the application to process the request

Defining Constants

Global constants are very well defined in the entry scripts. They should be defined at the beginning of an entry script for effective result when other PHP files are included. Yii framework supports following three constants:

  • YII_DEBUG: It specifies whether an application is running in debug mode or not. This mode should be mainly used during development. Because an application will keep more log information and will reveal detailed error if in debug mode.
  • YII_ENV: It defines the environment the application is running in. Its default value is ‘prod’ which stands for ‘Production’. Other values are dev and test.
  • YII_ENABLE_ERROR_HANDLER: By default it is always true. It specifies whether to enable or disable the error handler value.

Yii Models

Models are part of MVC structure. They represent the rules and logic for an application. Means they hold data and define the validating rules for the data.

Model classes are extended by yii\base\Model or its child classes.

Mainly following features are implemented using models.

  • attribute declaration
  • attribute labels
  • massive attribute assignment
  • scenario-based validation
  • can not embed HTML
  • can not be directly accessed

Attributes

Attributes mainly represent the business data. Each attribute is a publicly accessible property of a model. They can be accessed like array elements or normal object properties. it is like publicly accessible properties of a model.

The method,

  1. yii\base\Model::attributes()

specifies what attributes a model class has.

Model class is also the base class for ActiveRecord class (which is an advanced model with additional functionality).

Attribute as a normal object property:

  1. $model = new \app\models\ContactForm;
  2. // “name” is an attribute of ContactForm
  3. $model->name = ‘example’;
  4. echo $model->name;
  5. Attribute as array elements:
  6. $model = new \app\models\ContactForm;
  7. // accessing attributes like array elements
  8. $model[‘name’] = ‘example’;
  9. echo $model[‘name’];
  10. // Model is traversable using foreach.
  11. foreach ($model as $name => $value) {
  12.     echo “$name: $value\n”;
  13. }

In earlier versions of Yii, scenarios and validation were handled with the same function. But in Yii2, they are split into different functions i.e; rules() and scenarios().

Here, rules() specify the validation of a data while scenarios() specify which attributes are safe to be assigned to the model.


Attribute Labels

Attribute labels are values which are displayed with attributes to get the input from the users.

For example, in the below code, ID, Name, Designation, Contact and Email denotes the attribute labels. All this is defined under a function attributeLabels().

  1. public function attributeLabels()
  2.     {
  3.         return [
  4.             ‘id’ => ‘ID’,
  5.             ‘name’ => ‘Name’,
  6.             ‘designation’ => ‘Designation’,
  7.             ‘contact’ => ‘Contact’,
  8.             ’email’ => ‘Email’,
  9.         ];
  10.     }

YII Models 1

Look at the above snapshot, the heading data denotes the attribute labels.

Scenarios

A model may be used for different scenarios. For example, a model may be used to collect login user inputs while it may also be used to collect inputs of new users for registration. So in different scenarios a model may use different rules and logic.

Example

This is the ContactForm.php code,

  1. <?php
  2.    namespace frontend\models;
  3.    use Yii;
  4.    use yii\base\Model;
  5.    /** 
  6.    * ContactForm is the model behind the contact form. 
  7.    */
  8.    class ContactForm extends Model {
  9.       public $name;
  10.       public $email;
  11.       public $subject;
  12.       public $body;
  13.       public $verifyCode;
  14.        const SCENARIO_EMAIL_FROM_GUEST = ‘EMAIL_FROM_GUEST’;
  15.       const SCENARIO_EMAIL_FROM_USER = ‘EMAIL_FROM_USER’;
  16.       public function scenarios() {
  17.          return [
  18.             self::SCENARIO_EMAIL_FROM_GUEST => [‘name’’email’‘subject’,
  19.                ‘body’‘verifyCode’],
  20.             self::SCENARIO_EMAIL_FROM_USER => [‘name’’email’ ,‘subject’‘body’,
  21.                ‘verifyCode’],
  22.          ];
  23.       }
  24.       /** 
  25.       * @return array the validation rules. 
  26.       */
  27.       public function rules() {
  28.          return [
  29.             // name, email, subject and body are required 
  30.             [[‘name’’email’‘subject’‘body’], ‘required’],
  31.             // email has to be a valid email address 
  32.             [’email’’email’],
  33.             // verifyCode needs to be entered correctly 
  34.             [‘verifyCode’‘captcha’],
  35.          ];
  36.       }
  37.       /** 
  38.       * @return array customized attribute labels 
  39.       */
  40.       public function attributeLabels() {
  41.          return [
  42.            ‘name’ => ‘Name’,
  43.             ’email’ => ‘Email’,
  44.             ‘subject’ => ‘Subject’,
  45.             ‘body’ => ‘Body’,
  46.             ‘verifyCode’ => ‘Verification Code’,
  47.          ];
  48.       }
  49.       /** 
  50.       * Sends an email to the specified email address using the information 
  51.          collected by this model. 
  52.       * @param  string  $email the target email address 
  53.       * @return boolean whether the model passes validation 
  54.       */
  55.       public function contact($email) {
  56.          if ($this -> validate()) {
  57.             Yii::$app->mailer->compose()
  58.                ->setTo($email)
  59.                ->setFrom([$this->email => $this->name])
  60.                ->setSubject($this->subject)
  61.                ->setTextBody($this->body)
  62.                ->send();
  63.             return true;
  64.          }
  65.          return false;
  66.       }
  67.    }
  68. ?>

Create an action actionContact in SiteController.php file

  1. public function actionContact() {
  2.  $model = new ContactForm();
  3.  $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_GUEST;
  4.  if ($model->load(Yii::$app->request->post()) && $model->
  5.     contact(Yii::$app->params [‘adminEmail’])) {
  6.        Yii::$app->session->setFlash(‘contactFormSubmitted’);
  7.        return $this->refresh();
  8.  }
  9.  return $this->render(‘contact’, [
  10.     ‘model’ => $model,
  11.  ]);

Now, we’ll run the program in the browser,

YII Models 2

Now change the scenarion in actionContact in SiteController.php as

  1. $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_USER;

Now on running the program in the browser, Subject and Body field will be no longer required field.

YII Models 3

Validation Rules

These are the rules which are set for the fields to be fulfilled by the users. For example, required rule will make sure that the respective field is not empty. And email attribute will make sure that the email entered is a valid email. If values do not satisfy the rules, an error message will appear on the screen.

To declare validation rules for all the fields in all the scenarios, following code is used.

  1. public function rules()
  2. {
  3.     return [
  4.         // the name, email, subject and body attributes are required
  5.         [[‘name’’email’‘subject’‘body’], ‘required’],
  6.         // the email attribute should be a valid email address
  7.         [’email’’email’],
  8.     ];
  9. }
  10. To declare different validation rules for different scenarios, use the following code.
  11. public function rules()
  12. {
  13.     return [
  14.         // username, email and password are all required in “register” scenario
  15.         [[‘username’’email’‘password’‘d_o_b’], ‘required’‘on’ => self::SCENARIO_REGISTER],
  16.         // username and password are required in “login” scenario
  17.         [[‘username’‘password’], ‘required’‘on’ => self::SCENARIO_LOGIN],
  18.     ];
  19. }

The on property implements that, rule will be applied to a particular scenario. If you’ll not use on property than by default rule will be applied for all the fields.


Massive Assignment

In massive assignment, a model is populated with user inputs using a single line of code. Massive assignment only applies to the safe attributes.

Look at the following two types of code, both assigning the submitted form data by the end users to attributes of the ContactForm model.

First one is,

  1. $model = new \app\models\ContactForm;
  2. $model->attributes = \Yii::$app->request->post(‘ContactForm’);
  3. Second one is,
  4. $model = new \app\models\ContactForm;
  5. $data = \Yii::$app->request->post(‘ContactForm’, []);
  6. $model->name = isset($data[‘name’]) ? $data[‘name’] : null;
  7. $model->email = isset($data[’email’]) ? $data[’email’] : null;
  8. $model->subject = isset($data[‘subject’]) ? $data[‘subject’] : null;
  9. $model->body = isset($data[‘body’]) ? $data[‘body’] : null;

The first one using massive assignment is much easier, neat and less error prone.

Views

View part in the MVC structure is responsible to present data in front of users. They mainly contain the HTML content and presentational PHP code.


Creating Views

Look at the About page code of basic Yii page.

  1. <?php
  2. /* @var $this yii\web\View */
  3. use yii\helpers\Html;
  4. $this->title = ‘About’;
  5. $this->params[‘breadcrumbs’][] = $this->title;
  6. ?>
  7. <div class=“site-about”>
  8.     <h1><?= Html::encode($this->title) ?></h1>
  9.     <p>This is the About page. You may modify the following file to customize its content:</p>
  10.     <code><?= __FILE__ ?></code>
  11. </div>

And it’s output is this:

YII Views 1

In the above script, PHP code is used to generate the dynamic content in title and inside the form tag. HTML tags displays the data in a presentation view.


View Conventions

  • Views rendered by a controller should be written into @app/views/controllerID folder.
  • Views rendered by a widget should be written into widgetPath/views folder.

Following controller methods can be called to render views within controller:

  • render() : Renders the mentioned view file and applies a layout.
  • renderPartial() : Renders the mentioned view but without applying a layout.
  • renderAjax() : Renders a view without a layout and injects all registered JS scripts and CSS files.
  • renderFile() : Renders a view file in the specified path.
  • renderContent() : Renders a static ring.

Following controller methods can be called to render views within another view:

  • render() : Renders a view page.
  • renderAjax() : Renders a view without a layout and injects all registered JS scripts and CSS files.
  • renderFile() : Renders a view file in the specified path.

Following controller methods can be called to render views within widgets:

  • render() : Renders a view page.
  • renderFile() : Renders a view file in the specified path.

Example:

Step 1 Inside views/site folder, we are creating a view file exm.php file.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title></title>
  5. </head>
  6. <body>
  7.     <h1>Hello, welcome to JavaTpoint.</h1>
  8. </body>
  9. </html>

Step 2 Render exm.php view file in the about.php view file in the site folder.

  1. <?php
  2. /* @var $this yii\web\View */
  3. use yii\helpers\Html;
  4. $this->title = ‘About’;
  5. $this->params[‘breadcrumbs’][] = $this->title;
  6. ?>
  7. <div class=“site-about”>
  8.     <h1><?= Html::encode($this->title) ?></h1>
  9.     <p>This is the About page. You may modify the following file to customize its content:</p>
  10.      <?= $this->render(“exm”) ?>
  11.     <code><?= __FILE__ ?></code>
  12. </div>

Step 3 Run it on the browser.

Creating Form

We’ll create a form to get the data from users.

In our form, we’ll create four input fields for name, contact, course and email. Page will display the entered values back.

Step 1 Create Model file UserForm.php

Here we’ll create a model file to request data from the user in models/UserForm.php.

  1. <?php
  2.     namespace frontend\models;
  3.     use Yii;
  4.     use yii\base\Model;
  5.     class UserForm extends Model
  6.     {
  7.         public $name;
  8.         public $contact;
  9.         public $course;
  10.         public $email;
  11.         public function rules()
  12.         {
  13.             return [
  14.                 [[‘name’‘contact’‘course’’email’], ‘required’],
  15.                 [’email’’email’],
  16.         ];
  17.         }
  18.     }

Look at the above code, the function rules() is set to validate data from users.

Step 2 Create Action

In the controllers/SiteController.php, we’ll create an action user.

  1. <?php
  2.     namespace frontend\controllers;
  3.     use Yii;
  4.     use yii\base\InvalidParamException;
  5.     use yii\web\BadRequestHttpException;
  6.     use yii\web\Controller;
  7.     use yii\filters\VerbFilter;
  8.     use yii\filters\AccessControl;
  9.     use common\models\LoginForm;
  10.     use frontend\models\PasswordResetRequestForm;
  11.     use frontend\models\ResetPasswordForm;
  12.     use frontend\models\SignupForm;
  13.     use frontend\models\ContactForm;
  14.     use frontend\models\UserForm;
  15.     /** 
  16.     * Site controller 
  17.     */
  18.     class SiteController extends Controller
  19.     {
  20.         /** 
  21.         * @inheritdoc 
  22.         */
  23.     public function actionUser()
  24.         {
  25.             $model = new UserForm();
  26.             if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  27.                 // valid data received in $model 
  28.                 // do something meaningful here about $model … 
  29.                 return $this->render(‘user-confirm’, [‘model’ => $model]);
  30.             } else {
  31.                 // either the page is initially displayed or there is some validation error 
  32.                 return $this->render(‘user’, [‘model’ => $model]);
  33.             }
  34.         }

Look at the above code, action receives the data from the $_POST method provided by the users. The action validate() will make sure that entered data is valid.

If data is valid, then action will render to the view page user-confirm to confirm the submission. Otherwise, it will go to else part, stating error in the validation.

Step 3 Create views

Two files in the view directory will be created.

One is user-confirm.php file in views/site/user-confirm.php.

  1. <?php
  2.     use yii\helpers\Html;
  3.     ?>
  4.     <p>You have entered the following information:</p>
  5.     <ul>
  6.         <li><label>Name</label>: <?= Html::encode($model->name) ?></li>
  7.         <li><label>Contact</label>: <?= Html::encode($model->contact) ?></li>
  8.         <li><label>Course</label>: <?= Html::encode($model->course) ?></li>
  9.      <li><label>Email</label>: <?= Html::encode($model->email) ?></li>
  10.     </ul>

Other is user.php file in views/site/user.php.

  1. <?php
  2.     use yii\helpers\Html;
  3.     use yii\widgets\ActiveForm;
  4.     ?>
  5.     <?php $form = ActiveForm::begin(); ?>
  6.         <?= $form->field($model‘name’) ?>
  7.         <?= $form->field($model‘contact’) ?>
  8.         <?= $form->field($model‘course’) ?>
  9.         <?= $form->field($model’email’) ?>
  10.         <div class=“form-group”>
  11.             <?= Html::submitButton(‘Submit’, [‘class’ => ‘btn btn-primary’]) ?>
  12.         </div>
  13.     <?php ActiveForm::end(); ?>

Look at the above code, the ActiveForm widget is used to create the HTML form. The begin() and end() widgets represents the opening and closing tags of HTML form respectively.

Step 4 Running on Browser

Type the following URL in your browser to run the form,

http://localhost/form/frontend/web/index.php?r=site%2Fuser

YII Creating form 1

Now we’ll fill the details in the above form.

YII Creating form 2

On clicking the Submit button, we’ll see the validated information.

YII Creating form 3

Sessions

Sessions allow us to get access to data across various pages for each user request. A file is created in a temporary directory on the server by session to store all session variables. This stored data is available to all the pages of a web site during the visit of a particular user.

In PHP, session is accessed through the $_SESSION global variable.

When a session starts,

  • A unique ID is generated for that particular session.
  • A cookie is sent to the client side.
  • All these session variables are saved in the temporary folder on the server.
  • When a value is retrived from the session variable, it automatically gets unique session ID from the cookie. Then it looks into its temporary folder for the particular file.

Sessions Opening and Closing

Let’s see an example of opening and closing a session.

Step 1 Go to the SiteController.php file. Add the action actionCheckStatus.

  1. public function actionCheckStatus()
  2.    {
  3.   $session = Yii::$app->session;
  4.   // open a session 
  5.   $session->open();
  6.   // check if a session is already active 
  7.   if ($session->isActive) echo “Session is Active”;
  8.   // close a session 
  9.   $session->close();
  10.   // destroys all data registered to a session 
  11.   $session->destroy();
  12.    }

Look at the above code, it shows session opening, session closing, checks whether session is active or not and destroys the session.

Step 2 Run it on the browser with the URL,

http://localhost/sess/frontend/web/index.php?r=site/check-status

YII Session 1


Accessing Session Data

During accessing of the data, if no session is running than session will automatically start it.

To access the data stored in the session, run the following code.

  1. $session = Yii::$app->session;
  2. // get a session variable. The following usages are equivalent:
  3. $language = $session->get(‘language’);
  4. $language = $session[‘language’];
  5. $language = isset($_SESSION[‘language’]) ? $_SESSION[‘language’] : null;
  6. // set a session variable. The following usages are equivalent:
  7. $session->set(‘language’‘en-US’);
  8. $session[‘language’] = ‘en-US’;
  9. $_SESSION[‘language’] = ‘en-US’;
  10. // remove a session variable. The following usages are equivalent:
  11. $session->remove(‘language’);
  12. unset($session[‘language’]);
  13. unset($_SESSION[‘language’]);
  14. // check if a session variable exists. The following usages are equivalent:
  15. if ($session->has(‘language’)) …
  16. if (isset($session[‘language’])) …
  17. if (isset($_SESSION[‘language’])) …
  18. // traverse all session variables. The following usages are equivalent:
  19. foreach ($session as $name => $value) …
  20. foreach ($_SESSION as $name => $value) …

 

Flash Data

Flash data is a kind of session data, which possesses the following features.

  • Set in one request.
  • Only available during the next request.
  • Automatically deleted afterwards.

It is mainly used to deliver messages to the end users that is delivered only once such as confirmation messages sent after the login.

Example

Step 1 Create an action ationFlashData in the SiteController.php file.

  1. public function actionFlashData()
  2.    {
  3.   $session = Yii::$app->session;
  4.   // set a flash message named as “welcome” 
  5.   $session->setFlash(‘welcome’‘Successfully Logged In!’);
  6.   return $this->render(‘flashdata’);
  7.    }

Step 2 Create a view file flashdata.php in the views/site folder.

  1. <?php
  2.    use yii\bootstrap\Alert;
  3.    echo Alert::widget([
  4.       ‘options’ => [‘class’ => ‘alert-info’],
  5.       ‘body’ => Yii::$app->session->getFlash(‘welcome’),
  6.    ]);
  7. ?>

Step 3 Run it on the browser with the URL,

  1. http://localhost/flash/frontend/web/index.php?r=site/flash-data

YII Flash data 1

 

-YiiFramework helps Web developers build complex applications and deliver them on-time.Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly.YiiFramework is released under the BSD LICENSE.

Features

Features that make Yii Framework the best:

Yii is a high performance open source web application development framework that uses PHP in order to develop web 2.0 applications. Yii framework is a new yet efficient enough to be one of the mostly PHP frameworks available in the market nowadays. Does not matter whether a large or small scale projects is to be handled, Yii does it all. The developer friendly features of Yii helps it in managing highly complex projects with huge requirements. Yii is available for free download from its official website. These are some of the biggest reasons why almost every PHP web development company is now opting in for Yii web development services.

Just because of its user-friendly and new innovative features, Yii has become one of the leading and most preferable frameworks of PHP. Below are some of the key features of Yii Framework which has made it the number one choice of PHP developers nowadays:

Model View Controller (MVC) design pattern
Yii implements the widely adopted in web programming architecture- Model View Controller (MVC) design pattern. MVC aims to categorize business logic separately from user interface considerations, making it easier for the developers to change each part without affecting the other.In this MVC tool, the model represents the basic information 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 main model and the view.

image

 

 

 

 

 

 

 

 

 

 

 

 

 

Data Access Objects (DAO)
Data Access Objects (DAO) provides a generic API to access data stored in different database management systems (DBMS). This results the easier changing of the underlying DBMS to a different one without any change in the code which uses DAO to access the data.A web development company can easily avoid the long and tedious job of writing repetitive SQL queries by using Yii that allows developers to develop database in terms of objects.

Form Input and validation:
With Yii framework, the process of creating forms that can take input and validate the data becomes more simple and easy. Also, it comes with various widgets and validators that help in collecting the form input and thereafter, validating it.

AJAX-enabled widgets
Integrated with jQuery, Yii comes with a set AJAX-enabled widgets, such as auto-complete input field, data grid, treeview and hence, enabling writing highly efficient and versatile user interface extremely simple. Developers, now highly efficient User Interfaces went easy.

Authentication and Authorization
Yii comes with built-in authentication support. The Authorization via Hierarchical Role-Based Access Control (RBAC) support feature makes web development simpler yet efficient.

Error handling and Logging
Yii features comprehensive error handling and correction with errors being handled and presented more nicely, with all the log messages properly categorized.

Yii

 

 

 

 

 

 

 

Security
Security is one of biggest reasons why most of the PHP web development companies are opting for the Yii framework. Yii is equipped with many security measures to help prevent your Web applications from attacks such as SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF), and cookie tampering.

Automatic Code Generation
Yii helps developers to escape tedious jobs of rewriting codes by providing a set of intuitive and highly extensible code generation tools that helps you to generate the code you need for features such as form input, CRUD.

Detailed Documentation:
Every single method or property is properly documented. The PHP developers can easily learn Yii through the book of comprehensively tutorials available on its website.

Extensive Library
With this extensive library that contains various user contributed components which offers a never ending list of features of Yii framework.

Yii features high speed, security and other extensively useful tools which makes it a product of superb engineering that is available as an open source platform. The overall framework is highly flexible and offers intuitive environment where developers can improvise their skills and come up with new innovative applications.

-Major Features of YiiFramework:

  • Model-View-Controller (MVC) design pattern
  • Database Access Objects (DAO), Query Builder, and Active Record
  • Form input and validation
  • AJAX-enabled widgets
  • Authentication and authorization
  • Skinning and theming
  • Web services
  • Internationalization (I18N) and localization (L10N)
  • Layered caching scheme
  • Error handling and logging
  • Security
  • Unit and functionality testing
  • Automatic code generation
  • Compliance to XHTML
  • Purely object-oriented
  • Friendly with third-party code
  • Detailed documentation
  • Extension library

Videos

Yii Framework Installation and Create Web Application

YiiFramework on cloud

Related Posts