<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// register Composer autoloader
require __DIR__ . '/../vendor/autoload.php';
// include Yii class file
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
// load application configuration
$config = require __DIR__ . '/../config/web.php';
// create, configure and run application
(new yii\web\Application($config))->run();
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// register Composer autoloader
require __DIR__ . '/vendor/autoload.php';
// include Yii class file
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
// load application configuration
$config = require __DIR__ . '/config/console.php';
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
YII_DEBUG
: specifies whether the application is running in debug mode. When in debug mode, an application will keep more log information, and will reveal detailed error call stacks if exceptions are thrown. For this reason, debug mode should be used mainly during development. The default value of YII_DEBUG is false.YII_ENV
: specifies which environment the application is running in. This will be described in more detail in the Configurations section. The default value of YII_ENV is 'prod', meaning the application is running in production environment.YII_ENABLE_ERROR_HANDLER
: specifies whether to enable the error handler provided by Yii. The default value of this constant is true.defined('YII_DEBUG') or define('YII_DEBUG', true);
if (!defined('YII_DEBUG')) {
define('YII_DEBUG', true);
}
composer global require "fxp/composer-asset-plugin:^1.3.1"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
$_GET
, $_POST
, and other PHP variables representing user requests.\Yii::$app
.require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
// load application configuration
$config = require __DIR__ . '/../config/web.php';
// instantiate and configure the application
(new yii\web\Application($config))->run();
web.php
file in the above example.urlManager
component is responsible for routing Web requests to appropriate controllers; the db component provides DB-related services; and so on.\Yii::$app->componentID
\Yii::$app->db
to get the DB connection, and \Yii::$app->cache
to get the primary cache registered with the application.yii\base\Application::$components
property in application configurations. [
'components' => [
// register "cache" component using a class name
'cache' => 'yii\caching\ApcCache',
// register "db" component using a configuration array
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=demo',
'username' => 'root',
'password' => '',
],
// register "search" component using an anonymous function
'search' => function () {
return new app\components\SolrService;
},
],
]
yii\base\Model
or its child classes. The base class yii\base\Model
supports many useful features:yii\helpers
namespace.use yii\helpers\Html;
echo Html::encode('Test > test');
yii\i18n\Formatter
, which provides a set of methods to format data as date/time, numbers, currencies, and other commonly used formats. You can use the formatter as the following,$formatter = \Yii::$app->formatter;
// output: January 1, 2021
echo $formatter->asDate('2021-01-01', 'long');
// output: 12.50%
echo $formatter->asPercent(0.125, 2);
// output: jtp@example.com
echo $formatter->asEmail('jtp@example.com');
// output: Yes
echo $formatter->asBoolean(true);
// it also handles display of null values:
// output: (not set)
echo $formatter->asDate(null);
yii\base\ActionFilter
and override the beforeAction()
and/or afterAction()
methods. The former will be executed before an action runs while the latter after an action runs. The return value of beforeAction()
determines whether an action should be executed or not. If it is false, the filters after this one will be skipped and the action will not be executed.namespace app\components;
use Yii;
use yii\base\ActionFilter;
class ActionTimeFilter extends ActionFilter
{
private $_startTime;
public function beforeAction($action)
{
$this->_startTime = microtime(true);
return parent::beforeAction($action);
}
public function afterAction($action, $result)
{
$time = microtime(true) - $this->_startTime;
Yii::debug("Action '{$action->uniqueId}' spent $time second.");
return parent::afterAction($action, $result);
}
}
<?php
use yii\jui\DatePicker;
?>
<?= DatePicker::widget(['name' => 'date']) ?>
views
. You can call the yii\base\Widget::widget()
method to use a widget in a view. The method takes a configuration
array for initializing the widget and returns the rendering result of the widget. For example, the following code inserts a date picker widget which is configured to use the Russian language and keep the input in the from_date
attribute of $model.<?php
use yii\jui\DatePicker;
?>
<?= DatePicker::widget([
'model' => $model,
'attribute' => 'from_date',
'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
]) ?>
yii\base\Widget::begin()
and yii\base\Widget::end()
. For example, the following code uses the yii\widgets\ActiveForm
widget to generate a login form. The widget will generate the opening and closing <form>
tags at the place where begin() and end() are called, respectively. Anything in between will be rendered as is.<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Login') ?>
</div>
<?php ActiveForm::end(); ?>
yii\base\Widget::widget()
which returns the rendering result of a widget, the method yii\base\Widget::begin()
returns an instance of the widget which you can use to build the widget content.\Yii::$container->set('yii\widgets\LinkPager', ['maxButtonCount' => 5]);
config/web.php
configuration file :$config = [ ... ];
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
} ​
index.php
is the first file that loaded when we run an application using the Yii application. It will create a new object of new yii\web\Application
and start the application.require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
// load application configuration
$config = require(__DIR__ . '/../config/web.php');
// instantiate and configure the application
(new yii\web\Application($config))->run(); ​
http://hostname/index.php?r=ControllerID/ActionID ​
r
refers to the route.CApplication::preinit();
CApplication::init()
onBeginRequest
event; onEndRequest
event;yiisoft/yii2-debug
extension adds a handy debug toolbar at the bottom of every page in your application to help you more easily grasp how the pages are generated. You can use extensions to accelerate your development process. You can also package your code as extensions to share with other people your great work.composer.json
file of your application and specify which extensions (Composer packages) you want to install.Packagist
- the biggest repository for open source Composer packages. You can look for extensions on Packagist
. You may also create your own repository and configure Composer to use it. This is useful if you are developing private extensions that you want to share within your projects only.BasePath/vendor
directory, where BasePath
refers to the application's base path. Because Composer is a dependency manager, when it installs a package, it will also install all its dependent packages.yiisoft/yii2-imagine
extension, modify your composer.json
like the following :{
// ...
"require": {
// ... other dependencies
"yiisoft/yii2-imagine": "*"
}
}
yiisoft/yii2-imagine
under BasePath/
vendor. You should also see another directory imagine/imagine which contains the installed dependent package. yiisoft/yii2-imagine
is a core extension developed and maintained by the Yii developer team. All core extensions are hosted on Packagist
and named like yiisoft/yii2-xyz
, where xyz
varies for different extensions.yii\imagine\Image
class provided by the yiisoft/yii2-imagine
extension:use Yii;
use yii\imagine\Image;
// generate a thumbnail image
Image::thumbnail('@webroot/img/test-image.jpg', 120, 120)
->save(Yii::getAlias('@runtime/thumb-test-image.jpg'), ['quality' => 50]);
localhost/your-app/index.php?r=gii // utl to access gii
....
'modules' => array(
'module-name',
'other-module',
'user' => array(
'activeAfterRegister' => false,
),
.....
< ?php
namespace yii\helpers;
class ArrayHelper extends BaseArrayHelper
{
public static function merge($x, $y)
{
// your custom implementation
}
}​
main/config.php
user component :'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'loginUrl' => [ 'yourcontroller/youraction' ],
],
controllers/siteController
. You can change it to your module or controller name by putting the below configuration in main/config.php
:'defaultRoute' => 'yourcontroller',
CFormModel
represents a data model that collects HTML form inputs. The data collected by CFormModel
are stored in memory only instead of a database. Therefore to collect user inputs, you may extend CFormModel
and define the attributes whose values are collected from user inputs. $_SESSION
variable. Whereas to access the data stored in a session, you can do the following :$session = Yii::$app->session; // get a session variable.
$_SESSION
and $_COOKIE
, respectively. Yii encapsulates sessions and cookies as objects and thus allows you to access them in an object-oriented fashion with additional useful enhancements.$session = Yii::$app->session;
// check if a session is already open
if ($session->isActive) ...
// open a session
$session->open();
// close a session
$session->close();
// destroys all data registered to a session.
$session->destroy();
Cookies : Yii represents each cookie as an object of yii\web\Cookie. Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named cookies. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.
The part of the application dealing with request and response directly is controller. Therefore, cookies should be read and sent in controller.
Reading Cookies : You can get the cookies in the current request using the following code:
// get the cookie collection (yii\web\CookieCollection) from the "request" component
$cookies = Yii::$app->request->cookies;
// get the "language" cookie value. If the cookie does not exist, return "en" as the default value.
$language = $cookies->getValue('language', 'en');
// an alternative way of getting the "language" cookie value
if (($cookie = $cookies->get('language')) !== null) {
$language = $cookie->value;
}
// you may also use $cookies like an array
if (isset($cookies['language'])) {
$language = $cookies['language']->value;
}
// check if there is a "language" cookie
if ($cookies->has('language')) ...
if (isset($cookies['language'])) ...
Sending Cookies : You can send cookies to end users using the following code :
// 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' => 'language',
'value' => 'zh-CN',
]));
// remove a cookie
$cookies->remove('language');
// equivalent to the following
unset($cookies['language']);
YII_ENABLE_ERROR_HANDLER
to be false in the entry script of your application.errorHandler
. You may configure it in the application configuration like the following :return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 20,
],
],
];
use Yii;
use yii\base\ErrorException;
try {
10/0;
} catch (ErrorException $e) {
Yii::warning("Division by zero.");
}
// execution continues...
yii\web\NotFoundHttpException
. The error handler will correctly set the HTTP status code of the response and use an appropriate error view to display the error message.use yii\web\NotFoundHttpException;
throw new NotFoundHttpException();
Yii::debug()
: record a message to trace how a piece of code runs. This is mainly for development use.Yii::info()
: record a message that conveys some useful information.Yii::warning()
: record a warning message that indicates something unexpected has happened.Yii::error()
: record a fatal error that should be investigated as soon as possible.$message, $category = 'application'
), where $message stands for the log message to be recorded, while $category is the category of the log message. The code in the following example records a trace message under the default category application:Yii::debug('start calculating average revenue');
yii\helpers\VarDumper::export()
.__METHOD__
for the category names. This is also the approach used in the core Yii framework code. For example : Yii::debug('start calculating average revenue', __METHOD__);
__METHOD__
constant evaluates as the name of the method (prefixed with the fully qualified class name) where the constant appears. For example, it is equal to the string 'app\controllers\RevenueController::calculate
' if the above line of code is called within this method.log()
method of the logger object which is a singleton accessible through the expression Yii::getLogger()
. When enough messages are logged or when the application ends, the logger object will call a message dispatcher to send recorded log messages to the registered log targets.yii\log\Target
class or its child class. It filters the log messages by their severity levels and categories and then exports them to some medium. For example, a database target exports the filtered log messages to a database table, while an email target exports the log messages to specified email addresses.return [
// the "log" component must be loaded during bootstrapping time
'bootstrap' => ['log'],
// the "log" component process messages with timestamp. Set PHP timezone to create correct timestamp
'timeZone' => 'America/Los_Angeles',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\DbTarget',
'levels' => ['error', 'warning'],
],
[
'class' => 'yii\log\EmailTarget',
'levels' => ['error'],
'categories' => ['yii\db\*'],
'message' => [
'from' => ['log@example.com'],
'to' => ['admin@example.com', 'developer@example.com'],
'subject' => 'Database errors at example.com',
],
],
],
],
],
];
yii\log\Dispatcher::$targets property
:yii\db\
, and sends them in an email to both admin@example.com and developer@example.com.yii\log\DbTarget
: stores log messages in a database table.yii\log\EmailTarget
: sends log messages to pre-specified email addresses.yii\log\FileTarget
: saves log messages in files.yii\log\SyslogTarget
: saves log messages to syslog by calling the PHP function syslog()
.Yii | Yii2 |
---|---|
Yii requires PHP 5.2. | Yii 2.0 requires PHP 5.4.0 or higher, which makes use of the latest features of PHP. |
In Yii, prefix C was used, and the classes were in global namespaces. | In Yii2, prefix C is not used in namespaces. And classes based on the directory structure. |
Yii uses the On-event method, where custom event names are not allowed to use. | In Yii 2.0, any name can be used for the event with a handler attached to it, and event handling can be done using J-query. |
Yii uses PHP as the primary template language. | Yii 2.0 is equipped with PHP and two more template engines- TWIG and SMARTY. |
Yii.php
file.// $className is a fully qualified class name without the leading backslash
$classFile = Yii::getAlias('@' . str_replace('\\', '/', $className) . '.php');
foo\bar\MyClass,
the alias for the corresponding class file path would be @foo/bar/MyClass.php
. In order for this alias to be resolvable into a file path, either @foo
or @foo/bar
must be a root alias.@app
is a predefined alias, and a class name like app\components\MyClass
can be resolved into the class file AppBasePath/components/MyClass.php
, according to the algorithm just described.Yii::$classMap
, using :Yii::$classMap['foo\bar\MyClass'] = 'path/to/MyClass.php';
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
Yii.php
file and include it in your entry script.composer.json
file. Please refer to the Composer documentation for more details about specifying autoload.class Foo
{
public function __construct(Bar $bar)
{
}
}
$foo = $container->get('Foo');
// which is equivalent to the following:
$bar = new Bar;
$foo = new Foo($bar);
doSomething()
method in the following example:class MyClass extends \yii\base\Component
{
public function __construct(/*Some lightweight dependencies here*/, $config = [])
{
// ...
}
public function doSomething($param1, \my\heavy\Dependency $something)
{
// do something with $something
}
}
\my\heavy\Dependency
yourself or using yii\di\Container::invoke()
like the following:$obj = new MyClass(/*...*/);
Yii::$container->invoke([$obj, 'doSomething'], ['param1' => 42]); // $something will be provided by the DI container
use yii\base\BaseObject;
class Foo extends BaseObject
{
public $bar;
private $_qux;
public function getQux()
{
return $this->_qux;
}
public function setQux(Qux $qux)
{
$this->_qux = $qux;
}
}
$container->get('Foo', [], [
'bar' => $container->get('Bar'),
'qux' => $container->get('Qux'),
]);
yii\di\Container::get()
is called, the corresponding callable will be invoked. The callable is responsible to resolve the dependencies and inject them appropriately to the newly created objects. For example :$container->set('Foo', function ($container, $params, $config) {
$foo = new Foo(new Bar);
// ... other initializations ...
return $foo;
});
$foo = $container->get('Foo');
class FooBuilder
{
public static function build($container, $params, $config)
{
$foo = new Foo(new Bar);
// ... other initializations ...
return $foo;
}
}
$container->set('Foo', ['app\helper\FooBuilder', 'build']);
$foo = $container->get('Foo');
yii\di\Container::set()
to register dependencies. The registration requires a dependency name as well as a dependency definition. A dependency name can be a class name, an interface name, or an alias name; and a dependency definition can be a class name, a configuration array, or a PHP callable.$container = new \yii\di\Container;
// register a class name as is. This can be skipped.
$container->set('yii\db\Connection');
// register an interface
// When a class depends on the interface, the corresponding class
// will be instantiated as the dependent object
$container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
// register an alias name. You can use $container->get('foo')
// to create an instance of Connection
$container->set('foo', 'yii\db\Connection');
// register an alias with `Instance::of`
$container->set('bar', Instance::of('foo'));
// register a class with configuration. The configuration
// will be applied when the class is instantiated by get()
$container->set('yii\db\Connection', [
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
// register an alias name with class configuration
// In this case, a "class" or "__class" element is required to specify the class
$container->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
// register callable closure or array
// The callable will be executed each time when $container->get('db') is called
$container->set('db', function ($container, $params, $config) {
return new \yii\db\Connection($config);
});
$container->set('db', ['app\db\DbFactory', 'create']);
// register a component instance
// $container->get('pageCache') will return the same instance each time it is called
$container->set('pageCache', new FileCache);
set()
will generate an instance each time the dependency is needed. You can use yii\di\Container::setSingleton()
to register a dependency that only generates a single instance :$container->setSingleton('yii\db\Connection', [
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
get()
to either create or get object instance. The method takes a dependency name, which can be a class name, an interface name or an alias name. The dependency name may be registered via set()
or setSingleton()
. You may optionally provide a list of class constructor parameters and a configuration to configure the newly created object.// "db" is a previously registered alias name
$db = $container->get('db');
// equivalent to: $engine = new \app\components\SearchEngine($apiKey, $apiSecret, ['type' => 1]);
$engine = $container->get('app\components\SearchEngine', [$apiKey, $apiSecret], ['type' => 1]);
// equivalent to: $api = new \app\components\Api($host, $apiKey);
$api = $container->get('app\components\Api', ['host' => $host, 'apiKey' => $apiKey]);
get('userLister')
.namespace app\models;
use yii\base\BaseObject;
use yii\db\Connection;
use yii\di\Container;
interface UserFinderInterface
{
function findUser();
}
class UserFinder extends BaseObject implements UserFinderInterface
{
public $db;
public function __construct(Connection $db, $config = [])
{
$this->db = $db;
parent::__construct($config);
}
public function findUser()
{
}
}
class UserLister extends BaseObject
{
public $finder;
public function __construct(UserFinderInterface $finder, $config = [])
{
$this->finder = $finder;
parent::__construct($config);
}
}
$container = new Container;
$container->set('yii\db\Connection', [
'dsn' => '...',
]);
$container->set('app\models\UserFinderInterface', [
'class' => 'app\models\UserFinder',
]);
$container->set('userLister', 'app\models\UserLister');
$lister = $container->get('userLister');
// which is equivalent to:
$db = new \yii\db\Connection(['dsn' => '...']);
$finder = new UserFinder($db);
$lister = new UserLister($finder);
yii\di\ServiceLocator
or a child class.\Yii::$app
. The services it provides are called application components, such as the request, response, and urlManager components. You may configure these components, or even replace them with your own implementations, easily through functionality provided by the service locator.yii\di\ServiceLocator::set()
. The following code shows different ways of registering components :use yii\di\ServiceLocator;
use yii\caching\FileCache;
$locator = new ServiceLocator;
// register "cache" using a class name that can be used to create a component
$locator->set('cache', 'yii\caching\ApcCache');
// register "db" using a configuration array that can be used to create a component
$locator->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=demo',
'username' => 'root',
'password' => '',
]);
// register "search" using an anonymous function that builds a component
$locator->set('search', function () {
return new app\components\SolrService;
});
// register "pageCache" using a component
$locator->set('pageCache', new FileCache);
$cache = $locator->get('cache');
// or alternatively
$cache = $locator->cache;
$db = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
return [
// ...
'components' => [
// ...
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
],
// ...
];
Yii::$app->db
.mysql:host=localhost;dbname=mydatabase
sqlite:/path/to/database/file
pgsql:host=localhost;port=5432;dbname=mydatabase
cubrid:dbname=demodb;host=localhost;port=33000
sqlsrv:Server=localhost;Database=mydatabase
dblib:host=localhost;dbname=mydatabase
mssql:host=localhost;dbname=mydatabase
oci:dbname=//localhost:1521/mydatabase
yii\db\Connection::$driverName
property so that Yii can know the actual database type. For example : 'db' => [
'class' => 'yii\db\Connection',
'driverName' => 'mysql',
'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test',
'username' => 'root',
'password' => '',
],
yii\db\Command
with a plain SQL query;yii\db\Command
.// 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
$posts = Yii::$app->db->createCommand('SELECT * FROM post')
->queryAll();
// return a single row (the first row)
// false is returned if the query has no result
$post = Yii::$app->db->createCommand('SELECT * FROM post WHERE id=1')
->queryOne();
// return a single column (the first column)
// an empty array is returned if the query returned no results
$titles = Yii::$app->db->createCommand('SELECT title FROM post')
->queryColumn();
// return a scalar value
// false is returned if the query has no result
$count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM post')
->queryScalar();
$formatter = \Yii::$app->formatter;
// output: January 1, 2014
echo $formatter->asDate('2014-01-01', 'long');
// output: 12.50%
echo $formatter->asPercent(0.125, 2);
// output: <a href="mailto:cebe@example.com">cebe@example.com</a>
echo $formatter->asEmail('cebe@example.com');
// output: Yes
echo $formatter->asBoolean(true);
// it also handles display of null values:
// output: (not set)
echo $formatter->asDate(null);
yii\data\DataProviderInterface
. It mainly supports retrieving paginated and sorted data. It is usually used to work with data widgets so that end users can interactively paginate and sort data.yii\data\ActiveDataProvider
: uses yii\db\Query or yii\db\ActiveQuery
to query data from databases and return them in terms of arrays or Active Record instances.yii\data\SqlDataProvider
: executes a SQL statement and returns database data as arrays.yii\data\ArrayDataProvider
: takes a big array and returns a slice of it based on the paginating and sorting specifications.// create the data provider by configuring its pagination and sort properties
$provider = new XyzDataProvider([
'pagination' => [...],
'sort' => [...],
]);
// retrieves paginated and sorted data
$models = $provider->getModels();
// get the number of data items in the current page
$count = $provider->getCount();
// get the total number of data items across all pages
$totalCount = $provider->getTotalCount();
yii\data\Pagination
and yii\data\Sort
, respectively. You may also configure them to be false to disable pagination and/or sorting features.yii\grid\GridView
, have a property named dataProvider which can take a data provider instance and display the data it provides. For example :echo yii\grid\GridView::widget([
'dataProvider' => $dataProvider,
]);
$key = Yii::$app->getSecurity()->generateRandomString();
// $data and $secretKey are obtained from the form
$encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);
// store $encryptedData to database
Subsequently when user wants to read the data:
// $secretKey is obtained from user input, $encryptedData is from the database
$data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
It's also possible to use key instead of password via yii\base\Security::encryptByKey()
and yii\base\Security::decryptByKey()
.
// $secretKey our application or user secret, $genuineData obtained from a reliable source
$data = Yii::$app->getSecurity()->hashData($genuineData, $secretKey);
Checks if the data integrity has been compromised
// $secretKey our application or user secret, $data obtained from an unreliable source
$data = Yii::$app->getSecurity()->validateData($data, $secretKey);
// try retrieving $data from cache
$data = $cache->get($key);
if ($data === false) {
// $data is not found in cache, calculate it from scratch
$data = $this->calculateSomething();
// store $data in cache so that it can be retrieved next time
$cache->set($key, $data);
}
// $data is available here
getOrSet()
method that simplifies code for data getting, calculating and storing. The following code does exactly the same as the previous example:$data = $cache->getOrSet($key, function () {
return $this->calculateSomething();
});
$user_id = 42;
$data = $cache->getOrSet($key, function () use ($user_id) {
return $this->calculateSomething($user_id);
});
if ($this->beginCache($id)) {
// ... generate content here ...
$this->endCache();
}
beginCache()
and endCache()
calls. If the content is found in the cache, beginCache()
will render the cached content and return false, thus skip the content generation logic. Otherwise, your content generation logic will be called, and when endCache()
is called, the generated content will be captured and stored in the cache.yii\filters\HttpCache
as a filter for controller actions whose rendering result may be cached on the client-side. HttpCache only works for GET and HEAD requests. It can handle three kinds of cache-related HTTP headers for these requests:/**
* @param Action $action the action object that is being handled currently
* @param array $params the value of the "params" property
* @return int a UNIX timestamp representing the page modification time
*/
function ($action, $params)
public function behaviors()
{
return [
[
'class' => 'yii\filters\HttpCache',
'only' => ['index'],
'lastModified' => function ($action, $params) {
$q = new \yii\db\Query();
return $q->from('post')->max('updated_at');
},
],
];
}
yii\filters\HttpCache::$etagSeed
property to enable sending the ETag header. The property should be a PHP callable returning a seed for generating the ETag hash. The signature of the PHP callable should be as follows,/**
* @param Action $action the action object that is being handled currently
* @param array $params the value of the "params" property
* @return string a string used as the seed for generating an ETag hash
*/
function ($action, $params)
public function behaviors()
{
return [
[
'class' => 'yii\filters\HttpCache',
'only' => ['view'],
'etagSeed' => function ($action, $params) {
$post = $this->findModel(\Yii::$app->request->get('id'));
return serialize([$post->title, $post->content]);
},
],
];
}
yii\filters\HttpCache::$cacheControlHeader
property with the header value. By default, the following header will be sent :Cache-Control: public, max-age=3600
use yii\helpers\Html;
echo Html::encode('Test > test');
yii\helpers\ArrayHelper
), you should create a new class extending from the helpers corresponding base class (e.g. yii\helpers\BaseArrayHelper)
and name your class the same as the corresponding concrete class (e.g. yii\helpers\ArrayHelper
), including its namespace. This class will then be set up to replace the original implementation of the framework.merge()
method of the yii\helpers\ArrayHelper
class :<?php
namespace yii\helpers;
class ArrayHelper extends BaseArrayHelper
{
public static function merge($a, $b)
{
// your custom implementation
}
}
ArrayHelper.php
. The file can be in any directory, for example @app/components
.Yii::$classMap['yii\helpers\ArrayHelper'] = '@app/components/ArrayHelper.php';
yii\test\Fixture
or its child class. For example, you may use UserFixture to make sure the user DB table contains a fixed set of data. You load one or multiple fixture objects before running a test and unload them when finishing.yii\test\Fixture::$depends
property. When a fixture is being loaded, the fixtures it depends on will be automatically loaded BEFORE the fixture; and when the fixture is being unloaded, the dependent fixtures will be unloaded AFTER the fixture.yii\test\Fixture
or yii\test\ActiveFixture
. The former is best suited for general purpose fixtures, while the latter has enhanced features specifically designed to work with database and ActiveRecord.<?php
namespace app\tests\fixtures;
use yii\test\ActiveFixture;
class UserFixture extends ActiveFixture
{
public $modelClass = 'app\models\User';
}