Commit ec52f164 authored by tufengqi's avatar tufengqi

init yii2

parent a63a23be
{
"directory" : "vendor/bower-asset"
}
# phpstorm project files
.idea
# netbeans project files
nbproject
# zend studio for eclipse project files
.buildpath
.project
.settings
# windows thumbnail cache
Thumbs.db
# composer itself is not needed
composer.phar
# Mac DS_Store Files
/build
.DS_Store
# phpunit itself is not needed
phpunit.phar
# local phpunit config
/phpunit.xml
tests/_output/*
tests/_support/_generated
#vagrant folder
/.vagrant
\ No newline at end of file
.idea
/composer.lock
.vscode
\ No newline at end of file
{
"name": "yii2_33cn",
"name": "yiisoft/yii2-app-basic",
"description": "Yii 2 Basic Project Template",
"keywords": ["yii2", "framework", "basic", "project template"],
"homepage": "http://www.yiiframework.com/",
......
......@@ -14,7 +14,7 @@ $config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '5C7G_15_s1b0A1tDEa0Ki8MmEOomIn_R',
'cookieValidationKey' => '14hhexVTxr4OC4BBrLE4rJfIbodU7LVz',
],
'cache' => [
'class' => 'yii\caching\FileCache',
......
......@@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit2c27aae683e1f1fb7dc2fdde03e9f332::getLoader();
return ComposerAutoloaderInitb7f6fff58df4cda48239fd6d0378e5f0::getLoader();
......@@ -7,6 +7,7 @@ $baseDir = dirname($vendorDir);
return array(
'yii\\swiftmailer\\' => array($vendorDir . '/yiisoft/yii2-swiftmailer'),
'yii\\redis\\' => array($vendorDir . '/yiisoft/yii2-redis/src'),
'yii\\gii\\' => array($vendorDir . '/yiisoft/yii2-gii/src'),
'yii\\faker\\' => array($vendorDir . '/yiisoft/yii2-faker'),
'yii\\debug\\' => array($vendorDir . '/yiisoft/yii2-debug'),
......
......@@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit2c27aae683e1f1fb7dc2fdde03e9f332
class ComposerAutoloaderInitb7f6fff58df4cda48239fd6d0378e5f0
{
private static $loader;
......@@ -19,15 +19,15 @@ class ComposerAutoloaderInit2c27aae683e1f1fb7dc2fdde03e9f332
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit2c27aae683e1f1fb7dc2fdde03e9f332', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInitb7f6fff58df4cda48239fd6d0378e5f0', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit2c27aae683e1f1fb7dc2fdde03e9f332', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInitb7f6fff58df4cda48239fd6d0378e5f0', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
......@@ -48,19 +48,19 @@ class ComposerAutoloaderInit2c27aae683e1f1fb7dc2fdde03e9f332
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332::$files;
$includeFiles = Composer\Autoload\ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire2c27aae683e1f1fb7dc2fdde03e9f332($fileIdentifier, $file);
composerRequireb7f6fff58df4cda48239fd6d0378e5f0($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire2c27aae683e1f1fb7dc2fdde03e9f332($fileIdentifier, $file)
function composerRequireb7f6fff58df4cda48239fd6d0378e5f0($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
......
......@@ -4,7 +4,7 @@
namespace Composer\Autoload;
class ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332
class ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0
{
public static $files = array (
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
......@@ -20,6 +20,7 @@ class ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332
'y' =>
array (
'yii\\swiftmailer\\' => 16,
'yii\\redis\\' => 10,
'yii\\gii\\' => 8,
'yii\\faker\\' => 10,
'yii\\debug\\' => 10,
......@@ -81,6 +82,10 @@ class ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-swiftmailer',
),
'yii\\redis\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-redis/src',
),
'yii\\gii\\' =>
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2-gii/src',
......@@ -767,10 +772,10 @@ class ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332::$prefixesPsr0;
$loader->classMap = ComposerStaticInit2c27aae683e1f1fb7dc2fdde03e9f332::$classMap;
$loader->prefixLengthsPsr4 = ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0::$prefixesPsr0;
$loader->classMap = ComposerStaticInitb7f6fff58df4cda48239fd6d0378e5f0::$classMap;
}, null, ClassLoader::class);
}
......
......@@ -2394,7 +2394,7 @@
"dev-master": "4.1-dev"
}
},
"installation-source": "source",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Symfony\\Component\\CssSelector\\": ""
......@@ -2801,7 +2801,7 @@
},
"time": "2017-04-07T12:08:54+00:00",
"type": "library",
"installation-source": "source",
"installation-source": "dist",
"autoload": {
"classmap": [
"src/"
......@@ -2849,7 +2849,7 @@
"dev-master": "1.3-dev"
}
},
"installation-source": "source",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Webmozart\\Assert\\": "src/"
......@@ -3246,6 +3246,59 @@
]
},
{
"name": "yiisoft/yii2-redis",
"version": "2.0.8",
"version_normalized": "2.0.8.0",
"source": {
"type": "git",
"url": "https://github.com/yiisoft/yii2-redis.git",
"reference": "ffe6bff8dc6be4bb84c9495cd3ef7ef1161c1314"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/yiisoft/yii2-redis/zipball/ffe6bff8dc6be4bb84c9495cd3ef7ef1161c1314",
"reference": "ffe6bff8dc6be4bb84c9495cd3ef7ef1161c1314",
"shasum": ""
},
"require": {
"yiisoft/yii2": "~2.0.14"
},
"require-dev": {
"yiisoft/yii2-dev": "~2.0.14"
},
"time": "2018-03-20T11:01:04+00:00",
"type": "yii2-extension",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"yii\\redis\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Carsten Brandt",
"email": "mail@cebe.cc"
}
],
"description": "Redis Cache, Session and ActiveRecord for the Yii framework",
"keywords": [
"active-record",
"cache",
"redis",
"session",
"yii2"
]
},
{
"name": "yiisoft/yii2-swiftmailer",
"version": "2.0.7",
"version_normalized": "2.0.7.0",
......
/tests export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/appveyor.yml export-ignore
/phpunit.xml.dist export-ignore
language: php
sudo: false
branches:
only:
- master
cache:
directories:
- $HOME/.composer/cache/files
matrix:
include:
- php: 5.3
dist: precise
- php: 7.1
env: COVERAGE=yes
- php: 5.4
- php: 5.5
- php: 5.6
- php: 7.0
- php: hhvm
- php: nightly
- php: 7.1
env: COMPOSER_FLAGS='--prefer-lowest --prefer-stable'
- php: 7.2
allow_failures:
- php: hhvm
- php: nightly
fast_finish: true
before_install:
- if [[ $TRAVIS_PHP_VERSION != hhvm && $COVERAGE != yes ]]; then phpenv config-rm xdebug.ini; fi;
- if [[ $TRAVIS_REPO_SLUG = webmozart/assert ]]; then cp .composer-auth.json ~/.composer/auth.json; fi;
- composer self-update
install: composer update $COMPOSER_FLAGS --prefer-dist --no-interaction
script: if [[ $COVERAGE = yes ]]; then vendor/bin/phpunit --verbose --coverage-clover=coverage.clover; else vendor/bin/phpunit --verbose; fi
after_script: if [[ $COVERAGE = yes ]]; then wget https://scrutinizer-ci.com/ocular.phar && php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi
build: false
platform: x86
clone_folder: c:\projects\webmozart\assert
branches:
only:
- master
cache:
- c:\php -> appveyor.yml
init:
- SET PATH=c:\php;%PATH%
- SET COMPOSER_NO_INTERACTION=1
- SET PHP=1
install:
- IF EXIST c:\php (SET PHP=0) ELSE (mkdir c:\php)
- cd c:\php
- IF %PHP%==1 appveyor DownloadFile http://windows.php.net/downloads/releases/archives/php-7.0.0-nts-Win32-VC14-x86.zip
- IF %PHP%==1 7z x php-7.0.0-nts-Win32-VC14-x86.zip -y >nul
- IF %PHP%==1 del /Q *.zip
- IF %PHP%==1 echo @php %%~dp0composer.phar %%* > composer.bat
- IF %PHP%==1 copy /Y php.ini-development php.ini
- IF %PHP%==1 echo max_execution_time=1200 >> php.ini
- IF %PHP%==1 echo date.timezone="UTC" >> php.ini
- IF %PHP%==1 echo extension_dir=ext >> php.ini
- IF %PHP%==1 echo extension=php_curl.dll >> php.ini
- IF %PHP%==1 echo extension=php_openssl.dll >> php.ini
- IF %PHP%==1 echo extension=php_mbstring.dll >> php.ini
- IF %PHP%==1 echo extension=php_fileinfo.dll >> php.ini
- appveyor DownloadFile https://getcomposer.org/composer.phar
- cd c:\projects\webmozart\assert
- mkdir %APPDATA%\Composer
- IF %APPVEYOR_REPO_NAME%==webmozart/assert copy /Y .composer-auth.json %APPDATA%\Composer\auth.json
- composer update --prefer-dist --no-progress --ansi
test_script:
- cd c:\projects\webmozart\assert
- vendor\bin\phpunit.bat --verbose
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="Webmozart Assert Test Suite">
<directory suffix="Test.php">./tests/</directory>
</testsuite>
</testsuites>
<!-- Whitelist for code coverage -->
<filter>
<whitelist>
<directory suffix=".php">./src/</directory>
</whitelist>
</filter>
</phpunit>
This diff is collapsed.
......@@ -48,4 +48,13 @@ return array (
'@yii/faker' => $vendorDir . '/yiisoft/yii2-faker',
),
),
'yiisoft/yii2-redis' =>
array (
'name' => 'yiisoft/yii2-redis',
'version' => '2.0.8.0',
'alias' =>
array (
'@yii/redis' => $vendorDir . '/yiisoft/yii2-redis/src',
),
),
);
Yii Framework 2 redis extension Change Log
==========================================
2.0.8 March 20, 2018
--------------------
- Bug #141: Calling ActiveQuery::indexBy() had no effect since Yii 2.0.14 (cebe)
- Bug: (CVE-2018-8073): Fix possible remote code execution when improperly filtered user input is passed to `ActiveRecord::findOne()` and `::findAll()` (cebe)
- Enh #66: Cache component can be configured to read / get from replicas (ryusoft)
2.0.7 December 11, 2017
-----------------------
- Bug #114: Fixed ActiveQuery `not between` and `not` conditions which where not working correctly (cebe, ak1987)
- Bug #123: Fixed ActiveQuery to work with negative limit values, which are used in ActiveDataProvider for the count query (cebe)
- Enh #9: Added orderBy support to redis ActiveQuery and LuaScriptBuilder (valinurovam)
- Enh #91: Added option to retry connection after failing to communicate with redis server on stale socket (cebe)
- Enh #106: Improved handling of connection errors and introduced `yii\redis\SocketException` for these (cebe)
- Chg #127: Added PHP 7.2 compatibility (brandonkelly)
2.0.6 April 05, 2017
--------------------
- Bug #44: Remove quotes from numeric parts of composite key to avoid problem with different hashes for the same record (uniserpl)
- Bug #67: Fixed regression from 2.0.5, reconnecting a closed connection fails (cebe)
- Bug #82: Fixed session object destruction failure when key expires (juffin-halli, samdark)
- Bug #93: Fixed `yii\redis\ActiveRecord::deleteAll()` with condition (samdark)
- Bug #104: Fixed execution of two-word commands (cebe,branimir93)
- Enh #53: Added `Mutex` that implements a Redis based mutex (turboezh, sergeymakinen)
- Enh #81: Allow setting `Connection::$database` to `null` to avoid sending a `SELECT` command after connection (cebe)
- Enh #89: Added support for `\yii\db\QueryInterface::emulateExecution()` (samdark)
- Enh #103: Added missing commands and `@method` documentation for redis commands (cebe)
- Enh: Optimized find by PK for relational queries and IN condition (cebe, andruha)
2.0.5 March 17, 2016
--------------------
- Bug #22: Fixed string escaping issue in LuaScriptBuilder (vistart)
- Bug #37: Fixed detection of open socket (mirocow)
- Bug #46: Fixed bug to execute session_regenerate_id in PHP 7.0 (githubjeka)
- Enh #31: Added `Connection::$socketClientFlags` property for connection flags to be passed to `stream_socket_client()` (hugh-lee)
- Chg #14: Added missing `BLPOP` command to `$redisCommands` (samdark)
- Chg #61: Added missing `GEO*` commands to `$redisCommands` (leadermt)
2.0.4 May 10, 2015
------------------
- Enh #8: Auto increment value was not updated when a primary key was explicitly set (cebe, andruha)
2.0.3 March 01, 2015
--------------------
- no changes in this release.
2.0.2 January 11, 2015
----------------------
- Bug #6547: Fixed redis connection to deal with large data in combination with `mget()` (pyurin)
2.0.1 December 07, 2014
-----------------------
- Bug #4745: value of simple string returns was ignored by redis client and `true` is returned instead, now only `OK` will result in a `true` while all other values are returned as is (cebe)
- Enh #3714: Added support for connecting to redis server using a unix socket (savvot, robregonm)
2.0.0 October 12, 2014
----------------------
- no changes in this release.
2.0.0-rc September 27, 2014
---------------------------
- Bug #1311: Fixed storage and finding of `null` and boolean values (samdark, cebe)
- Enh #3520: Added `unlinkAll()`-method to active record to remove all records of a model relation (NmDimas, samdark, cebe)
- Enh #4048: Added `init` event to `ActiveQuery` classes (qiangxue)
- Enh #4086: changedAttributes of afterSave Event now contain old values (dizews)
2.0.0-beta April 13, 2014
-------------------------
- Bug #1993: afterFind event in AR is now called after relations have been populated (cebe, creocoder)
- Enh #1773: keyPrefix property of Session and Cache is not restricted to alnum characters anymore (cebe)
- Enh #2002: Added filterWhere() method to yii\redis\ActiveQuery to allow easy addition of search filter conditions by ignoring empty search fields (samdark, cebe)
- Enh #2892: ActiveRecord dirty attributes are now reset after call to `afterSave()` so information about changed attributes is available in `afterSave`-event (cebe)
- Chg #2281: Renamed `ActiveRecord::create()` to `populateRecord()` and changed signature. This method will not call instantiate() anymore (cebe)
- Chg #2146: Removed `ActiveRelation` class and moved the functionality to `ActiveQuery`.
All relational queries are now directly served by `ActiveQuery` allowing to use
custom scopes in relations (cebe)
2.0.0-alpha, December 1, 2013
-----------------------------
- Initial release.
The Yii framework is free software. It is released under the terms of
the following BSD License.
Copyright © 2008 by Yii Software LLC (http://www.yiisoft.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Yii Software LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
# default versions to test against
# these can be overridden by setting the environment variables in the shell
REDIS_VERSION=3.0.0
PHP_VERSION=php-5.6.8
YII_VERSION=dev-master
# ensure all the configuration variables above are in environment of the shell commands below
export
help:
@echo "make test - run phpunit tests using a docker environment"
@echo "make clean - stop docker and remove container"
test: docker adjust-config
#composer require "yiisoft/yii2:${YII_VERSION}" --prefer-dist
#composer install --prefer-dist
docker run --rm=true -v $(shell pwd):/opt/test --link $(shell cat tests/dockerids/redis):redis yiitest/php:${PHP_VERSION} phpunit --verbose --color
adjust-config:
echo "<?php \$$config['databases']['redis']['port'] = 6379; \$$config['databases']['redis']['hostname'] = 'redis';" > tests/data/config.local.php
docker: build-docker
docker run -d -P yiitest/redis:${REDIS_VERSION} > tests/dockerids/redis
build-docker:
test -d tests/docker || git clone https://github.com/cebe/jenkins-test-docker tests/docker
cd tests/docker && git checkout -- . && git pull
cd tests/docker/php && sh build.sh
cd tests/docker/redis && sh build.sh
mkdir -p tests/dockerids
clean:
docker stop $(shell cat tests/dockerids/redis)
docker rm $(shell cat tests/dockerids/redis)
rm tests/dockerids/redis
<p align="center">
<a href="http://redis.io/" target="_blank" rel="external">
<img src="http://download.redis.io/logocontest/82.png" height="100px">
</a>
<h1 align="center">Redis Cache, Session and ActiveRecord for Yii 2</h1>
<br>
</p>
This extension provides the [redis](http://redis.io/) key-value store support for the [Yii framework 2.0](http://www.yiiframework.com).
It includes a `Cache` and `Session` storage handler and implements the `ActiveRecord` pattern that allows
you to store active records in redis.
For license information check the [LICENSE](LICENSE.md)-file.
Documentation is at [docs/guide/README.md](docs/guide/README.md).
[![Latest Stable Version](https://poser.pugx.org/yiisoft/yii2-redis/v/stable.png)](https://packagist.org/packages/yiisoft/yii2-redis)
[![Total Downloads](https://poser.pugx.org/yiisoft/yii2-redis/downloads.png)](https://packagist.org/packages/yiisoft/yii2-redis)
[![Build Status](https://travis-ci.org/yiisoft/yii2-redis.svg?branch=master)](https://travis-ci.org/yiisoft/yii2-redis)
Requirements
------------
At least redis version 2.6.12 is required for all components to work properly.
Installation
------------
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```
php composer.phar require --prefer-dist yiisoft/yii2-redis
```
or add
```json
"yiisoft/yii2-redis": "~2.0.0"
```
to the require section of your composer.json.
Configuration
-------------
To use this extension, you have to configure the Connection class in your application configuration:
```php
return [
//....
'components' => [
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
],
]
];
```
{
"name": "yiisoft/yii2-redis",
"description": "Redis Cache, Session and ActiveRecord for the Yii framework",
"keywords": ["yii2", "redis", "active-record", "cache", "session"],
"type": "yii2-extension",
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/yiisoft/yii2-redis/issues",
"forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2-redis"
},
"authors": [
{
"name": "Carsten Brandt",
"email": "mail@cebe.cc"
}
],
"require": {
"yiisoft/yii2": "~2.0.14"
},
"autoload": {
"psr-4": { "yii\\redis\\": "src" }
},
"autoload-dev": {
"psr-4": { "yiiunit\\extensions\\redis\\": "tests/"}
},
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
],
"require-dev": {
"yiisoft/yii2-dev": "~2.0.14"
}
}
This diff is collapsed.
This diff is collapsed.
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\redis;
use Yii;
use yii\di\Instance;
/**
* Redis Cache implements a cache application component based on [redis](http://redis.io/) key-value store.
*
* Redis Cache requires redis version 2.6.12 or higher to work properly.
*
* It needs to be configured with a redis [[Connection]] that is also configured as an application component.
* By default it will use the `redis` application component.
*
* See [[Cache]] manual for common cache operations that redis Cache supports.
*
* Unlike the [[Cache]], redis Cache allows the expire parameter of [[set]], [[add]], [[mset]] and [[madd]] to
* be a floating point number, so you may specify the time in milliseconds (e.g. 0.1 will be 100 milliseconds).
*
* To use redis Cache as the cache application component, configure the application as follows,
*
* ~~~
* [
* 'components' => [
* 'cache' => [
* 'class' => 'yii\redis\Cache',
* 'redis' => [
* 'hostname' => 'localhost',
* 'port' => 6379,
* 'database' => 0,
* ]
* ],
* ],
* ]
* ~~~
*
* Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
*
* ~~~
* [
* 'components' => [
* 'cache' => [
* 'class' => 'yii\redis\Cache',
* // 'redis' => 'redis' // id of the connection application component
* ],
* ],
* ]
* ~~~
*
* If you have multiple redis replicas (e.g. AWS ElasticCache Redis) you can configure the cache to
* send read operations to the replicas. If no replicas are configured, all operations will be performed on the
* master connection configured via the [[redis]] property.
*
* ~~~
* [
* 'components' => [
* 'cache' => [
* 'class' => 'yii\redis\Cache',
* 'enableReplicas' => true,
* 'replicas' => [
* // config for replica redis connections, (default class will be yii\redis\Connection if not provided)
* // you can optionally put in master as hostname as well, as all GET operation will use replicas
* 'redis',//id of Redis [[Connection]] Component
* ['hostname' => 'redis-slave-002.xyz.0001.apse1.cache.amazonaws.com'],
* ['hostname' => 'redis-slave-003.xyz.0001.apse1.cache.amazonaws.com'],
* ],
* ],
* ],
* ]
* ~~~
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class Cache extends \yii\caching\Cache
{
/**
* @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
* This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
* redis connection as an application component.
* After the Cache object is created, if you want to change this property, you should only assign it
* with a Redis [[Connection]] object.
*/
public $redis = 'redis';
/**
* @var bool whether to enable read / get from redis replicas.
* @since 2.0.8
* @see $replicas
*/
public $enableReplicas = false;
/**
* @var array the Redis [[Connection]] configurations for redis replicas.
* Each entry is a class configuration, which will be used to instantiate a replica connection.
* The default class is [[Connection|yii\redis\Connection]]. You should at least provide a hostname.
*
* Configuration example:
*
* ```php
* 'replicas' => [
* 'redis',
* ['hostname' => 'redis-slave-002.xyz.0001.apse1.cache.amazonaws.com'],
* ['hostname' => 'redis-slave-003.xyz.0001.apse1.cache.amazonaws.com'],
* ],
* ```
*
* @since 2.0.8
* @see $enableReplicas
*/
public $replicas = [];
/**
* @var Connection currently active connection.
*/
private $_replica;
/**
* Initializes the redis Cache component.
* This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
* @throws \yii\base\InvalidConfigException if [[redis]] is invalid.
*/
public function init()
{
parent::init();
$this->redis = Instance::ensure($this->redis, Connection::className());
}
/**
* Checks whether a specified key exists in the cache.
* This can be faster than getting the value from the cache if the data is big.
* Note that this method does not check whether the dependency associated
* with the cached data, if there is any, has changed. So a call to [[get]]
* may return false while exists returns true.
* @param mixed $key a key identifying the cached value. This can be a simple string or
* a complex data structure consisting of factors representing the key.
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
*/
public function exists($key)
{
return (bool) $this->redis->executeCommand('EXISTS', [$this->buildKey($key)]);
}
/**
* @inheritdoc
*/
protected function getValue($key)
{
return $this->getReplica()->executeCommand('GET', [$key]);
}
/**
* @inheritdoc
*/
protected function getValues($keys)
{
$response = $this->getReplica()->executeCommand('MGET', $keys);
$result = [];
$i = 0;
foreach ($keys as $key) {
$result[$key] = $response[$i++];
}
return $result;
}
/**
* @inheritdoc
*/
protected function setValue($key, $value, $expire)
{
if ($expire == 0) {
return (bool) $this->redis->executeCommand('SET', [$key, $value]);
} else {
$expire = (int) ($expire * 1000);
return (bool) $this->redis->executeCommand('SET', [$key, $value, 'PX', $expire]);
}
}
/**
* @inheritdoc
*/
protected function setValues($data, $expire)
{
$args = [];
foreach ($data as $key => $value) {
$args[] = $key;
$args[] = $value;
}
$failedKeys = [];
if ($expire == 0) {
$this->redis->executeCommand('MSET', $args);
} else {
$expire = (int) ($expire * 1000);
$this->redis->executeCommand('MULTI');
$this->redis->executeCommand('MSET', $args);
$index = [];
foreach ($data as $key => $value) {
$this->redis->executeCommand('PEXPIRE', [$key, $expire]);
$index[] = $key;
}
$result = $this->redis->executeCommand('EXEC');
array_shift($result);
foreach ($result as $i => $r) {
if ($r != 1) {
$failedKeys[] = $index[$i];
}
}
}
return $failedKeys;
}
/**
* @inheritdoc
*/
protected function addValue($key, $value, $expire)
{
if ($expire == 0) {
return (bool) $this->redis->executeCommand('SET', [$key, $value, 'NX']);
} else {
$expire = (int) ($expire * 1000);
return (bool) $this->redis->executeCommand('SET', [$key, $value, 'PX', $expire, 'NX']);
}
}
/**
* @inheritdoc
*/
protected function deleteValue($key)
{
return (bool) $this->redis->executeCommand('DEL', [$key]);
}
/**
* @inheritdoc
*/
protected function flushValues()
{
return $this->redis->executeCommand('FLUSHDB');
}
/**
* It will return the current Replica Redis [[Connection]], and fall back to default [[redis]] [[Connection]]
* defined in this instance. Only used in getValue() and getValues().
* @since 2.0.8
* @return array|string|Connection
* @throws \yii\base\InvalidConfigException
*/
protected function getReplica()
{
if ($this->enableReplicas === false) {
return $this->redis;
}
if ($this->_replica !== null) {
return $this->_replica;
}
if (empty($this->replicas)) {
return $this->_replica = $this->redis;
}
$replicas = $this->replicas;
shuffle($replicas);
$config = array_shift($replicas);
$this->_replica = Instance::ensure($config, Connection::className());
return $this->_replica;
}
}
This diff is collapsed.
This diff is collapsed.
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\redis;
use Yii;
use yii\base\InvalidConfigException;
use yii\di\Instance;
/**
* Redis Mutex implements a mutex component using [redis](http://redis.io/) as the storage medium.
*
* Redis Mutex requires redis version 2.6.12 or higher to work properly.
*
* It needs to be configured with a redis [[Connection]] that is also configured as an application component.
* By default it will use the `redis` application component.
*
* To use redis Mutex as the application component, configure the application as follows:
*
* ```php
* [
* 'components' => [
* 'mutex' => [
* 'class' => 'yii\redis\Mutex',
* 'redis' => [
* 'hostname' => 'localhost',
* 'port' => 6379,
* 'database' => 0,
* ]
* ],
* ],
* ]
* ```
*
* Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
*
* ```php
* [
* 'components' => [
* 'mutex' => [
* 'class' => 'yii\redis\Mutex',
* // 'redis' => 'redis' // id of the connection application component
* ],
* ],
* ]
* ```
*
* @see \yii\mutex\Mutex
* @see http://redis.io/topics/distlock
*
* @author Sergey Makinen <sergey@makinen.ru>
* @author Alexander Zhuravlev <axelhex@gmail.com>
* @since 2.0.6
*/
class Mutex extends \yii\mutex\Mutex
{
/**
* @var int the number of seconds in which the lock will be auto released.
*/
public $expire = 30;
/**
* @var string a string prefixed to every cache key so that it is unique. If not set,
* it will use a prefix generated from [[Application::id]]. You may set this property to be an empty string
* if you don't want to use key prefix. It is recommended that you explicitly set this property to some
* static value if the cached data needs to be shared among multiple applications.
*/
public $keyPrefix;
/**
* @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
* This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
* redis connection as an application component.
* After the Mutex object is created, if you want to change this property, you should only assign it
* with a Redis [[Connection]] object.
*/
public $redis = 'redis';
/**
* @var array Redis lock values. Used to be safe that only a lock owner can release it.
*/
private $_lockValues = [];
/**
* Initializes the redis Mutex component.
* This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
* @throws InvalidConfigException if [[redis]] is invalid.
*/
public function init()
{
parent::init();
$this->redis = Instance::ensure($this->redis, Connection::className());
if ($this->keyPrefix === null) {
$this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
}
}
/**
* Acquires a lock by name.
* @param string $name of the lock to be acquired. Must be unique.
* @param int $timeout time (in seconds) to wait for lock to be released. Defaults to `0` meaning that method will return
* false immediately in case lock was already acquired.
* @return bool lock acquiring result.
*/
protected function acquireLock($name, $timeout = 0)
{
$key = $this->calculateKey($name);
$value = Yii::$app->security->generateRandomString(20);
$waitTime = 0;
while (!$this->redis->executeCommand('SET', [$key, $value, 'NX', 'PX', (int) ($this->expire * 1000)])) {
$waitTime++;
if ($waitTime > $timeout) {
return false;
}
sleep(1);
}
$this->_lockValues[$name] = $value;
return true;
}
/**
* Releases acquired lock. This method will return `false` in case the lock was not found or Redis command failed.
* @param string $name of the lock to be released. This lock must already exist.
* @return bool lock release result: `false` in case named lock was not found or Redis command failed.
*/
protected function releaseLock($name)
{
static $releaseLuaScript = <<<LUA
if redis.call("GET",KEYS[1])==ARGV[1] then
return redis.call("DEL",KEYS[1])
else
return 0
end
LUA;
if (!isset($this->_lockValues[$name]) || !$this->redis->executeCommand('EVAL', [
$releaseLuaScript,
1,
$this->calculateKey($name),
$this->_lockValues[$name]
])) {
return false;
} else {
unset($this->_lockValues[$name]);
return true;
}
}
/**
* Generates a unique key used for storing the mutex in Redis.
* @param string $name mutex name.
* @return string a safe cache key associated with the mutex name.
*/
protected function calculateKey($name)
{
return $this->keyPrefix . md5(json_encode([__CLASS__, $name]));
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\redis;
use Yii;
use yii\base\InvalidConfigException;
/**
* Redis Session implements a session component using [redis](http://redis.io/) as the storage medium.
*
* Redis Session requires redis version 2.6.12 or higher to work properly.
*
* It needs to be configured with a redis [[Connection]] that is also configured as an application component.
* By default it will use the `redis` application component.
*
* To use redis Session as the session application component, configure the application as follows,
*
* ~~~
* [
* 'components' => [
* 'session' => [
* 'class' => 'yii\redis\Session',
* 'redis' => [
* 'hostname' => 'localhost',
* 'port' => 6379,
* 'database' => 0,
* ]
* ],
* ],
* ]
* ~~~
*
* Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
*
* ~~~
* [
* 'components' => [
* 'session' => [
* 'class' => 'yii\redis\Session',
* // 'redis' => 'redis' // id of the connection application component
* ],
* ],
* ]
* ~~~
*
* @property bool $useCustomStorage Whether to use custom storage. This property is read-only.
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class Session extends \yii\web\Session
{
/**
* @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
* This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
* redis connection as an application component.
* After the Session object is created, if you want to change this property, you should only assign it
* with a Redis [[Connection]] object.
*/
public $redis = 'redis';
/**
* @var string a string prefixed to every cache key so that it is unique. If not set,
* it will use a prefix generated from [[Application::id]]. You may set this property to be an empty string
* if you don't want to use key prefix. It is recommended that you explicitly set this property to some
* static value if the cached data needs to be shared among multiple applications.
*/
public $keyPrefix;
/**
* Initializes the redis Session component.
* This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
* @throws InvalidConfigException if [[redis]] is invalid.
*/
public function init()
{
if (is_string($this->redis)) {
$this->redis = Yii::$app->get($this->redis);
} elseif (is_array($this->redis)) {
if (!isset($this->redis['class'])) {
$this->redis['class'] = Connection::className();
}
$this->redis = Yii::createObject($this->redis);
}
if (!$this->redis instanceof Connection) {
throw new InvalidConfigException("Session::redis must be either a Redis connection instance or the application component ID of a Redis connection.");
}
if ($this->keyPrefix === null) {
$this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
}
parent::init();
}
/**
* Returns a value indicating whether to use custom session storage.
* This method overrides the parent implementation and always returns true.
* @return bool whether to use custom storage.
*/
public function getUseCustomStorage()
{
return true;
}
/**
* Session read handler.
* Do not call this method directly.
* @param string $id session ID
* @return string the session data
*/
public function readSession($id)
{
$data = $this->redis->executeCommand('GET', [$this->calculateKey($id)]);
return $data === false || $data === null ? '' : $data;
}
/**
* Session write handler.
* Do not call this method directly.
* @param string $id session ID
* @param string $data session data
* @return bool whether session write is successful
*/
public function writeSession($id, $data)
{
return (bool) $this->redis->executeCommand('SET', [$this->calculateKey($id), $data, 'EX', $this->getTimeout()]);
}
/**
* Session destroy handler.
* Do not call this method directly.
* @param string $id session ID
* @return bool whether session is destroyed successfully
*/
public function destroySession($id)
{
$this->redis->executeCommand('DEL', [$this->calculateKey($id)]);
// @see https://github.com/yiisoft/yii2-redis/issues/82
return true;
}
/**
* Generates a unique key used for storing session data in cache.
* @param string $id session variable name
* @return string a safe cache key associated with the session variable name
*/
protected function calculateKey($id)
{
return $this->keyPrefix . md5(json_encode([__CLASS__, $id]));
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\redis;
use yii\db\Exception;
/**
* SocketException indicates a socket connection failure in [[Connection]].
* @since 2.0.7
*/
class SocketException extends Exception
{
/**
* @return string the user-friendly name of this exception
*/
public function getName()
{
return 'Redis Socket Exception';
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment