mirror of
https://github.com/yiisoft/yii2.git
synced 2025-11-12 20:21:19 +08:00
Merge branch 'master' of github.com:yiisoft/yii2 into 8670-multi-data-session
This commit is contained in:
299
docs/guide-pt-BR/output-data-providers.md
Normal file
299
docs/guide-pt-BR/output-data-providers.md
Normal file
@@ -0,0 +1,299 @@
|
||||
Data Providers (Provedores de Dados)
|
||||
==============
|
||||
|
||||
Nas seções [Paginação](output-pagination.md) e [ordenação](output-sorting.md), descrevemos como os usuários finais podem escolher uma determinada página de dados para exibir e ordená-los por algumas colunas. Uma vez que esta tarefa de paginação e ordenação de dados é muito comum, Yii fornece um conjunto de classes *data provider* para encapsular estes recursos.
|
||||
|
||||
Um data provider é uma classe que implementa
|
||||
[[yii\data\DataProviderInterface]]. Ele suporta principalmente a recuperação de dados paginados e ordenados. Geralmente é usado para trabalhar com [widgets de dados](output-data-widgets.md) de modo que os usuários finais possam interativamente paginar e ordenar dados.
|
||||
|
||||
O Yii fornece as seguintes classes de data provider:
|
||||
|
||||
* [[yii\data\ActiveDataProvider]]: Utilize [[yii\db\Query]] ou [[yii\db\ActiveQuery]] para consultar dados de um database e retorná-los na forma de array ou uma instância de [Active Record](db-active-record.md).
|
||||
* [[yii\data\SqlDataProvider]]: executa uma instrução SQL e retorna os dados do banco de dados como array.
|
||||
* [[yii\data\ArrayDataProvider]]: é preciso um grande array e retorna uma parte deste baseado na paginação e ordenação especificada.
|
||||
|
||||
O uso de todos estes data providers compartilham o seguinte padrão comum:
|
||||
|
||||
```php
|
||||
// cria o data provider configurando suas propriedades de paginação e ordenação
|
||||
$provider = new XyzDataProvider([
|
||||
'pagination' => [...],
|
||||
'sort' => [...],
|
||||
]);
|
||||
|
||||
// recupera dados paginados e ordenados
|
||||
$models = $provider->getModels();
|
||||
|
||||
// obtem o número de itens de dados na página atual
|
||||
$count = $provider->getCount();
|
||||
|
||||
// obtem o número total de itens de dados de todas as páginas
|
||||
$totalCount = $provider->getTotalCount();
|
||||
```
|
||||
|
||||
Você define o comportamento da paginação e ordenação do data provider configurando suas propriedades [[yii\data\BaseDataProvider::pagination|pagination]] e [[yii\data\BaseDataProvider::sort|sort]] que correspondem às configurações [[yii\data\Pagination]] and [[yii\data\Sort]] respectivamente. Você também pode configurá-los como false para desativar os recursos de paginação e/ou ordenação.
|
||||
|
||||
[widgets de dados](output-data-widgets.md), assim como [[yii\grid\GridView]], tem uma propriedade chamada `dataProvider` que pode receber uma instância de data provider e exibir os dados que ele fornece. Por exemplo,
|
||||
|
||||
```php
|
||||
echo yii\grid\GridView::widget([
|
||||
'dataProvider' => $dataProvider,
|
||||
]);
|
||||
```
|
||||
|
||||
Estes data providers variam principalmente conforme a fonte de dados é especificada. Nas subseções seguintes, vamos explicar o uso detalhado de cada um dos data providers.
|
||||
|
||||
## Active Data Provider (Provedor de Dados) <span id="active-data-provider"></span>
|
||||
|
||||
Para usar [[yii\data\ActiveDataProvider]], você deve configurar sua propriedade [[yii\data\ActiveDataProvider::query|query]].
|
||||
Ele pode receber qualquer um dos objetos [[yii\db\Query]] ou [[yii\db\ActiveQuery]]. Se for o primeiro, os dados serão retornados em array; se for o último, os dados podem ser retornados em array ou uma instância de [Active Record](db-active-record.md).
|
||||
Por Exemplo,
|
||||
|
||||
```php
|
||||
use yii\data\ActiveDataProvider;
|
||||
|
||||
$query = Post::find()->where(['status' => 1]);
|
||||
|
||||
$provider = new ActiveDataProvider([
|
||||
'query' => $query,
|
||||
'pagination' => [
|
||||
'pageSize' => 10,
|
||||
],
|
||||
'sort' => [
|
||||
'defaultOrder' => [
|
||||
'created_at' => SORT_DESC,
|
||||
'title' => SORT_ASC,
|
||||
]
|
||||
],
|
||||
]);
|
||||
|
||||
// retorna um array de objetos Post
|
||||
$posts = $provider->getModels();
|
||||
```
|
||||
|
||||
Se `$query` no exemplo acima fosse criada usando o código a seguir, então o data provider retornaria um array.
|
||||
|
||||
```php
|
||||
use yii\db\Query;
|
||||
|
||||
$query = (new Query())->from('post')->where(['status' => 1]);
|
||||
```
|
||||
|
||||
> Observação: Se uma query já especificou a cláusula `orderBy, as novas instruções de ordenação dadas por usuários finais
|
||||
(através da configuração `sort`) será acrescentada a cláusula `orderBy` existente. Existindo qualquer uma das cláusulas `limit` e `offset` será substituído pelo request de paginação dos usuários finais (através da configuração `pagination`).
|
||||
|
||||
Por padrão, [[yii\data\ActiveDataProvider]] utiliza o componente `db` da aplicação como a conexão de banco de dados. Você pode usar uma conexão de banco de dados diferente, configurando a propriedade [[yii\data\ActiveDataProvider::db]].
|
||||
|
||||
## SQL Data Provider <span id="sql-data-provider"></span>
|
||||
|
||||
[[yii\data\SqlDataProvider]] trabalha com uma instrução SQL, que é usado para obter os dados necessários. Com base nas especificações de [[yii\data\SqlDataProvider::sort|sort]] e
|
||||
[[yii\data\SqlDataProvider::pagination|pagination]], o provider ajustará as cláusulas `ORDER BY` e `LIMIT` da instrução SQL em conformidade para buscar somente a página de dados solicitada na ordem desejada.
|
||||
|
||||
Para usar [[yii\data\SqlDataProvider]], você deve especificar a propriedade [[yii\data\SqlDataProvider::sql|sql]] bem como a propriedade [[yii\data\SqlDataProvider::totalCount|totalCount]. Por exemplo,
|
||||
|
||||
```php
|
||||
use yii\data\SqlDataProvider;
|
||||
|
||||
$count = Yii::$app->db->createCommand('
|
||||
SELECT COUNT(*) FROM post WHERE status=:status
|
||||
', [':status' => 1])->queryScalar();
|
||||
|
||||
$provider = new SqlDataProvider([
|
||||
'sql' => 'SELECT * FROM post WHERE status=:status',
|
||||
'params' => [':status' => 1],
|
||||
'totalCount' => $count,
|
||||
'pagination' => [
|
||||
'pageSize' => 10,
|
||||
],
|
||||
'sort' => [
|
||||
'attributes' => [
|
||||
'title',
|
||||
'view_count',
|
||||
'created_at',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
// retorna um array de linha de dados
|
||||
$models = $provider->getModels();
|
||||
```
|
||||
|
||||
> Observação: A propriedade [[yii\data\SqlDataProvider::totalCount|totalCount]] é requerida somente se você precisar paginar os dados. Isto porque a instrução SQL definida por [[yii\data\SqlDataProvider::sql|sql]] será modificada pelo provider para retornar somente a página atual de dados solicitada. O provider ainda precisa saber o número total de dados a fim de calcular correctamente o número de páginas disponíveis.
|
||||
|
||||
## Array Data Provider <span id="array-data-provider"></span>
|
||||
|
||||
[[yii\data\ArrayDataProvider]] é melhor usado quando se trabalha com um grande array. O provider permite-lhe retornar uma página dos dados do array ordenados por uma ou várias colunas. Para usar [[yii\data\ArrayDataProvider]], você precisa especificar a propriedade [[yii\data\ArrayDataProvider::allModels|allModels]] como um grande array. Elementos deste array podem ser outros arrays associados
|
||||
(por exemplo, resultados de uma query do [DAO](db-dao.md)) ou objetos (por exemplo uma isntância do [Active Record](db-active-record.md)).
|
||||
Por exemplo,
|
||||
|
||||
```php
|
||||
use yii\data\ArrayDataProvider;
|
||||
|
||||
$data = [
|
||||
['id' => 1, 'name' => 'name 1', ...],
|
||||
['id' => 2, 'name' => 'name 2', ...],
|
||||
...
|
||||
['id' => 100, 'name' => 'name 100', ...],
|
||||
];
|
||||
|
||||
$provider = new ArrayDataProvider([
|
||||
'allModels' => $data,
|
||||
'pagination' => [
|
||||
'pageSize' => 10,
|
||||
],
|
||||
'sort' => [
|
||||
'attributes' => ['id', 'name'],
|
||||
],
|
||||
]);
|
||||
|
||||
// obter as linhas na página corrente
|
||||
$rows = $provider->getModels();
|
||||
```
|
||||
|
||||
> Observação: Comparado [Active Data Provider](#active-data-provider) com [SQL Data Provider](#sql-data-provider),
|
||||
array data provider é menos eficiante porque requer o carregamento de *todo* o dado na memória.
|
||||
|
||||
## Trabalhando com chave de dados <span id="working-with-keys"></span>
|
||||
|
||||
Ao usar os itens de dados retornados por um data provider, muitas vezes você precisa identificar cada item de dados com uma chave única.
|
||||
Por exemplo, se os itens de dados representam as informações do cliente, você pode querer usar o ID do cliente como a chave
|
||||
para cada dado do cliente. Data providers podem retornar uma lista das tais chaves correspondentes aos itens de dados retornados por [[yii\data\DataProviderInterface::getModels()]]. Por exemplo,
|
||||
|
||||
```php
|
||||
use yii\data\ActiveDataProvider;
|
||||
|
||||
$query = Post::find()->where(['status' => 1]);
|
||||
|
||||
$provider = new ActiveDataProvider([
|
||||
'query' => Post::find(),
|
||||
]);
|
||||
|
||||
// retorna uma array de objetos Post
|
||||
$posts = $provider->getModels();
|
||||
|
||||
// retorna os valores de chave primária correspondente a $posts
|
||||
$ids = $provider->getKeys();
|
||||
```
|
||||
|
||||
No exemplo abaixo, como você fornecer para [[yii\data\ActiveDataProvider]] um objeto [[yii\db\ActiveQuery]],
|
||||
ele é inteligente o suficiente para retornar os valores de chave primária como chaves no resultado. Você também pode especificar explicitamente como os valores de chave devem ser calculados configurando
|
||||
[[yii\data\ActiveDataProvider::key]] com um nome de coluna ou com uma função calback que retorna os valores das chaves. Por exemplo,
|
||||
|
||||
```php
|
||||
// use "slug" column as key values
|
||||
$provider = new ActiveDataProvider([
|
||||
'query' => Post::find(),
|
||||
'key' => 'slug',
|
||||
]);
|
||||
|
||||
// usa o resultados do md5(id) como valor da chave
|
||||
$provider = new ActiveDataProvider([
|
||||
'query' => Post::find(),
|
||||
'key' => function ($model) {
|
||||
return md5($model->id);
|
||||
}
|
||||
]);
|
||||
```
|
||||
|
||||
## Criado Data Provider customizado <span id="custom-data-provider"></span>
|
||||
|
||||
Para criar sau prórpia classe de data provider customizada, você deve implementar [[yii\data\DataProviderInterface]].
|
||||
Um caminho fácil é extender de [[yii\data\BaseDataProvider]] o que permite a você se concentrar na lógica principal do data provider. Em particular, você precisa principalmente implementar os seguintes métodos:
|
||||
|
||||
- [[yii\data\BaseDataProvider::prepareModels()|prepareModels()]]: prepara o data models que será disponibilizado na página atual e as retorna como um array.
|
||||
- [[yii\data\BaseDataProvider::prepareKeys()|prepareKeys()]]:recebe um array de data models disponíveis e retorna chaves que lhes estão associados.
|
||||
- [[yii\data\BaseDataProvider::prepareTotalCount()|prepareTotalCount]]: retorna um valor que indica o número total de data models no data provider.
|
||||
|
||||
Abaixo está um exemplo de um data provider que lê dados em CSV eficientemente:
|
||||
|
||||
```php
|
||||
<?php
|
||||
use yii\data\BaseDataProvider;
|
||||
|
||||
class CsvDataProvider extends BaseDataProvider
|
||||
{
|
||||
/**
|
||||
* @var string name of the CSV file to read
|
||||
*/
|
||||
public $filename;
|
||||
|
||||
/**
|
||||
* @var string|callable name of the key column or a callable returning it
|
||||
*/
|
||||
public $key;
|
||||
|
||||
/**
|
||||
* @var SplFileObject
|
||||
*/
|
||||
protected $fileObject; // SplFileObject é muito conveniente para procurar uma linha específica em um arquivo
|
||||
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
public function init()
|
||||
{
|
||||
parent::init();
|
||||
|
||||
// open file
|
||||
$this->fileObject = new SplFileObject($this->filename);
|
||||
}
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function prepareModels()
|
||||
{
|
||||
$models = [];
|
||||
$pagination = $this->getPagination();
|
||||
if ($pagination === false) {
|
||||
// no caso não há paginação, lê todas as linhas
|
||||
while (!$this->fileObject->eof()) {
|
||||
$models[] = $this->fileObject->fgetcsv();
|
||||
$this->fileObject->next();
|
||||
}
|
||||
} else {
|
||||
// no caso existe paginação, lê somente uma página
|
||||
$pagination->totalCount = $this->getTotalCount();
|
||||
$this->fileObject->seek($pagination->getOffset());
|
||||
$limit = $pagination->getLimit();
|
||||
for ($count = 0; $count < $limit; ++$count) {
|
||||
$models[] = $this->fileObject->fgetcsv();
|
||||
$this->fileObject->next();
|
||||
}
|
||||
}
|
||||
return $models;
|
||||
}
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function prepareKeys($models)
|
||||
{
|
||||
if ($this->key !== null) {
|
||||
$keys = [];
|
||||
foreach ($models as $model) {
|
||||
if (is_string($this->key)) {
|
||||
$keys[] = $model[$this->key];
|
||||
} else {
|
||||
$keys[] = call_user_func($this->key, $model);
|
||||
}
|
||||
}
|
||||
return $keys;
|
||||
} else {
|
||||
return array_keys($models);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @inheritdoc
|
||||
*/
|
||||
protected function prepareTotalCount()
|
||||
{
|
||||
$count = 0;
|
||||
while (!$this->fileObject->eof()) {
|
||||
$this->fileObject->next();
|
||||
++$count;
|
||||
}
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
95
docs/guide-pt-BR/output-theming.md
Normal file
95
docs/guide-pt-BR/output-theming.md
Normal file
@@ -0,0 +1,95 @@
|
||||
Temas
|
||||
=====
|
||||
|
||||
Tema é uma forma de substituir um conjunto de [views](structure-views.md) por outras, sem a necessidade de tocar no código de renderização de view original. Você pode usar tema para alterar sistematicamente a aparência de uma aplicação.
|
||||
|
||||
Para usar tema, você deve configurar a propriedade [[yii\base\View::theme|theme]] da `view (visão)` da aplicação.
|
||||
A propriedade configura um objeto [[yii\base\Theme]] que rege a forma como os arquivos de views são substituídos. Você deve principalmente especificar as seguintes propriedades de [[yii\base\Theme]]:
|
||||
|
||||
- [[yii\base\Theme::basePath]]: determina o diretório de base que contém os recursos temáticos (CSS, JS, images, etc.)
|
||||
- [[yii\base\Theme::baseUrl]]: determina a URL base dos recursos temáticos.
|
||||
- [[yii\base\Theme::pathMap]]: determina as regras de substituição dos arquivos de view. Mais detalhes serão dados nas subseções seguintes.
|
||||
|
||||
Por exemplo, se você chama `$this->render('about')` no `SiteController`, você estará renderizando a view
|
||||
`@app/views/site/about.php`. Todavia, se você habilitar tema na seguinte configuração da aplicação, a view `@app/themes/basic/site/about.php` será renderizada, no lugar da primeira.
|
||||
|
||||
```php
|
||||
return [
|
||||
'components' => [
|
||||
'view' => [
|
||||
'theme' => [
|
||||
'basePath' => '@app/themes/basic'
|
||||
'baseUrl' => '@web/themes/basic',
|
||||
'pathMap' => [
|
||||
'@app/views' => '@app/themes/basic',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
> Observação: aliases de caminhos são suportados por temas. Ao fazer substituição de view, aliases de caminho serão transformados nos caminhos ou URLs reais.
|
||||
|
||||
Você pode acessar o objeto [[yii\base\Theme]] através da propriedade [[yii\base\View::theme]]. Por exemplo, na view, você pode escrever o seguinte código, pois `$this` refere-se ao objeto view:
|
||||
|
||||
```php
|
||||
$theme = $this->theme;
|
||||
|
||||
// retorno: $theme->baseUrl . '/img/logo.gif'
|
||||
$url = $theme->getUrl('img/logo.gif');
|
||||
|
||||
// retorno: $theme->basePath . '/img/logo.gif'
|
||||
$file = $theme->getPath('img/logo.gif');
|
||||
```
|
||||
|
||||
A propriedade [[yii\base\Theme::pathMap]] rege como a view deve ser substituída. É preciso um array de pares de valores-chave, onde as chaves são os caminhos originais da view que serão substituídos e os valores são os caminhos dos temas correspondentes. A substituição é baseada na correspondência parcial: Se um caminho de view inicia com alguma chave no array [[yii\base\Theme::pathMap|pathMap]], a parte correspondente será substituída pelo valor do array.
|
||||
Usando o exemplo de configuração acima,
|
||||
`@app/views/site/about.php` corresponde parcialmente a chave
|
||||
`@app/views`, ele será substituído por `@app/themes/basic/site/about.php`.
|
||||
|
||||
|
||||
## Tema de Módulos <span id="theming-modules"></span>
|
||||
|
||||
A fim de configurar temas por módulos, [[yii\base\Theme::pathMap]] pode ser configurado da seguinte forma:
|
||||
|
||||
```php
|
||||
'pathMap' => [
|
||||
'@app/views' => '@app/themes/basic',
|
||||
'@app/modules' => '@app/themes/basic/modules', // <-- !!!
|
||||
],
|
||||
```
|
||||
|
||||
Isto lhe permitirá tematizar `@app/modules/blog/views/comment/index.php` com `@app/themes/basic/modules/blog/views/comment/index.php`.
|
||||
|
||||
|
||||
## Tema de Widgets <span id="theming-widgets"></span>
|
||||
|
||||
A fim de configurar temas por widgets, você pode configurar [[yii\base\Theme::pathMap]] da seguinte forma:
|
||||
|
||||
```php
|
||||
'pathMap' => [
|
||||
'@app/views' => '@app/themes/basic',
|
||||
'@app/widgets' => '@app/themes/basic/widgets', // <-- !!!
|
||||
],
|
||||
```
|
||||
|
||||
Isto lhe permitirá tematizar `@app/widgets/currency/views/index.php` com `@app/themes/basic/widgets/currency/index.php`.
|
||||
|
||||
|
||||
## Herança de Tema <span id="theme-inheritance"></span>
|
||||
|
||||
Algumas vezes você pode querer definir um tema que contém um visual básico da aplicação, e em seguida, com base em algum feriado, você pode querer variar o visual levemente. Você pode atingir este objetivo usando herança de tema que é feito através do mapeamento de um único caminho de view para múltiplos alvos. Por exemplo,
|
||||
|
||||
```php
|
||||
'pathMap' => [
|
||||
'@app/views' => [
|
||||
'@app/themes/christmas',
|
||||
'@app/themes/basic',
|
||||
],
|
||||
]
|
||||
```
|
||||
|
||||
Neste caso, a view `@app/views/site/index.php` seria tematizada tanto como `@app/themes/christmas/site/index.php` ou
|
||||
`@app/themes/basic/site/index.php`, dependendo de qual arquivo de tema existir. Se os dois arquivos existirem, o primeiro terá precedência. Na prática, você iria manter mais arquivos de temas em `@app/themes/basic` e personalizar alguns deles em `@app/themes/christmas`.
|
||||
|
||||
185
docs/guide-pt-BR/security-authentication.md
Normal file
185
docs/guide-pt-BR/security-authentication.md
Normal file
@@ -0,0 +1,185 @@
|
||||
Autenticação
|
||||
==============
|
||||
|
||||
Autenticação é o processo de verificação da identidade do usuário. geralmente é usado um identificador (ex. um nome de usuário ou endereço de e-mail) e um token secreto (ex. uma senha ou um token de acesso) para determinar se o usuário é quem ele diz ser. Autenticação é a base do recurso de login.
|
||||
|
||||
Yii fornece um framework de autenticação com vários componentes que dão suporte a login. Para usar este framework, você precisa primeiramente fazer o seguinte:
|
||||
|
||||
* Configurar o componente [[yii\web\User|user]] da aplicação;
|
||||
* Criar uma classe que implementa a interface [[yii\web\IdentityInterface]].
|
||||
|
||||
|
||||
## Configurando [[yii\web\User]] <span id="configuring-user"></span>
|
||||
|
||||
O componente [[yii\web\User|user]] da aplicação gerencia o status de autenticação dos usuários. Ele requer que você especifique uma [[yii\web\User::identityClass|identity class]] que contém a atual lógia de autenticação.
|
||||
Na cofiguração abaixo, o [[yii\web\User::identityClass|identity class]] do
|
||||
[[yii\web\User|user]] é configurada para ser `app\models\User` cuja implementação é explicada na próxima subseção:
|
||||
|
||||
```php
|
||||
return [
|
||||
'components' => [
|
||||
'user' => [
|
||||
'identityClass' => 'app\models\User',
|
||||
],
|
||||
],
|
||||
];
|
||||
```
|
||||
|
||||
|
||||
## Implementação [[yii\web\IdentityInterface]] <span id="implementing-identity"></span>
|
||||
|
||||
O [[yii\web\User::identityClass|identity class]] deve implementar a interface [[yii\web\IdentityInterface]] que contém os seguintes métodos:
|
||||
|
||||
* [[yii\web\IdentityInterface::findIdentity()|findIdentity()]]: ele procura por uma instância da classe de identidade usando o ID de usuário especificado. Este método é usado quando você precisa manter o status de login via sessão.
|
||||
* [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]: ele procura por uma instância da classe de identidade usando o token de acesso informado. Este método é usado quando você precisa autenticar um usuário por um único token secreto (ex. Em uma aplicação stateless RESTful).
|
||||
* [[yii\web\IdentityInterface::getId()|getId()]]: Retorna o ID do usuário representado por essa instância da classe de identidade.
|
||||
* [[yii\web\IdentityInterface::getAuthKey()|getAuthKey()]]: retorna uma chave para verificar login via cookie. A chave é mantida no cookie de login e será comparada com o informação do lado servidor para atestar a validade do cookie.
|
||||
* [[yii\web\IdentityInterface::validateAuthKey()|validateAuthKey()]]: Implementa a lógica de verificação da chave de login via cookie.
|
||||
|
||||
Se um método em particular não for necessário, você pode implementá-lo com um corpo vazio. Por exemplo, se a sua aplicação é somente stateless RESTful, você só precisa implementar [[yii\web\IdentityInterface::findIdentityByAccessToken()|findIdentityByAccessToken()]]
|
||||
e [[yii\web\IdentityInterface::getId()|getId()]] deixando todos os outros métodos com um corpo vazio.
|
||||
|
||||
No exemplo a seguir, um [[yii\web\User::identityClass|identity class]] é implementado como uma classe [Active Record](db-active-record.md) associada com a tabela `user` do banco de dados.
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
use yii\db\ActiveRecord;
|
||||
use yii\web\IdentityInterface;
|
||||
|
||||
class User extends ActiveRecord implements IdentityInterface
|
||||
{
|
||||
public static function tableName()
|
||||
{
|
||||
return 'user';
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds an identity by the given ID.
|
||||
*
|
||||
* @param string|integer $id the ID to be looked for
|
||||
* @return IdentityInterface|null the identity object that matches the given ID.
|
||||
*/
|
||||
public static function findIdentity($id)
|
||||
{
|
||||
return static::findOne($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds an identity by the given token.
|
||||
*
|
||||
* @param string $token the token to be looked for
|
||||
* @return IdentityInterface|null the identity object that matches the given token.
|
||||
*/
|
||||
public static function findIdentityByAccessToken($token, $type = null)
|
||||
{
|
||||
return static::findOne(['access_token' => $token]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|string current user ID
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string current user auth key
|
||||
*/
|
||||
public function getAuthKey()
|
||||
{
|
||||
return $this->auth_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $authKey
|
||||
* @return boolean if auth key is valid for current user
|
||||
*/
|
||||
public function validateAuthKey($authKey)
|
||||
{
|
||||
return $this->getAuthKey() === $authKey;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Como explicado anteriormente, você só precisa implementar `getAuthKey()` e `validateAuthKey()` se a sua aplicação usa recurso de login via cookie. Neste caso, você pode utilizar o seguinte código para gerar uma chave de autenticação para cada usuário
|
||||
e gravá-la na tabela `user`:
|
||||
|
||||
```php
|
||||
class User extends ActiveRecord implements IdentityInterface
|
||||
{
|
||||
......
|
||||
|
||||
public function beforeSave($insert)
|
||||
{
|
||||
if (parent::beforeSave($insert)) {
|
||||
if ($this->isNewRecord) {
|
||||
$this->auth_key = \Yii::$app->security->generateRandomString();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Observação: Não confunda a classe de identidade `User` com [[yii\web\User]]. O primeiro é a classe que implementa a lógica de autenticação. Muitas vezes, é implementado como uma classe [Active Record](db-active-record.md) associado com algum tipo de armazenamento persistente para armazenar as informações de credenciais do usuário. O último é um componente da apicação responsável pela gestão do estado de autenticação do usuário.
|
||||
|
||||
|
||||
## Usando [[yii\web\User]] <span id="using-user"></span>
|
||||
|
||||
Você usa o [[yii\web\User]] principalmente como um componente `user` da aplicação.
|
||||
|
||||
É possível detectar a identidade do usuário corrente utilizando a expressão `Yii::$app->user->identity`. retorna uma instância de [[yii\web\User::identityClass|identity class]] representando o atual usuário logado, ou null se o usuário corrente não estiver autenticado (acessando como convidado). O código a seguir mostra como recuperar outras informações relacionadas à autenticação de [[yii\web\User]]:
|
||||
|
||||
```php
|
||||
// identidade do usuário corrente. Null se o usuário não estiver autenticado.
|
||||
$identity = Yii::$app->user->identity;
|
||||
|
||||
// o ID do usuário corrente. Null se o usuário não estiver autenticado.
|
||||
$id = Yii::$app->user->id;
|
||||
|
||||
// se o usuário atual é um convidado (não autenticado)
|
||||
$isGuest = Yii::$app->user->isGuest;
|
||||
```
|
||||
|
||||
Para logar um usuário, você pode usar o seguinte código:
|
||||
|
||||
```php
|
||||
// encontrar uma identidade de usuário com o nome de usuário especificado.
|
||||
// note que você pode quere checar a senha se necessário
|
||||
$identity = User::findOne(['username' => $username]);
|
||||
|
||||
// Logar o usuário
|
||||
Yii::$app->user->login($identity);
|
||||
```
|
||||
|
||||
O método [[yii\web\User::login()]] define a identidade do usuário atual para o [[yii\web\User]]. Se a sessão está [[yii\web\User::enableSession|enabled]], ele vai manter a identidade na sessão para que o status de autenticação do usuário seja mantido durante toda a sessão. Se for login via cookie(ex. login "remember me") for [[yii\web\User::enableAutoLogin|enabled]], ele também guardará a identidade em um cookie para que o estado de autenticação do usuário possa ser recuperado a partir do cookie enquanto o cookie permanece válido.
|
||||
|
||||
A fim de permitir login via cookie, você pode configurar [[yii\web\User::enableAutoLogin]] como true na configuração da aplicação. Você também precisará fornecer um parâmetro de tempo de duração quando chamar o método [[yii\web\User::login()]].
|
||||
|
||||
Para realizar o logout de um usuário, simplesmente chame
|
||||
|
||||
```php
|
||||
Yii::$app->user->logout();
|
||||
```
|
||||
|
||||
Note que o logout de um usuário só tem sentido quando a sessão está habilitada. O método irá limpar o status de autenticação de usuário de memória e sessão. E por padrão, ele também destruirá *todos* os dados da sessão do usuário. Se você quiser guardar os dados da sessão, você deve chamar `Yii::$app->user->logout(false)`.
|
||||
|
||||
|
||||
## Eventos de Autenticação <span id="auth-events"></span>
|
||||
|
||||
A classe [[yii\web\User]] dispara alguns eventos durante os processos de login e logout.
|
||||
|
||||
* [[yii\web\User::EVENT_BEFORE_LOGIN|EVENT_BEFORE_LOGIN]]: disparado no início de [[yii\web\User::login()]].
|
||||
Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para false, o processo de login será cancelado.
|
||||
* [[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]]: dispara após de um login com sucesso.
|
||||
* [[yii\web\User::EVENT_BEFORE_LOGOUT|EVENT_BEFORE_LOGOUT]]: dispara no início de [[yii\web\User::logout()]]. Se o manipulador de evento define a propriedade [[yii\web\UserEvent::isValid|isValid]] do objeto de evento para false, o processo de logout será cancelado.
|
||||
* [[yii\web\User::EVENT_AFTER_LOGOUT|EVENT_AFTER_LOGOUT]]: dispara após um logout com sucesso.
|
||||
|
||||
Você pode responder a estes eventos implementando funcionalidades, tais como auditoria de login, estatísticas de usuários on-line. Por exemplo, no manipulador
|
||||
[[yii\web\User::EVENT_AFTER_LOGIN|EVENT_AFTER_LOGIN]], você pode registrar o tempo de login e endereço IP na tabela `user`.
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
Первый лучше всего подходит для фикстур общего назначения, в то время как последний имеет расширенные функции,
|
||||
специально предназначенные для работы с базой данных и ActiveRecord.
|
||||
|
||||
Следующий код показывает как объявить фикстуру для модели ActiveRecord `User`, которая соответствует таблицы пользователей.
|
||||
Следующий код показывает как объявить фикстуру для модели ActiveRecord `User`, которая соответствует таблице пользователей.
|
||||
|
||||
|
||||
```php
|
||||
@@ -96,7 +96,7 @@ class UserProfileFixture extends ActiveFixture
|
||||
```
|
||||
|
||||
Зависимость также гарантирует, что фикстуры загружаются и выгружаются в определенном порядке. В предыдущем примере `UserFixture`
|
||||
будет автоматически загружена до `UserProfileFixture`, тем самым гарантирую существование всех внешних ключей, и будет выгружена
|
||||
будет автоматически загружена до `UserProfileFixture`, тем самым гарантируя существование всех внешних ключей, и будет выгружена
|
||||
после того как выгрузится `UserProfileFixture` по тем же причинам.
|
||||
|
||||
Выше мы показали как объявить фикстуру для таблицы базы данных. Для объявления фикстуры не связанной с базой данных (например,
|
||||
@@ -107,7 +107,7 @@ class UserProfileFixture extends ActiveFixture
|
||||
Использование фикстур
|
||||
---------------------
|
||||
|
||||
Если вы используете [CodeCeption](http://codeception.com/) для тестирование вашего кода, вам следует рассмотреть вопрос
|
||||
Если вы используете [CodeCeption](http://codeception.com/) для тестирования вашего кода, вам следует рассмотреть вопрос
|
||||
об использовании расширения `yii2-codeception`, которое имеет встроенную поддержку загрузки фикстур и доступа к ним.
|
||||
Если вы используете другой фреймворк для тестирования, вы можете использовать [[yii\test\FixtureTrait]] в ваших тестах для
|
||||
этих целей.
|
||||
|
||||
@@ -18,6 +18,7 @@ Yii Framework 2 Change Log
|
||||
- Bug #8593: Fixed `yii\db\ActiveQuery` produces incorrect SQL for aggregations, when `sql` field is set (klimov-paul)
|
||||
- Bug #8595: Fixed `yii\rbac\DbManager::checkAccessFromCache()` to check against auth items loaded in cache recursively (achretien, qiangxue)
|
||||
- Bug #8606: Fixed `yii\web\Response::xSendFile()` does not reset format (vyants)
|
||||
- Bug #8627: Fixed `yii\db\Migration` produces incorrect results due to table schema caching (klimov-paul)
|
||||
- Bug: Fixed string comparison in `BaseActiveRecord::unlink()` which may result in wrong comparison result for hash valued primary keys starting with `0e` (cebe)
|
||||
- Bug: Pass correct action name to `yii\console\Controller::options()` when default action was requested (cebe)
|
||||
- Bug: Automatic garbage collection in `yii\caching\FileCache` was not triggered (kidol)
|
||||
|
||||
@@ -78,7 +78,7 @@ class Markdown extends \cebe\markdown\Parser
|
||||
*/
|
||||
protected function renderEmph($element)
|
||||
{
|
||||
return Console::ansiFormat($this->renderAbsy($element[1]), Console::ITALIC);
|
||||
return Console::ansiFormat($this->renderAbsy($element[1]), [Console::ITALIC]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,7 +88,7 @@ class Markdown extends \cebe\markdown\Parser
|
||||
*/
|
||||
protected function renderStrong($element)
|
||||
{
|
||||
return Console::ansiFormat($this->renderAbsy($element[1]), Console::BOLD);
|
||||
return Console::ansiFormat($this->renderAbsy($element[1]), [Console::BOLD]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -93,6 +93,10 @@ class Command extends Component
|
||||
* @var string the SQL statement that this command represents
|
||||
*/
|
||||
private $_sql;
|
||||
/**
|
||||
* @var string name of the table, which schema, should be refreshed after command execution.
|
||||
*/
|
||||
private $_refreshTableName;
|
||||
|
||||
|
||||
/**
|
||||
@@ -142,6 +146,7 @@ class Command extends Component
|
||||
$this->_sql = $this->db->quoteSql($sql);
|
||||
$this->_pendingParams = [];
|
||||
$this->params = [];
|
||||
$this->_refreshTableName = null;
|
||||
}
|
||||
|
||||
return $this;
|
||||
@@ -412,7 +417,7 @@ class Command extends Component
|
||||
*
|
||||
* @param string $table the table that new rows will be inserted into.
|
||||
* @param array $columns the column data (name => value) to be inserted into the table.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function insert($table, $columns)
|
||||
{
|
||||
@@ -443,7 +448,7 @@ class Command extends Component
|
||||
* @param string $table the table that new rows will be inserted into.
|
||||
* @param array $columns the column names
|
||||
* @param array $rows the rows to be batch inserted into the table
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function batchInsert($table, $columns, $rows)
|
||||
{
|
||||
@@ -469,7 +474,7 @@ class Command extends Component
|
||||
* @param string|array $condition the condition that will be put in the WHERE part. Please
|
||||
* refer to [[Query::where()]] on how to specify condition.
|
||||
* @param array $params the parameters to be bound to the command
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function update($table, $columns, $condition = '', $params = [])
|
||||
{
|
||||
@@ -494,7 +499,7 @@ class Command extends Component
|
||||
* @param string|array $condition the condition that will be put in the WHERE part. Please
|
||||
* refer to [[Query::where()]] on how to specify condition.
|
||||
* @param array $params the parameters to be bound to the command
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function delete($table, $condition = '', $params = [])
|
||||
{
|
||||
@@ -519,7 +524,7 @@ class Command extends Component
|
||||
* @param string $table the name of the table to be created. The name will be properly quoted by the method.
|
||||
* @param array $columns the columns (name => definition) in the new table.
|
||||
* @param string $options additional SQL fragment that will be appended to the generated SQL.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function createTable($table, $columns, $options = null)
|
||||
{
|
||||
@@ -532,31 +537,31 @@ class Command extends Component
|
||||
* Creates a SQL command for renaming a DB table.
|
||||
* @param string $table the table to be renamed. The name will be properly quoted by the method.
|
||||
* @param string $newName the new table name. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function renameTable($table, $newName)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL command for dropping a DB table.
|
||||
* @param string $table the table to be dropped. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function dropTable($table)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->dropTable($table);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL command for truncating a DB table.
|
||||
* @param string $table the table to be truncated. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function truncateTable($table)
|
||||
{
|
||||
@@ -572,26 +577,26 @@ class Command extends Component
|
||||
* @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
|
||||
* to convert the give column type to the physical one. For example, `string` will be converted
|
||||
* as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function addColumn($table, $column, $type)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL command for dropping a DB column.
|
||||
* @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
|
||||
* @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function dropColumn($table, $column)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -599,13 +604,13 @@ class Command extends Component
|
||||
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
|
||||
* @param string $oldName the old name of the column. The name will be properly quoted by the method.
|
||||
* @param string $newName the new name of the column. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function renameColumn($table, $oldName, $newName)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -615,13 +620,13 @@ class Command extends Component
|
||||
* @param string $type the column type. [[\yii\db\QueryBuilder::getColumnType()]] will be called
|
||||
* to convert the give column type to the physical one. For example, `string` will be converted
|
||||
* as `varchar(255)`, and `string not null` becomes `varchar(255) not null`.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function alterColumn($table, $column, $type)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -630,26 +635,26 @@ class Command extends Component
|
||||
* @param string $name the name of the primary key constraint.
|
||||
* @param string $table the table that the primary key constraint will be added to.
|
||||
* @param string|array $columns comma separated string or array of columns that the primary key will consist of.
|
||||
* @return Command the command object itself.
|
||||
* @return $this the command object itself.
|
||||
*/
|
||||
public function addPrimaryKey($name, $table, $columns)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a SQL command for removing a primary key constraint to an existing table.
|
||||
* @param string $name the name of the primary key constraint to be removed.
|
||||
* @param string $table the table that the primary key constraint will be removed from.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function dropPrimaryKey($name, $table)
|
||||
{
|
||||
$sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
|
||||
|
||||
return $this->setSql($sql);
|
||||
return $this->setSql($sql)->requireTableSchemaRefresh($table);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -662,7 +667,7 @@ class Command extends Component
|
||||
* @param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas.
|
||||
* @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
|
||||
* @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
|
||||
{
|
||||
@@ -675,7 +680,7 @@ class Command extends Component
|
||||
* Creates a SQL command for dropping a foreign key constraint.
|
||||
* @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
|
||||
* @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function dropForeignKey($name, $table)
|
||||
{
|
||||
@@ -691,7 +696,7 @@ class Command extends Component
|
||||
* @param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
|
||||
* by commas. The column names will be properly quoted by the method.
|
||||
* @param boolean $unique whether to add UNIQUE constraint on the created index.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function createIndex($name, $table, $columns, $unique = false)
|
||||
{
|
||||
@@ -704,7 +709,7 @@ class Command extends Component
|
||||
* Creates a SQL command for dropping an index.
|
||||
* @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
|
||||
* @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
*/
|
||||
public function dropIndex($name, $table)
|
||||
{
|
||||
@@ -720,7 +725,7 @@ class Command extends Component
|
||||
* @param string $table the name of the table whose primary key sequence will be reset
|
||||
* @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
|
||||
* the next new row's primary key will have a value 1.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
* @throws NotSupportedException if this is not supported by the underlying DBMS
|
||||
*/
|
||||
public function resetSequence($table, $value = null)
|
||||
@@ -736,7 +741,7 @@ class Command extends Component
|
||||
* @param string $schema the schema name of the tables. Defaults to empty string, meaning the current
|
||||
* or default schema.
|
||||
* @param string $table the table name.
|
||||
* @return Command the command object itself
|
||||
* @return $this the command object itself
|
||||
* @throws NotSupportedException if this is not supported by the underlying DBMS
|
||||
*/
|
||||
public function checkIntegrity($check = true, $schema = '', $table = '')
|
||||
@@ -776,6 +781,8 @@ class Command extends Component
|
||||
|
||||
Yii::endProfile($token, __METHOD__);
|
||||
|
||||
$this->refreshTableSchema();
|
||||
|
||||
return $n;
|
||||
} catch (\Exception $e) {
|
||||
Yii::endProfile($token, __METHOD__);
|
||||
@@ -850,4 +857,27 @@ class Command extends Component
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks specified table schema to be refreshed after command execution.
|
||||
* @param string $name name of the table, which schema should be refreshed.
|
||||
* @return $this this command instance
|
||||
* @since 2.0.5
|
||||
*/
|
||||
protected function requireTableSchemaRefresh($name)
|
||||
{
|
||||
$this->_refreshTableName = $name;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes table schema, which was marked by [[requireTableSchemaRefreshment()]]
|
||||
* @since 2.0.5
|
||||
*/
|
||||
protected function refreshTableSchema()
|
||||
{
|
||||
if ($this->_refreshTableName !== null) {
|
||||
$this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ class Migration extends Component implements MigrationInterface
|
||||
{
|
||||
parent::init();
|
||||
$this->db = Instance::ensure($this->db, Connection::className());
|
||||
$this->db->getSchema()->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -280,6 +280,24 @@ abstract class Schema extends Object
|
||||
$this->_tables = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the particular table schema.
|
||||
* This method cleans up cached table schema so that it can be re-created later
|
||||
* to reflect the database schema change.
|
||||
* @param string $name table name.
|
||||
* @since 2.0.5
|
||||
*/
|
||||
public function refreshTableSchema($name)
|
||||
{
|
||||
unset($this->_tables[$name]);
|
||||
$this->_tableNames = [];
|
||||
/* @var $cache Cache */
|
||||
$cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
|
||||
if ($this->db->enableSchemaCache && $cache instanceof Cache) {
|
||||
$cache->delete($this->getCacheKey($name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a query builder for the database.
|
||||
* This method may be overridden by child classes to create a DBMS-specific query builder.
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
namespace yii\db\mssql;
|
||||
|
||||
use yii\base\InvalidParamException;
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\db\Query;
|
||||
|
||||
/**
|
||||
* QueryBuilder is the query builder for MS SQL Server databases (version 2008 and above).
|
||||
@@ -222,7 +224,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
|
||||
*
|
||||
* @param string $operator
|
||||
* @param array $columns
|
||||
* @param array $values
|
||||
* @param Query $values
|
||||
* @param array $params
|
||||
* @return string SQL
|
||||
*/
|
||||
|
||||
@@ -9,6 +9,7 @@ namespace yii\db\oci;
|
||||
|
||||
use yii\base\InvalidCallException;
|
||||
use yii\db\Connection;
|
||||
use yii\db\Expression;
|
||||
use yii\db\TableSchema;
|
||||
use yii\db\ColumnSchema;
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ use yii\db\Connection;
|
||||
use yii\db\Exception;
|
||||
use yii\base\InvalidParamException;
|
||||
use yii\base\NotSupportedException;
|
||||
use yii\db\Query;
|
||||
|
||||
/**
|
||||
* QueryBuilder is the query builder for SQLite databases.
|
||||
@@ -299,7 +300,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
|
||||
*
|
||||
* @param string $operator
|
||||
* @param array $columns
|
||||
* @param array $values
|
||||
* @param Query $values
|
||||
* @param array $params
|
||||
* @return string SQL
|
||||
*/
|
||||
|
||||
@@ -270,8 +270,7 @@ class Schema extends \yii\db\Schema
|
||||
*/
|
||||
public function setTransactionIsolationLevel($level)
|
||||
{
|
||||
switch($level)
|
||||
{
|
||||
switch ($level) {
|
||||
case Transaction::SERIALIZABLE:
|
||||
$this->db->createCommand("PRAGMA read_uncommitted = False;")->execute();
|
||||
break;
|
||||
|
||||
@@ -101,7 +101,7 @@ class EmailValidator extends Validator
|
||||
'message' => Yii::$app->getI18n()->format($this->message, [
|
||||
'attribute' => $model->getAttributeLabel($attribute),
|
||||
], Yii::$app->language),
|
||||
'enableIDN' => (boolean) $this->enableIDN,
|
||||
'enableIDN' => (bool) $this->enableIDN,
|
||||
];
|
||||
if ($this->skipOnEmpty) {
|
||||
$options['skipOnEmpty'] = 1;
|
||||
|
||||
@@ -370,7 +370,7 @@ class FileValidator extends Validator
|
||||
$options['mimeTypes'] = $this->mimeTypes;
|
||||
$options['wrongMimeType'] = Yii::$app->getI18n()->format($this->wrongMimeType, [
|
||||
'attribute' => $label,
|
||||
'mimeTypes' => join(', ', $this->mimeTypes)
|
||||
'mimeTypes' => join(', ', $this->mimeTypes),
|
||||
], Yii::$app->language);
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ class FileValidator extends Validator
|
||||
$options['extensions'] = $this->extensions;
|
||||
$options['wrongExtension'] = Yii::$app->getI18n()->format($this->wrongExtension, [
|
||||
'attribute' => $label,
|
||||
'extensions' => join(', ', $this->extensions)
|
||||
'extensions' => join(', ', $this->extensions),
|
||||
], Yii::$app->language);
|
||||
}
|
||||
|
||||
@@ -386,7 +386,7 @@ class FileValidator extends Validator
|
||||
$options['minSize'] = $this->minSize;
|
||||
$options['tooSmall'] = Yii::$app->getI18n()->format($this->tooSmall, [
|
||||
'attribute' => $label,
|
||||
'limit' => $this->minSize
|
||||
'limit' => $this->minSize,
|
||||
], Yii::$app->language);
|
||||
}
|
||||
|
||||
@@ -394,7 +394,7 @@ class FileValidator extends Validator
|
||||
$options['maxSize'] = $this->maxSize;
|
||||
$options['tooBig'] = Yii::$app->getI18n()->format($this->tooBig, [
|
||||
'attribute' => $label,
|
||||
'limit' => $this->maxSize
|
||||
'limit' => $this->maxSize,
|
||||
], Yii::$app->language);
|
||||
}
|
||||
|
||||
@@ -402,7 +402,7 @@ class FileValidator extends Validator
|
||||
$options['maxFiles'] = $this->maxFiles;
|
||||
$options['tooMany'] = Yii::$app->getI18n()->format($this->tooMany, [
|
||||
'attribute' => $label,
|
||||
'limit' => $this->maxFiles
|
||||
'limit' => $this->maxFiles,
|
||||
], Yii::$app->language);
|
||||
}
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ class UrlValidator extends Validator
|
||||
'message' => Yii::$app->getI18n()->format($this->message, [
|
||||
'attribute' => $model->getAttributeLabel($attribute),
|
||||
], Yii::$app->language),
|
||||
'enableIDN' => (boolean) $this->enableIDN,
|
||||
'enableIDN' => (bool) $this->enableIDN,
|
||||
];
|
||||
if ($this->skipOnEmpty) {
|
||||
$options['skipOnEmpty'] = 1;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
/* @var $lines string[] */
|
||||
/* @var $begin integer */
|
||||
/* @var $end integer */
|
||||
/* @var $args array */
|
||||
/* @var $handler \yii\web\ErrorHandler */
|
||||
?>
|
||||
<li class="<?php if ($index === 1 || !$handler->isCoreFile($file)) echo 'application'; ?> call-stack-item"
|
||||
|
||||
@@ -1224,7 +1224,7 @@ class Request extends \yii\base\Request
|
||||
$cookies[$name] = new Cookie([
|
||||
'name' => $name,
|
||||
'value' => $data[1],
|
||||
'expire'=> null
|
||||
'expire' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1233,7 +1233,7 @@ class Request extends \yii\base\Request
|
||||
$cookies[$name] = new Cookie([
|
||||
'name' => $name,
|
||||
'value' => $value,
|
||||
'expire'=> null
|
||||
'expire' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use yii\caching\FileCache;
|
||||
use yii\db\Connection;
|
||||
use yii\db\DataReader;
|
||||
use yii\db\Expression;
|
||||
use yii\db\Schema;
|
||||
|
||||
/**
|
||||
* @group db
|
||||
@@ -310,6 +311,40 @@ SQL;
|
||||
], $record);
|
||||
}
|
||||
|
||||
public function testCreateTable()
|
||||
{
|
||||
$db = $this->getConnection();
|
||||
$db->createCommand("DROP TABLE IF EXISTS testCreateTable;")->execute();
|
||||
|
||||
$db->createCommand()->createTable('testCreateTable', ['id' => Schema::TYPE_PK, 'bar' => Schema::TYPE_INTEGER])->execute();
|
||||
$db->createCommand()->insert('testCreateTable', ['bar' => 1])->execute();
|
||||
$records = $db->createCommand('SELECT [[id]], [[bar]] FROM {{testCreateTable}};')->queryAll();
|
||||
$this->assertEquals([
|
||||
['id' => 1, 'bar' => 1],
|
||||
], $records);
|
||||
}
|
||||
|
||||
public function testAlterTable()
|
||||
{
|
||||
if ($this->driverName === 'sqlite'){
|
||||
$this->markTestSkipped('Sqlite does not support alterTable');
|
||||
}
|
||||
|
||||
$db = $this->getConnection();
|
||||
$db->createCommand("DROP TABLE IF EXISTS testAlterTable;")->execute();
|
||||
|
||||
$db->createCommand()->createTable('testAlterTable', ['id' => Schema::TYPE_PK, 'bar' => Schema::TYPE_INTEGER])->execute();
|
||||
$db->createCommand()->insert('testAlterTable', ['bar' => 1])->execute();
|
||||
|
||||
$db->createCommand()->alterColumn('testAlterTable', 'bar', Schema::TYPE_STRING)->execute();
|
||||
|
||||
$db->createCommand()->insert('testAlterTable', ['bar' => 'hello'])->execute();
|
||||
$records = $db->createCommand('SELECT [[id]], [[bar]] FROM {{testAlterTable}};')->queryAll();
|
||||
$this->assertEquals([
|
||||
['id' => 1, 'bar' => 1],
|
||||
['id' => 2, 'bar' => 'hello'],
|
||||
], $records);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
@@ -321,10 +356,6 @@ SQL;
|
||||
{
|
||||
}
|
||||
|
||||
public function testCreateTable()
|
||||
{
|
||||
}
|
||||
|
||||
public function testRenameTable()
|
||||
{
|
||||
}
|
||||
@@ -349,10 +380,6 @@ SQL;
|
||||
{
|
||||
}
|
||||
|
||||
public function testAlterColumn()
|
||||
{
|
||||
}
|
||||
|
||||
public function testAddForeignKey()
|
||||
{
|
||||
}
|
||||
@@ -509,4 +536,23 @@ SQL;
|
||||
$command = $db->createCommand($sql, $params);
|
||||
$this->assertEquals($expectedRawSql, $command->getRawSql());
|
||||
}
|
||||
|
||||
public function testAutoRefreshTableSchema()
|
||||
{
|
||||
$db = $this->getConnection(false);
|
||||
$tableName = 'test';
|
||||
|
||||
$db->createCommand()->createTable($tableName, [
|
||||
'id' => 'pk',
|
||||
'name' => 'string',
|
||||
])->execute();
|
||||
$initialSchema = $db->getSchema()->getTableSchema($tableName);
|
||||
|
||||
$db->createCommand()->addColumn($tableName, 'value', 'integer')->execute();
|
||||
$newSchema = $db->getSchema()->getTableSchema($tableName);
|
||||
$this->assertNotEquals($initialSchema, $newSchema);
|
||||
|
||||
$db->createCommand()->dropTable($tableName)->execute();
|
||||
$this->assertNull($db->getSchema()->getTableSchema($tableName));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +67,23 @@ class SchemaTest extends DatabaseTestCase
|
||||
$this->assertEquals($noCacheTable, $cachedTable);
|
||||
}
|
||||
|
||||
/**
|
||||
* @depends testSchemaCache
|
||||
*/
|
||||
public function testRefreshTableSchema()
|
||||
{
|
||||
/* @var $schema Schema */
|
||||
$schema = $this->getConnection()->schema;
|
||||
|
||||
$schema->db->enableSchemaCache = true;
|
||||
$schema->db->schemaCache = new FileCache();
|
||||
$noCacheTable = $schema->getTableSchema('type', true);
|
||||
|
||||
$schema->refreshTableSchema('type');
|
||||
$refreshedTable = $schema->getTableSchema('type', false);
|
||||
$this->assertFalse($noCacheTable === $refreshedTable);
|
||||
}
|
||||
|
||||
public function testCompositeFk()
|
||||
{
|
||||
/* @var $schema Schema */
|
||||
|
||||
Reference in New Issue
Block a user