Yii Framework Training and Coaching
Suruhanjaya Pencegahan Rasuah Malaysia

Kursus ini berkonsepkan From Zero to Hero . Peserta dianggap telah mempunyai asas yang kukuh dalam pengaturcaraan PHP, tetapi pemula kepada Yii Framework. Peserta seharusnya juga telah mempunyai asas HTML, CSS dan SQL yang baik untuk mendapat hasil sepenuhnya dari kursus ini.
Perisian yang berkaitan yang akan digunakan didalam kelas ini adalah seperti berikut :-
- Laragon Full versi 4.0
- PHP 8.0
- Yii Versi 1 dan 2
- MySQL 5.7
- jQuery 3
- Twitter Bootstrap 5
- Visual Studio Code
- SQL Yog
- Composer
- Cmder
Dicadangkan PC yang akan digunakan ialah menggunakan Window 10 dengan RAM 8 Gb, dan kapasiti Storage yang Free sebanyak min 2 Gb
Syllabus
![]() |
Introduction Yii is an open-source, object-oriented, component-based MVC PHP web application framework. Yii is pronounced as "Yee" or [ji:] and in Chinese, it means "simple and evolutionary" and it can be an acronym for "Yes It Is!" What you will learn Students are expected to have strong PHP knowledge before joining this course. This course will cover the following core topics:
Course Duration : 3 days |
Module 1.0 : Introduction1.1 About PHP 7 and Yii
1.2 Fundamental PHP
Module 2.0 : Getting Started2.1 Installing Yii
2.2 Running Applications
2.3 Saying Hello
2.4 Working with Forms
2.5 Working with Databases
2.6 Generating Code with Gii
2.7 Looking Ahead
Module 3.0 : Application Structure3.1 Overview
3.2 Entry Scripts
3.3 Applications
3.4 Application Components
3.5 Controllers
3.6 Models
3.7 Views
3.8 Modules
3.9 Filters
3.10 Widgets
3.11 Assets
3.12 Extensions
Module 4.0 : Handling Requests4.1 Overview
4.2 Bootstrapping
4.3 Routing and URL Creation
4.4 Requests
4.5 Responses
4.6 Sessions and Cookies
4.7 Handling Errors
4.8 Logging
Module 5.0 : Key Concepts5.1 Components
5.2 Properties
5.3 Events
5.4 Behaviors
5.5 Configurations
5.6 Aliases
5.7 Class Autoloading
5.8 Service Locator
5.9 Dependency Injection Container
|
Module 6.0 : Displaying Data6.1 Data Formatting
6.2 Pagination
6.3 Sorting
6.4 Data Providers
6.5 Data Widgets
6.6 Working with Client Scripts
6.7 Theming
Module 7.0 : Security7.1 Authentication
7.2 Authorization
7.3 Working with Passwords
7.4 Auth Clients
7.5 Best Practices
Module 8.0 : Caching8.1 Overview
8.2 Data Caching
8.3 Fragment Caching
8.4 Page Caching
8.5 HTTP Caching
Module 9.0 : Working with Databases9.1 Data Access Objects: Connecting to a database, basic queries, transactions, and schema manipulation
9.2 Query Builder: Querying the database using a simple abstraction layer
9.3 Active Record: The Active Record ORM, retrieving and manipulating records, and defining relations
9.4 Migrations: Apply version control to your databases in a team development environment
9.5 Sphinx
9.6 Redis
9.7 MongoDB
9.8 ElasticSearch
Module 10.0 Getting Data from Users10.1 Creating Forms
10.2 Validating Input
10.3 Uploading Files
10.4 Collecting Tabular Input
10.5 Getting Data for Multiple Models
|
Module 11.0 : RESTful Web Services11.1 Quick Start
11.2 Resources
11.3 Controllers
11.4 Routing
11.5 Response Formatting
11.6 Authentication
11.7 Rate Limiting
11.8 Versioning
11.9 Error Handling
Module 12.0 : Development Tools12.1 Debug Toolbar and Debugger
12.2 Generating Code using Gii
12.3 TBD Generating API Documentation
Module 13.0 : Testing13.1 Overview
13.2 Testing environment setup
13.3 Unit Tests
13.4 Functional Tests
13.5 Acceptance Tests
13.6 Fixtures
Module 14.0 : Special Topics14.1 Advanced Project Template
14.2 Building Application from Scratch
14.3 Console Commands
14.4 Core Validators
14.5 Internationalization
14.6 Mailing
14.7 Performance Tuning
14.8 Shared Hosting Environment
14.9 Template Engines
14.10 Working with Third-Party Code
|
Training Materials
Berikut adalah perisian yang berkaitan yang akan digunakan dalam kelas ini:
| Yii Framework | Official Yii Framework web site |
| Visual Studio Code | Integrated Development Environment (IDE) for PHP / Yii framework programming |
| Laragon |
Installer for : |
| SQL Yog Community | MySQL database manager |
| Source Code Latihan | gitlab.com/azman1204/yiitot2 |
Trainer Profile
![]() |
Nama : Azman bin Zakaria
|
|
Azman merupakan senior programmer yang passionate dalam bidang pengaturcaraan komputer dari awal mulai beliau bekerja pada tahun 2000 sehingga hari ini. Beliau mempunyai pengalaman bekerja yang luas di agensi kerajaan, swasta dan sebagai freelancer.
|
|
Notes
1.1 About PHP 7 and Yii
Yii 2.0 is compatible with PHP 7 and PHP 8 (since version 2.0.38) and should run on it without any issues. Yii 1.1 has some issues which will be fixed in 1.1.17. The latest Yii 1 is 1.1.24 and is now compatible with PHP 7 and PHP 8.
1.2 Fundamental PHP
In order to really mater Yii framework, you must have a strong knowledge of Object-Oriented Programming (OOP) in PHP.
Login / authentication
-------------------------
Staff extends ActiveRecord implements IdentityInterface {
function getId() {
}
findIndetity() {
}
}
Yii Framework
-------------
1. Layout
- custom
2. Authentication and Authorization
- login
- access level
1. MVC = Model.view.controller
2. ORM = Obj. Relational Mapping
- Query Builder
3. Bootstrap
- layout
- twitter bootstrap 4 / 3 (yii 1)
4. Gii
- code generator
5. Terminal
6. Complete library
7. Debug Bar
DRY = Don't repeat yourself
3 folder utama:
- models
- Actor.php
- User2.php
public static function tableName() {
return 'user';
}
- views
- actor
- list.php
- form.php
- controllers
- ActorController.php
public function actionList() {
return $this->render('nama view file', ['key' => 'val']);
}
2.1 Installing Yii
Yii 1 Installation
- Go to yiiframework.com/download, and download the latest Yii 1 framework
- Extract the zip file into Laragon "www" folder. i.e yiiapp
- Go to
http://hostname/path/to/yii/requirements/index.phpto check Yii and PHP compatibility - Open terminal, change directory to yiiapp/framework folder, and type
>yiic webapp ../myapp - Open browser and type
http://localhost/yiiapp/myapp
Yii 2 installation
There are two methods to install Yii 2:
1. via archive file (zip file)
2. via Composer (the preferred one)
- open terminal, and change directory to Laragon www folder
>composer create-project --prefer-dist yiisoft/yii2-app-basic basic- Open browser and type
http://localhost/basic/web
2.2 Running Applications
In both cases of Yii 1 and Yii 2, we use our favorite browser to run the application. There are settings in Apache / Nginx / IIS that you can apply to run the application on a domain instead of localhost / 127.0.0.1. Luckily Laragon comes with an auto domain setting and you just need to stop and restart the services to apply a new domain after installation.
2.3 Saying Hello
1. Create a new file named "HelloController.php" in the controllers folder. Type the following code:
<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller {
public function actionWorld() {
return "Hello World";
}
}
2. Open browser, type http://localhost/basic/web/index.php?r=hello/world. The "Hello World" will be displayed.
2.4 Working with Forms
Let's see ho Yii 2 handle form in a view
1. Create a file in "views" folder, name it myform.php, then type the following code
<form action="index.php?r=hello/save" method="post">
<input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
name : <input type="text" name="name">
<input type="submit" value="Save" />
</form>
2. Adjust the HelloController.php, create a new function.
<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller {
public function actionWorld() {
return "Hello World";
}
public function actionMyform() {
return $this->render('myform');
}
public function actionSave() {
echo \Yii::$app->request->post('name');
}
}
3. In browser, type HTTP://localhost/basic/web/index.php?r=hello/myform
- Input any name in the field and submit
- The output will show the name entered!
2.5 Working with Databases
Yii provides powerful support for database programming. Built on top of the PHP Data Objects (PDO) extension, Yii Data Access Objects (DAO) enables access to different database management systems (DBMS) in a single uniform interface. Applications developed using Yii DAO can be easily switched to use a different DBMS without the need to modify the data accessing code.
Yii Query Builder offers an object-oriented method for building SQL queries, which helps reduce the risk of SQL injection attacks. And Yii Active Record (AR), implemented as a widely adopted Object-Relational Mapping (ORM) approach, further simplifies database programming. Representing a table in terms of a class and a row an instance, Yii AR eliminates the repetitive task of writing SQL statements that mainly deal with CRUD (create, read, update and delete) operations.
Although the included Yii database features can handle nearly all database-related tasks, you can still use your own database libraries in your Yii application. As a matter of fact, the Yii framework is carefully designed to be used together with other third-party libraries.
2.6 Generating Code with Gii
Starting from version 1.1.2, Yii is equipped with a Web-based code generation tool called Gii. It supersedes the previous yiic shell generation tool which runs on the command line.
- open a browser and go to HTTP://localhost/basic/web/index.php?r=gii
- A Gii panel will be displayed
- Play around by generating a new Controller
2.7 Looking Ahead
In the next module will be starting to discuss in detail the MVC framework.
3.1 Overview
![]() |
Yii 2 follows the MVC design pattern, where M stands for Model, V stands for view, and C stands for the controller. We’re going to discuss this briefly, but just for an overview.
Models, Views, and Controllers
|
3.2 Entry Scripts
Entry scripts are responsible for starting a request handling cycle. They are just PHP scripts accessible by users. Web application (as well as a console application) has a single entry script. The End user makes a request to the entry script. Then the entry script instantiates application instances and forwards requests to them.
The entry script for a console application is usually stored in a project base path and named yii.bat (win) / yii (linux / mac). Entry script for a web application must be stored under a web-accessible directory. It is often called index.php.
The Entry scripts do the following:
- Define constants
- Register Composer autoloader
- Include Yii files
- Load configuration
- Create and configure an application instance
- Process the incoming request
3.3 Components
To create a reusable functionality, the user can write his own components. Components are just objects that contain logic. For example, a component could be a weight converter.
3.4 Application Components
These are objects that instanced just one time in the whole application. The main difference between Components and Application components is that the latter can have only one instance in the whole application.
3.5 Controllers
Controllers are responsible for processing requests and generating responses. After the user's request, the controller will analyze request data, pass them to the model, then insert the model result into a view, and generate a response.
Understanding Actions
Controllers include actions. They are the basic units that users can request for execution. A controller can have one or several actions. Let's revisit our previous controller. All functions that are accessible from the web start with the "action" keyword.
The URL to access actionWorld() function is index.php?r=hello/world.
- hello - from HelloController
- world - from actionWorld()
<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller {
public function actionWorld() {
return "Hello World";
}
public function actionMyform() {
return $this->render('myform');
}
public function actionSave() {
echo \Yii::$app->request->post('name');
}
}
3.6 Models
Models are objects representing business logic and rules. To create a model, you should extend the yii\base\Model class or its subclasses.
Attributes
Attributes represent the business data. They can be accessed like array elements or object properties. Each attribute is a publicly accessible property of a model. To specify what attributes a model possesses, you should override the yii\base\Model::attributes() method.
Let us have a look at the ContactForm model of the basic application template.
<?php
namespace app\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;
// ... more code here
}
3.7 Views
Views are responsible for presenting the data to end-users. In web applications, Views are just PHP script files containing HTML and PHP code. Let's look at about.php in views/site/about.
Rules for creating a view:
- The view must be under a folder following the controller name, i.e hello (HelloController), site (SiteController) etc.
<?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>
3.8 Modules
A module is an entity that has its own models, views, controllers, and possibly other modules. It is practically an application inside the application.
Step 1 − Create a folder called modules inside your project root. Inside the modules folder, create a folder named hello. This will be the basic folder for our Hello module.
Step 2 − Inside the hello folder, create a file Hello.php with the following code.
<?php
namespace app\modules\hello;
class Hello extends \yii\base\Module {
public function init() {
parent::init();
}
}
?>
We have just created a module class. This should be located under the module's base path. Every time a module is accessed, an instance of the correspondent module class is created. The init() function is for initializing the module's properties.
Step 3 − Now, add two more directories inside the hello folder − controllers and views. Add a CustomController.php file to the controller’s folder.
<?php
namespace app\modules\hello\controllers;
use yii\web\Controller;
class CustomController extends Controller {
public function actionGreet() {
return $this->render('greet');
}
}
?>
When creating a module, a convention is to put the controller classes into the controller’s directory of the module's base path. We have just defined the actionGreet function, that just returns a greet view. Views in the module should be put in the views folder of the module's base path. If views are rendered by a controller, they should be located in the folder corresponding to the controllerID. Add custom folder to the views folder.
Step 4 − Inside the custom directory, create a file called greet.php with the following code.
<h1>Hello world from custom module!</h1>
Step 5 − Modify the config/web.php file.
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
....
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => $params,
];
...
?>
A route for a module's controller must begin with the module ID followed by the controller ID and action ID.
Step 6 − To run the actionGreet in our application, we should use the following route.
hello/custom/greet. Where hello is a module ID, custom is a controller ID, and greet is an action ID.
Step 7 − Now, type http://localhost:8080/basic/web/index.php?r=hello/custom/greet and you will see the output.
3.9 Filters
Filters are objects that run before and/or after controller actions. For example, an access control filter may run before actions to ensure that they are allowed to be accessed by particular end users; a content compression filter may run after actions to compress the response content before sending them out to end users.
A filter may consist of a pre-filter (filtering logic applied before actions) and/or a post-filter (logic applied after actions).
public function behaviors() {
return [
[
'class' => 'yii\filters\HttpCache',
'only' => ['index', 'view'],
'lastModified' => function ($action, $params) {
$q = new \yii\db\Query();
return $q->from('user')->max('updated_at');
},
],
];
}
By default, filters declared in a controller class will be applied to all actions in that controller. You can, however, explicitly specify which actions the filter should be applied to by configuring the only property. In the above example, the HttpCache filter only applies to the index and view actions. You can also configure the except property to prevent some actions from being filtered.
Besides controllers, you can also declare filters in a module or application. When you do so, the filters will be applied to all controller actions belonging to that module or application, unless you configure the filters' only and except properties like described above.
3.10 Widgets
A widget is a reusable client-side code, which contains HTML, CSS, and JS. This code includes minimal logic and is wrapped in a yii\base\Widget object. We can easily insert and apply this object in any view.
Step 1 − To see widgets in action, create an actionTestWidget function in the SiteController with the following code.
public function actionTestWidget() {
return $this->render('testwidget');
}
In the above example, we just returned a View called “testwidget”.
Step 2 − Now, inside the views/site folder, create a View file called testwidget.php.
<?php
use yii\bootstrap4\Progress;
?>
<?= Progress::widget(['percent' => 60, 'label' => 'Progress 60%']) ?>
Step 3 − If you go to http://localhost/basic/index.php?r=site/test-widget, you will see the progress bar widget.
3.11 Assets
An asset is a file (css, js, video, audio or image, etc.) that may be referenced in a web page. Yii manages assets in asset bundles. The purpose of an asset bundle is to have a group of related JS or CSS files in the code base and to be able to register them within a single PHP call. Asset bundles can also depend on other asset bundles.
Inside the assets folder, you will find the asset bundle for the basic application template −
<?php
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap4\BootstrapAsset',
];
}
The above class specifies that the asset files are located inside the @webroot folder, which corresponds to the URL @web. The bundle contains no JS files and a single CSS file. The bundle depends on other bundles
3.12 Extensions
Extensions are packages specifically designed to be used in Yii applications. You can share your own code as an extension or use third-party extensions to add features to your application.
Using Extensions
Most extensions are distributed as Composer packages. Composer installs packages from Packagist – the repository for Composer packages.
To install a third-party extension, you should −
- Add the extension to a
composer.jsonfile. - Run
composer install.
4.1 Overview
In this module, we will dive deeper into the Yii engine such as how to handle Request and Response.
4.2 Bootstrapping
Bootstrapping refers to the process of preparing the environment before an application starts to resolve and process an incoming request. Bootstrapping is done in two places: the entry script and the application. In the entry script, class autoloaders for different libraries are registered. This includes the Composer autoloader through its autoload.php file and the Yii autoloader through its Yii class file. The entry script then loads the application configuration and creates an application instance.
In the constructor of the application, the following bootstrapping work is done:
- preInit() is called, which configures some high-priority application properties, such as basePath.
- Register the error handler.
- Initialize application properties using the given application configuration.
- init() is called which in turn calls bootstrap() to run bootstrapping components.
- Include the extension manifest file vendor/yiisoft/extensions.php.
- Create and run bootstrap components declared by extensions.
- Create and run application components and/or modules that are declared in the application's bootstrap property.
Because the bootstrapping work has to be done before handling every request, it is very important to keep this process light and optimize it as much as possible. Try not to register too many bootstrapping components. A bootstrapping component is needed only if it wants to participate the whole life cycle of requesting handling. For example, if a module needs to register additional URL parsing rules, it should be listed in the bootstrap property so that the new URL rules can take effect before they are used to resolve requests.
In production mode, enable a bytecode cache, such as PHP OPcache or APC, to minimize the time needed for including and parsing PHP files. Some large applications have very complex application configurations which are divided into many smaller configuration files. If this is the case, consider caching the whole configuration array and loading it directly from cache before creating the application instance in the entry script.

4.3 Routing and URL Creation
To change the default route of the application, you should configure the defaultRoute property.
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'defaultRoute' => 'site/contact',
'components' => [
//other code
?>
To put your application in maintenance mode temporarily, you should configure the yii\web\Application::$catchAll property.
Add the following function to the SiteController.
public function actionMaintenance() {
echo "<h1>Maintenance</h1>";
}
Adjust the config/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'catchAll' => ['site/maintenance'],
'components' => [
//OTHER CODE
Other useful function related to URL dan route are :
- Url::to(['post/index'])
- Url::home()
- Url::base()
- Url::previous()
- Url::canonical()
4.4 Requests
Requests are represented by the yii\web\Request object, which provides information about HTTP headers, request parameters, cookies, and so forth. The methods get() and post() return request parameters of the request component.
Example −
$req = Yii::$app->request;
/*
* $get = $_GET;
*/
$get = $req->get();
/*
* if(isset($_GET['id'])) {
* $id = $_GET['id'];
* } else {
* $id = null;
* }
*/
$id = $req->get('id');
/*
* if(isset($_GET['id'])) {
* $id = $_GET['id'];
* } else {
* $id = 1;
* }
*/
$id = $req->get('id', 1);
/*
* $post = $_POST;
*/
$post = $req->post();
/*
* if(isset($_POST['name'])) {
* $name = $_POST['name'];
* } else {
* $name = null;
* }
*/
$name = $req->post('name');
/*
* if(isset($_POST['name'])) {
* $name = $_POST['name'];
* } else {
* $name = '';
* }
*/
$name = $req->post('name', '');
4.5 Responses
When a web application handles a request, it generates a response object, which contains HTTP headers, body, and HTTP status code. In most cases, you will use the response application component. By default, it is an instance of yii\web\Response.
public function actionTestResponse() {
Yii::$app→response->statusCode = 201;
}
The most common status codes are :
1. 404 - Page not found
2. 500 - Server Error
3. 200 - Ok
4.6 Sessions and Cookies
Sessions make data accessible across various pages. A session creates a file on the server in a temporary directory where all session variables are stored. This data is available to all the pages of your web site during the visit of that particular user. When a session starts, the following happens:
- PHP creates a unique ID for that particular session.
- A cookie called PHPSESSID is sent on the client-side (to the browser).
- The server creates a file in the temporary folder where all session variables are saved.
- When a server wants to retrieve the value from a session variable, PHP automatically gets the unique session ID from the PHPSESSID cookie. Then, it looks in its temporary directory for the needed file.
To start a session, you should call the session_start() function. All session variables are stored in the $_SESSION global variable. You can also use the isset() function to check whether the session variable is set.
<?php
session_start();
if( isset( $_SESSION['number'] ) ) {
$_SESSION['number'] += 1;
}else {
$_SESSION['number'] = 1;
}
$msg = "This page was visited ". $_SESSION['number'];
$msg .= "in this session.";
echo $msg;
?>
To destroy a session, you should call the session_destroy() function. To destroy a single session variable, call the unset() function.
Session in Yii
public function actionAccessSession() {
$session = Yii::$app->session;
// set a session variable
$session->set('language', 'ru-RU');
// get a session variable
$language = $session->get('language');
var_dump($language);
// remove a session variable
$session->remove('language');
// check if a session variable exists
if (!$session->has('language')) echo "language is not set";
$session['captcha'] = [
'value' => 'aSBS23',
'lifetime' => 7200,
];
var_dump($session['captcha']);
}
4.7 Handling Errors
Yii includes a built-in error handler. The Yii error handler does the following −
- Converts all non-fatal PHP errors into catchable exceptions.
- Displays all errors and exceptions with a detailed call stack.
- Supports different error formats.
- Supports using a controller action to display errors.
public function actionShowError() {
throw new NotFoundHttpException("Something unexpected happened");
}
You can use dedicated error actions to customize the error display. see in the config/web.php file.
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
],
The above configuration defines that when an error needs to be displayed without the call stack, the site/error action will be executed.
4.8 Logging
Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages. To log a message, you should call one of the following methods:
- Yii::error() − Records a fatal error message.
- Yii::warning() − Records a warning message.
- Yii::info() − Records a message with some useful information.
- Yii::trace() − Records a message to trace how a piece of code runs.
The above methods record log messages at various categories. They share the following function signature −
function ($message, $category = 'application')
Please look inside config/web.php for log setting
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning', 'info'],
],
],
],
6.1 Data Formatting
6.2 Pagination
6.3 Sorting
6.4 Data Providers
6.5 Data Widgets
6.6 Working with Client Scripts
6.7 Theming
9.1 Data Access Objects: Connecting to a database, basic queries, transactions, and schema manipulation
Yii DAO (Database Access Object) provides an API for accessing databases. It also serves as the foundation for other database access methods: active record and query builder. Yii DAO supports the following databases:
- MySQL
- MSSQL
- SQLite
- MariaDB
- PostgreSQL
- ORACLE
Creating Database Connection
A common practice is to configure a DB connection inside the application components. For example, in the basic application template the DB connection configuration is located in the config/db.php file as shown in the following code.
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host = localhost;dbname = helloworld',
'username' => 'azman',
'password' => '123574896',
'charset' => 'utf8',
];
?>
To access the DB connection you may use this expression.
Yii::$app->db
9.2 Query Builder: Querying the database using a simple abstraction layer
To execute an SQL query, you should follow these steps −
- Create an yii\db\Command with an SQL query.
- Bind parameters (not required)
- Execute the command.
public function actionTestDb(){
// return a set of rows. each row is an associative array of column names and values.
// an empty array is returned if the query returned no results
$users = Yii::$app->db->createCommand('SELECT * FROM user LIMIT 5')
->queryAll();
var_dump($users);
// return a single row (the first row)
// false is returned if the query has no result
$user = Yii::$app->db->createCommand('SELECT * FROM user WHERE id=1')
->queryOne();
var_dump($user);
// return a single column (the first column)
// an empty array is returned if the query returned no results
$userName = Yii::$app->db->createCommand('SELECT name FROM user')
->queryColumn();
var_dump($userName);
// return a scalar value
// false is returned if the query has no result
$count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM user')
->queryScalar();
var_dump($count);
}
9.3 Active Record: The Active Record ORM, retrieving and manipulating records, and defining relations
Active Record provides an object-oriented API for accessing data. An Active Record class is associated with a database table. Yii provides the Active Record support for the following relational databases:
- MySQL 4.1 or later
- SQLite 2 and 3:
- PostgreSQL 7.3 or later
- Microsoft SQL Server 2008 or later
- CUBRID 9.3 or later
- Oracle
- ElasticSearch
- Sphinx
Additionally, the Active Record class supports the following NoSQL databases:
- Redis 2.6.12 or later
- MongoDB 1.3.0 or later
After declaring an Active Record class(MyUser model in our case) for a separate database table, you should follow these steps to query data from it:
- Create a new query object, using the yii\db\ActiveRecord::find() method.
- Build the query object.
- Call a query method to retrieve data.
public function actionTestDb() {
// return a single user whose ID is 1
// SELECT * FROM `user` WHERE `id` = 1
$user = MyUser::find()
->where(['id' => 1])
->one();
var_dump($user);
// return the number of users
// SELECT COUNT(*) FROM `user`
$users = MyUser::find()
->count();
var_dump($users);
// return all users and order them by their IDs
// SELECT * FROM `user` ORDER BY `id`
$users = MyUser::find()
->orderBy('id')
->all();
var_dump($users);
}
Other example:
public function actionTestDb() {
// returns a single customer whose ID is 1
// SELECT * FROM `user` WHERE `id` = 1
$user = MyUser::findOne(1);
var_dump($user);
// returns customers whose ID is 1,2,3, or 4
// SELECT * FROM `user` WHERE `id` IN (1,2,3,4)
$users = MyUser::findAll([1, 2, 3, 4]);
var_dump($users);
// returns a user whose ID is 5
// SELECT * FROM `user` WHERE `id` = 5
$user = MyUser::findOne([
'id' => 5
]);
var_dump($user);
}
Save data example:
public function actionTestDb() {
// insert a new row of data
$user = new MyUser();
$user->name = 'MyCustomUser2';
$user->email = 'mycustomuser@gmail.com';
$user->save();
var_dump($user->attributes);
// update an existing row of data
$user = MyUser::findOne(['name' => 'MyCustomUser2']);
$user->email = 'newemail@gmail.com';
$user->save();
var_dump($user->attributes);
}
Photo Gallery
Coming Soon ...
Borang Penilaian Keberkesanan Latihan
Training evaluation · Yii Framework Training and Coaching
Log in with the account you registered for this training to fill in the survey.
Log in to fill in the surveyAttendance
Students (8)
| # | Name |
|---|---|
| 1. | nurhazwani |
| 2. | Iezzatul Syahiera Badal Abdullah |
| 3. | Hazwani Binti Tuah |
| 4. | MAIZAN BINTI SULAIMAN |
| 5. | ABDUL HASIM BIN HASAN |
| 6. | SYED ABDULLAH BIN SAYED ABU BAKAR |
| 7. | Hamidah Omar |
| 8. | qthymzezlv |



