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.
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
- ROOT
- / contains the frontend entry script and web resources
- /assets contains the frontend web assets
- common
- config/ contains shared configurations
- mail/ contains view files for e-mails
- models/ contains model classes used in both backend and frontend
- tests/ contains various tests for objects that are common among applications
- console
- config/ contains console configurations
- controllers/ contains console controllers (commands)
- migrations/ contains database migrations
- models/ contains console-specific model classes
- runtime/ contains files generated during runtime
- tests/ contains various tests for the console application
- backend
- assets/ contains application assets such as JavaScript and CSS
- config/ contains backend configurations
- controllers/ contains Web controller classes
- models/ contains backend-specific model classes
- runtime/ contains files generated during runtime
- tests/ contains various tests for the backend application
- views/ contains view files for the Web application
- web/ contains the entry script and Web resources
- frontend
- assets/ contains application assets such as JavaScript and CSS
- config/ contains frontend configurations
- controllers/ contains Web controller classes
- models/ contains frontend-specific model classes
- runtime/ contains files generated during runtime
- tests/ contains various tests for the frontend application
- views/ contains view files for the Web application
- vendor/ contains dependent 3rd-party packages
- 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.
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,
- 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:
- $model = new \app\models\ContactForm;
- // “name” is an attribute of ContactForm
- $model->name = ‘example’;
- echo $model->name;
- Attribute as array elements:
- $model = new \app\models\ContactForm;
- // accessing attributes like array elements
- $model[‘name’] = ‘example’;
- echo $model[‘name’];
- // Model is traversable using foreach.
- foreach ($model as $name => $value) {
- echo “$name: $value\n”;
- }
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().
- public function attributeLabels()
- {
- return [
- ‘id’ => ‘ID’,
- ‘name’ => ‘Name’,
- ‘designation’ => ‘Designation’,
- ‘contact’ => ‘Contact’,
- ’email’ => ‘Email’,
- ];
- }
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,
- <?php
- namespace frontend\models;
- use Yii;
- use yii\base\Model;
- /**
- * ContactForm is the model behind the contact form.
- */
- class ContactForm extends Model {
- public $name;
- public $email;
- public $subject;
- public $body;
- public $verifyCode;
- const SCENARIO_EMAIL_FROM_GUEST = ‘EMAIL_FROM_GUEST’;
- const SCENARIO_EMAIL_FROM_USER = ‘EMAIL_FROM_USER’;
- public function scenarios() {
- return [
- self::SCENARIO_EMAIL_FROM_GUEST => [‘name’, ’email’, ‘subject’,
- ‘body’, ‘verifyCode’],
- self::SCENARIO_EMAIL_FROM_USER => [‘name’, ’email’ ,‘subject’, ‘body’,
- ‘verifyCode’],
- ];
- }
- /**
- * @return array the validation rules.
- */
- public function rules() {
- return [
- // name, email, subject and body are required
- [[‘name’, ’email’, ‘subject’, ‘body’], ‘required’],
- // email has to be a valid email address
- [’email’, ’email’],
- // verifyCode needs to be entered correctly
- [‘verifyCode’, ‘captcha’],
- ];
- }
- /**
- * @return array customized attribute labels
- */
- public function attributeLabels() {
- return [
- ‘name’ => ‘Name’,
- ’email’ => ‘Email’,
- ‘subject’ => ‘Subject’,
- ‘body’ => ‘Body’,
- ‘verifyCode’ => ‘Verification Code’,
- ];
- }
- /**
- * Sends an email to the specified email address using the information
- collected by this model.
- * @param string $email the target email address
- * @return boolean whether the model passes validation
- */
- public function contact($email) {
- if ($this -> validate()) {
- Yii::$app->mailer->compose()
- ->setTo($email)
- ->setFrom([$this->email => $this->name])
- ->setSubject($this->subject)
- ->setTextBody($this->body)
- ->send();
- return true;
- }
- return false;
- }
- }
- ?>
Create an action actionContact in SiteController.php file
- public function actionContact() {
- $model = new ContactForm();
- $model->scenario = ContactForm::SCENARIO_EMAIL_FROM_GUEST;
- if ($model->load(Yii::$app->request->post()) && $model->
- contact(Yii::$app->params [‘adminEmail’])) {
- Yii::$app->session->setFlash(‘contactFormSubmitted’);
- return $this->refresh();
- }
- return $this->render(‘contact’, [
- ‘model’ => $model,
- ]);
Now, we’ll run the program in the browser,
Now change the scenarion in actionContact in SiteController.php as
- $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.
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.
- public function rules()
- {
- return [
- // the name, email, subject and body attributes are required
- [[‘name’, ’email’, ‘subject’, ‘body’], ‘required’],
- // the email attribute should be a valid email address
- [’email’, ’email’],
- ];
- }
- To declare different validation rules for different scenarios, use the following code.
- public function rules()
- {
- return [
- // username, email and password are all required in “register” scenario
- [[‘username’, ’email’, ‘password’, ‘d_o_b’], ‘required’, ‘on’ => self::SCENARIO_REGISTER],
- // username and password are required in “login” scenario
- [[‘username’, ‘password’], ‘required’, ‘on’ => self::SCENARIO_LOGIN],
- ];
- }
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,
- $model = new \app\models\ContactForm;
- $model->attributes = \Yii::$app->request->post(‘ContactForm’);
- Second one is,
- $model = new \app\models\ContactForm;
- $data = \Yii::$app->request->post(‘ContactForm’, []);
- $model->name = isset($data[‘name’]) ? $data[‘name’] : null;
- $model->email = isset($data[’email’]) ? $data[’email’] : null;
- $model->subject = isset($data[‘subject’]) ? $data[‘subject’] : null;
- $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.
- <?php
- /* @var $this yii\web\View */
- use yii\helpers\Html;
- $this->title = ‘About’;
- $this->params[‘breadcrumbs’][] = $this->title;
- ?>
- <div class=“site-about”>
- <h1><?= Html::encode($this->title) ?></h1>
- <p>This is the About page. You may modify the following file to customize its content:</p>
- <code><?= __FILE__ ?></code>
- </div>
And it’s output is this:
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.
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- </head>
- <body>
- <h1>Hello, welcome to JavaTpoint.</h1>
- </body>
- </html>
Step 2 Render exm.php view file in the about.php view file in the site folder.
- <?php
- /* @var $this yii\web\View */
- use yii\helpers\Html;
- $this->title = ‘About’;
- $this->params[‘breadcrumbs’][] = $this->title;
- ?>
- <div class=“site-about”>
- <h1><?= Html::encode($this->title) ?></h1>
- <p>This is the About page. You may modify the following file to customize its content:</p>
- <?= $this->render(“exm”) ?>
- <code><?= __FILE__ ?></code>
- </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.
- <?php
- namespace frontend\models;
- use Yii;
- use yii\base\Model;
- class UserForm extends Model
- {
- public $name;
- public $contact;
- public $course;
- public $email;
- public function rules()
- {
- return [
- [[‘name’, ‘contact’, ‘course’, ’email’], ‘required’],
- [’email’, ’email’],
- ];
- }
- }
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.
- <?php
- namespace frontend\controllers;
- use Yii;
- use yii\base\InvalidParamException;
- use yii\web\BadRequestHttpException;
- use yii\web\Controller;
- use yii\filters\VerbFilter;
- use yii\filters\AccessControl;
- use common\models\LoginForm;
- use frontend\models\PasswordResetRequestForm;
- use frontend\models\ResetPasswordForm;
- use frontend\models\SignupForm;
- use frontend\models\ContactForm;
- use frontend\models\UserForm;
- /**
- * Site controller
- */
- class SiteController extends Controller
- {
- /**
- * @inheritdoc
- */
- public function actionUser()
- {
- $model = new UserForm();
- if ($model->load(Yii::$app->request->post()) && $model->validate()) {
- // valid data received in $model
- // do something meaningful here about $model …
- return $this->render(‘user-confirm’, [‘model’ => $model]);
- } else {
- // either the page is initially displayed or there is some validation error
- return $this->render(‘user’, [‘model’ => $model]);
- }
- }
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.
- <?php
- use yii\helpers\Html;
- ?>
- <p>You have entered the following information:</p>
- <ul>
- <li><label>Name</label>: <?= Html::encode($model->name) ?></li>
- <li><label>Contact</label>: <?= Html::encode($model->contact) ?></li>
- <li><label>Course</label>: <?= Html::encode($model->course) ?></li>
- <li><label>Email</label>: <?= Html::encode($model->email) ?></li>
- </ul>
Other is user.php file in views/site/user.php.
- <?php
- use yii\helpers\Html;
- use yii\widgets\ActiveForm;
- ?>
- <?php $form = ActiveForm::begin(); ?>
- <?= $form->field($model, ‘name’) ?>
- <?= $form->field($model, ‘contact’) ?>
- <?= $form->field($model, ‘course’) ?>
- <?= $form->field($model, ’email’) ?>
- <div class=“form-group”>
- <?= Html::submitButton(‘Submit’, [‘class’ => ‘btn btn-primary’]) ?>
- </div>
- <?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
Now we’ll fill the details in the above form.
On clicking the Submit button, we’ll see the validated information.
SessionsSessions 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,
Sessions Opening and ClosingLet’s see an example of opening and closing a session. Step 1 Go to the SiteController.php file. Add the action actionCheckStatus.
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 Accessing Session DataDuring 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.
|
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.
- public function actionFlashData()
- {
- $session = Yii::$app->session;
- // set a flash message named as “welcome”
- $session->setFlash(‘welcome’, ‘Successfully Logged In!’);
- return $this->render(‘flashdata’);
- }
Step 2 Create a view file flashdata.php in the views/site folder.
- <?php
- use yii\bootstrap\Alert;
- echo Alert::widget([
- ‘options’ => [‘class’ => ‘alert-info’],
- ‘body’ => Yii::$app->session->getFlash(‘welcome’),
- ]);
- ?>
Step 3 Run it on the browser with the URL,
- http://localhost/flash/frontend/web/index.php?r=site/flash-data
Cookies
A cookie is a small file that server embeds in the user’s system which is used to identify a user.
In Yii, each cookie is an object of yii\web\Cookie.
The yii\web\Request (Collection of submitted cookies in a request) and yii\web\Response (Collection of cookies that need to be sent to a user) maintains the collection of cookies via the property named cookies.
Controller deals with the cookies request and response in an application. Hence, cookies should be read and sent in controller.
Setting Cookies
Send cookies to the end users using the following codes.
- // get the cookie collection (yii\web\CookieCollection) from the “response” component
- $cookies = Yii::$app->response->cookies;
- // add a new cookie to the response to be sent
- $cookies->add(new \yii\web\Cookie([
- ‘name’ => ‘name’,
- ‘value’ => ‘sssit’,
- ]));
Getting Cookies
To get a cookie use the following code.
- // get the cookie collection (yii\web\CookieCollection) from the “request” component
- $cookies = Yii::$app->request->cookies;
- // get the cookie value. If the cookie does not exist, return “default” as the default value.
- $name = $cookies->getValue(‘name’, ‘default’);
- // an alternative way of getting the “name” cookie value
- if (($cookie = $cookies->get(‘name’)) !== null) {
- $name = $cookie->value;
- }
- // you may also use $cookies like an array
- if (isset($cookies[‘name’])) {
- $name = $cookies[‘name’]->value;
- }
- // check if there is a “name” cookie
- if ($cookies->has(‘name’)) …
- if (isset($cookies[‘name’])) …
Removing Cookies
To remove a cookie, use remove() function of Yii.
- $cookies = Yii::$app->response->cookies;
- // remove a cookie
- $cookies->remove(‘name’);
- // equivalent to the following
- unset($cookies[‘name’]);
Example:
Let’s see an example to set and show cookie’s value.
Step 1 Add the two actions actionSetCookie and actionShowCookie in the SiteController.php file.
- class SiteController extends Controller
- {
- /**
- * @inheritdoc
- */
- public function behaviors()
- {
- return [
- ‘access’ => [
- ‘class’ => AccessControl::className(),
- ‘only’ => [‘logout’, ‘signup’],
- ‘rules’ => [
- [
- ‘actions’ => [‘signup’],
- ‘allow’ => true,
- ‘roles’ => [‘?’],
- ],
- [
- ‘actions’ => [‘logout’, ‘set-cookie’, ‘show-cookie’],
- ‘allow’ => true,
- ‘roles’ => [‘@’],
- ],
- ],
- ],
- ‘verbs’ => [
- ‘class’ => VerbFilter::className(),
- ‘actions’ => [
- ‘logout’ => [‘post’],
- ],
- ],
- ];
- }
- /**
- * @inheritdoc
- */
- public function actions()
- {
- return [
- ‘error’ => [
- ‘class’ => ‘yii\web\ErrorAction’,
- ],
- ‘captcha’ => [
- ‘class’ => ‘yii\captcha\CaptchaAction’,
- ‘fixedVerifyCode’ => YII_ENV_TEST ? ‘testme’ : null,
- ],
- ];
- }
- public function actionSetCookie()
- {
- $cookies = Yii::$app->response->cookies;
- $cookies->add(new \yii\web\Cookie
- ([
- ‘name’ => ‘test’,
- ‘value’ => ‘SSSIT Pvt. Ltd.’
- ]));
- }
- public function actionShowCookie()
- {
- if(Yii::$app->getRequest()->getCookies()->has(‘test’))
- {
- print_r(Yii::$app->getRequest()->getCookies()->getValue(‘test’));
- }
- }
Step 2 Run it on the browser to set the cookie first with following URL,
http://localhost/cook/frontend/web/index.php?r=site/set-cookie
Step 3 Run it on the browser to show the cookie with following URL,
http://localhost/cook/frontend/web/index.php?r=site/show-cookie
Top 10 advantages of Yii Framework:
Easy Install
- For developers, time is a tool, not a crutch. So it is essential while dealing with framework installation. The installation process should be very less.
- Yii framework comes with an easy installation and configuration process.
Uses Modern Technologies
- Yii framework uses PHP’s Advanced features an OOP framework.
- It also uses static binding, SPL classes, interfaces, and many other functions.
Highly Extensible
- Yii framework can fulfill our actual requirements.
- Yii components are very extensible.
Facilitates Testing
- Yii framework is integrated with Codeception, which makes Yii more desirable.
Highly secure
- Yii framework provides high security for the web applications that are developed using this framework.
- Yii framework is implemented with high-security components to provide the application with more secure.
Less development time
- In Yii framework, the code can be used repetitively by the development time will not be wasted.
- We can customize the code as per the requirement.
- Yii framework uses “Gii” tool, which is a web-based code scaffolding tool that is used to create code quickly.
- Using this, we can create templates in models, controllers, forums, modules, extensions, CRUD controlled actions, and views.
Better Performance
- Yii components are caching/Yii/cache. Whatever the standard API you use, these components will be helpful.
- Applications based on Yii framework can perform better.
Error Handling
- It has error handling ability and is based on PHP 5 exception.
- When some uncaught exceptions or PHP warnings occurred during the execution of applications, then one of the error handlers will control and takes necessary procedures to handle the error.
Using Themes
- Themes are the way for customizing the outlook of our web pages.
- Using proper themes will impact the overall structure of the web application.
- In Yii, every theme has the directory that has layouts files, JavaScript file and CSS files, image files, resource files, and many more.
- In Yii, directory name will be theme name that is found in the same web root directory. At a given time, only one thing can be used/ active.
Logging
- Logging features are very flexible and extensible.
- Using level category filters Selected messages can be directed to different destinations like files, emails, etc.
-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.
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.
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