Commit 76b3d89d by Carsten Brandt

Merge branch 'master' of github.com:yiisoft/yii2

* 'master' of github.com:yiisoft/yii2: (43 commits) `BaseActiveRecord::findAll()` comment fix Fixes #2913: RBAC `DbManager` is now initialized via migration [NL] Removed app.php [NL] brought translations up to date Fix for comparing numeric attributes in JavaScript Better Gii caption english Fix for comparing numeric attributes in JavaScript HHVM compatibility Fixes for Yii 2 Console Application Rough creation of a doc style guide typo Finished Edits Edited up to Active Record renamed chapter to section [skip ci] Catalan translation Edited up through "I18N" Cleaned Up updated guide toc [skip ci] Update concept-behaviors.md Fixed wrong links [skip ci] Fixed document for multisort in BaseArrayHelper ...
parents c3fe4aa0 00d00a3e
......@@ -45,6 +45,20 @@ class User extends ActiveRecord implements IdentityInterface
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
['role', 'default', 'value' => self::ROLE_USER],
['role', 'in', 'range' => [self::ROLE_USER]],
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
......
......@@ -48,7 +48,7 @@ class SignupForm extends Model
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save(false);
$user->save();
return $user;
}
......
......@@ -5,7 +5,7 @@
*
* In order to run in non-interactive mode:
*
* init --env=dev --overwrite=n
* init --env=Development --overwrite=n
*
* @author Alexander Makarov <sam@rmcreative.ru>
*
......
# Yii Documentation Style Guide
Guidelines to go by when writing or editing any Yii documentation.
*This needs to be expanded.*
## General Style
* Try to use an active voice.
* Use short, declarative sentences.
* Demonstrate ideas using code as much as possible.
* Never use "we". It's the Yii development team or the Yii core team. Better yet to put things in terms of the framework or the guide.
* Use the Oxford comma (e.g., "this, that, and the other" not "this, that and the other").
* Numeric lists should be complete sentences that end with periods (or other punctuation).
* Bullet lists should be fragments that don't end with periods.
## Formatting
## References
* Yii 2.0 or Yii 2 (not Yii2 or Yii2.0)
* Each "page" of the guide is referred to as a "section".
## Capitalizations
* Web, not web
* the guide or this guide, not the Guide
\ No newline at end of file
......@@ -18,11 +18,13 @@ Introduction
Getting Started
---------------
* [Preparing Your Environment](start-environment.md)
* [Creating Your First Yii Application](start-basic.md)
* [Application Structure](start-structure.md)
* [Request Lifecycle](start-lifecycle.md)
* **TBD** [Next Steps](start-next-steps.md)
* [Installing Yii](start-installation.md)
* [Running Applications](start-workflow.md)
* [Saying "Hello World"](start-hello-world.md)
* [Working with Forms](start-forms.md)
* [Working with Databases](start-databases.md)
* [Generating Code with Gii](start-gii.md)
* [Looking Ahead](start-looking-head.md)
Application Structure
......@@ -77,8 +79,8 @@ Working with Databases
* **TBD** [ElasticSearch](db-elastic-search.md)
Getting User Inputs
-------------------
Getting Data from Users
-----------------------
* [Creating Forms](input-forms.md)
* [Input Validation](input-validation.md)
......@@ -86,7 +88,7 @@ Getting User Inputs
* **TBD** [Inputs for Multiple Models](input-multiple-models.md)
Presenting Data
Displaying Data
---------------
* **TBD** [Data Formatting](output-formatting.md)
......@@ -190,7 +192,6 @@ Widgets
* **TBD** [Jquery UI Widgets](jui-widgets.md)
Helpers
-------
......
Bootstrap Widgets
=================
> Note: This chapter is under development.
> Note: This section is under development.
Out of the box, Yii includes support for the [Bootstrap 3](http://getbootstrap.com/) markup and components framework
(also known as "Twitter Bootstrap"). Bootstrap is an excellent, responsive framework that can greatly speed up the
......
Caching
=======
> Note: This chapter is under development.
> Note: This section is under development.
Caching is a cheap and effective way to improve the performance of a web application. By storing relatively
static data in cache and serving it from cache when requested, the application saves the time required to generate the data from scratch. Caching is one of the best ways to improve the performance of your application, almost mandatory on any large-scale site.
......
......@@ -6,7 +6,7 @@ to locate and include required class files. It provides a high-performance class
[PSR-4 standard](https://github.com/php-fig/fig-standards/blob/master/proposed/psr-4-autoloader/psr-4-autoloader.md).
The autoloader is installed when you include the `Yii.php` file.
> Note: For simplicity of description, in this chapter we will only talk about autoloading of classes. However, keep in
> Note: For simplicity of description, in this section we will only talk about autoloading of classes. However, keep in
mind that the content we are describing here applies to autoloading of interfaces and traits as well.
......
......@@ -15,7 +15,7 @@ Using Behaviors
---------------
To use a behavior, you first need to attach it to a [[yii\base\Component|component]]. We will describe how to
attach a behavior in the next section.
attach a behavior in the next subsection.
Once a behavior is attached to a component, its usage is straightforward.
......@@ -129,7 +129,7 @@ $component->attachBehavior('myBehavior3', [
```
You may also attach behaviors through [configurations](concept-configurations.md). For more details, please
refer to the [Configurations](concept-configurations.md#configuration-format) chapter.
refer to the [Configurations](concept-configurations.md#configuration-format) section.
<a name="detaching-behaviors"></a>
......@@ -184,7 +184,7 @@ class MyBehavior extends Behavior
}
```
The above code defines the behavior class `app\components\MyBehavior` which will provides two properties
The above code defines the behavior class `app\components\MyBehavior` which will provide two properties
`prop1` and `prop2`, and one method `foo()` to the component it is attached to. Note that property `prop2`
is defined via the getter `getProp2()` and the setter `setProp2()`. This is so because [[yii\base\Object]]
is an ancestor class of [[yii\base\Behavior]], which supports defining [properties](concept-properties.md) by getters/setters.
......@@ -227,7 +227,7 @@ its handler `beforeValidate()`. When specifying an event handler, you may use on
* an anonymous function.
The signature of an event handler should be as follows, where `$event` refers to the event parameter. Please refer
to the [Events](concept-events.md) chapter for more details about events.
to the [Events](concept-events.md) section for more details about events.
```php
function ($event) {
......
......@@ -58,7 +58,7 @@ where
defined by getters/setters can be configured.
* The `on eventName` elements specify what handlers should be attached to the object [events](concept-events.md).
Notice that the array keys are formed by prefixing event names with `on `. Please refer to
the [Events](concept-events.md) chapter for supported event handler formats.
the [Events](concept-events.md) section for supported event handler formats.
* And the `as behaviorName` elements specify what [behaviors](concept-behaviors.md) should be attached to the object.
Notice that the array keys are formed by prefixing behavior names with `on `. `$behaviorConfig` represents
the configuration for creating a behavior, like a normal configuration as we are describing here.
......@@ -84,8 +84,8 @@ Below is an example showing a configuration with property initial values, event
Using Configurations
--------------------
Configurations are used in many places in Yii. At the beginning of this chapter, we have shown how to use
create an object according to a configuration by using [[Yii::createObject()]]. In this section, we will
Configurations are used in many places in Yii. At the beginning of this section, we have shown how to use
create an object according to a configuration by using [[Yii::createObject()]]. In this subsection, we will
describe application configurations and widget configurations - two major usages of configurations.
......@@ -138,7 +138,7 @@ an [entry script](structure-entry-scripts.md), where the class name is already g
```
For more details about configuring the `components` property of an application can be found
in the [Applications](structure-applications.md) chapter and the [Service Locator](concept-service-locator.md) chapter.
in the [Applications](structure-applications.md) section and the [Service Locator](concept-service-locator.md) section.
<a name="widget-configurations"></a>
......
......@@ -129,7 +129,7 @@ $foo->on(Foo::EVENT_HELLO, function ($event) {
```
You may also attach event handlers through [configurations](concept-configurations.md). For more details, please
refer to the [Configurations](concept-configurations.md#configuration-format) chapter.
refer to the [Configurations](concept-configurations.md#configuration-format) section.
When attaching an event handler, you may provide additional data as the third parameter to [[yii\base\Component::on()]].
......@@ -201,7 +201,7 @@ $foo->off(Foo::EVENT_HELLO);
Class-Level Event Handlers
--------------------------
In the above sections, we have described how to attach a handler to an event at *instance level*.
In the above subsections, we have described how to attach a handler to an event at *instance level*.
Sometimes, you may want to respond to an event triggered by EVERY instance of a class instead of
a specific instance. Instead of attaching an event handler to every instance, you may attach the handler
at *class level* by calling the static method [[yii\base\Event::on()]].
......
Service Locator
===============
> Note: This chapter needs cleanup.
Both service locator and dependency injection are popular design patterns that allow building software
in a loosely-coupled fashion. Yii uses service locator and dependency injection extensively,
even though you may not be aware of them. In this tutorial, we will explore their implementation
and support to help you write code more consciously. We also highly recommend you to read
[Martin's article](http://martinfowler.com/articles/injection.html) to get a deeper understanding of
service locator and dependency injection.
A service locator is an object that knows how to provide all sorts of services (or components) that an application
might need. Within a service locator, each component has only a single instance which is uniquely identified by an ID.
You use the ID to retrieve a component from the service locator. In Yii, a service locator is simply an instance
of [[yii\di\ServiceLocator]] or its child class.
You use the ID to retrieve a component from the service locator.
In Yii, a service locator is simply an instance of [[yii\di\ServiceLocator]] or its child class.
The most commonly used service locator in Yii is the *application* object which can be accessed through
`\Yii::$app`. The services it provides are called *application components*, such as `request`, `response`,
`urlManager`. You may configure these components or replace them with your own implementations easily
through functionality provided the service locator.
`\Yii::$app`. The services it provides are called *application components*, such as the `request`, `response`,
`urlManager` components. You may configure these components or even replace them with your own implementations easily
through functionality provided by the service locator.
Besides the application object, each module object is also a service locator.
......@@ -26,7 +18,10 @@ To use a service locator, the first step is to register components. A component
via [[yii\di\ServiceLocator::set()]]. The following code shows different ways of registering components:
```php
$locator = new \yii\di\ServiceLocator;
use yii\di\ServiceLocator;
use yii\caching\FileCache;
$locator = new ServiceLocator;
// register "cache" using a class name that can be used to create a component
$locator->set('cache', 'yii\caching\ApcCache');
......@@ -43,6 +38,9 @@ $locator->set('db', [
$locator->set('search', function () {
return new app\components\SolrService;
});
// register "pageCache" using a component
$locator->set('pageCache', new FileCache);
```
Once a component is registered, you can access it using its ID in one of the following two ways:
......@@ -62,11 +60,10 @@ You may use [[yii\di\ServiceLocator::has()]] to check if a component ID has alre
If you call [[yii\di\ServiceLocator::get()]] with an invalid ID, an exception will be thrown.
Because service locators are often being configured using configuration arrays, a method named
[[yii\di\ServiceLocator::setComponents()]] is provided to allow registering components in configuration arrays.
The method is a setter which defines a writable property `components` that can be configured.
The following code shows a configuration array that can be used to configure an application and register
the "db", "cache" and "search" components:
Because service locators are often being created with [configurations](concept-configurations.md),
a writable property named [[yii\di\ServiceLocator::setComponents()|components]] is provided so that
you can configure it and register multiple components at once. The following code shows a configuration array
that can be used to configure an application and register the "db", "cache" and "search" components:
```php
return [
......
Active Record
=============
> Note: This chapter is under development.
> Note: This section is under development.
[Active Record](http://en.wikipedia.org/wiki/Active_record_pattern) provides an object-oriented interface
for accessing data stored in a database. An Active Record class is associated with a database table,
......
Database basics
===============
> Note: This chapter is under development.
> Note: This section is under development.
Yii has a database access layer built on top of PHP's [PDO](http://www.php.net/manual/en/book.pdo.php). It provides
uniform API and solves some inconsistencies between different DBMS. By default Yii supports the following DBMS:
......@@ -182,7 +182,7 @@ Quoting table and column names
Most of the time you would use the following syntax for quoting table and column names:
```php
$sql = "SELECT COUNT([[$column]]) FROM {{$table}}";
$sql = "SELECT COUNT([[$column]]) FROM {{table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
```
......@@ -192,7 +192,7 @@ quoted table name.
For table names there's a special variant `{{%Y}}` that allows you to automatically appending table prefix if it is set:
```php
$sql = "SELECT COUNT([[$column]]) FROM {{%$table}}";
$sql = "SELECT COUNT([[$column]]) FROM {{%table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
```
......
Database Migration
==================
> Note: This chapter is under development.
> Note: This section is under development.
Like source code, the structure of a database evolves as a database-driven application is developed and maintained. For example, during development, a new table may be added; Or, after the application goes live, it may be discovered that an additional index is required. It is important to keep track of these structural database changes (called **migration**), just as changes to the source code is tracked using version control. If the source code and the database become out of sync, bugs will occur, or the whole application might break. For this reason, Yii provides a database migration
tool that can keep track of database migration history, apply new migrations, or revert existing ones.
......
Query Builder and Query
=======================
> Note: This chapter is under development.
> Note: This section is under development.
Yii provides a basic database access layer as described in the [Database basics](database-basics.md) section.
The database access layer provides a low-level way to interact with the database. While useful in some situations,
......
Extending Yii
=============
> Note: This chapter is under development.
> Note: This section is under development.
The Yii framework was designed to be easily extendable. Additional features can be added to your project and then reused, either by yourself on other projects or by sharing your work as a formal Yii extension.
......
Helper Classes
==============
> Note: This chapter is under development.
> Note: This section is under development.
Yii provides many classes that help simplify common coding tasks, such as string or array manipulations,
HTML code generation, and so forth. These helper classes are organized under the `yii\helpers` namespace and
......
Composer
========
> Note: This chapter is under development.
> Note: This section is under development.
Yii2 uses Composer as its dependency management tool. Composer is a PHP utility that can automatically handle the installation of needed libraries and
extensions, thereby keeping those third-party resources up to date while absolving you of the need to manually manage the project's dependencies.
......
Using 3rd-Party Libraries
=========================
> Note: This chapter is under development.
> Note: This section is under development.
Yii is carefully designed so that third-party libraries can be
easily integrated to further extend Yii's functionalities.
......
Helpers
=======
> Note: This chapter is under development.
> Note: This section is under development.
Helper classes typically contain static methods only and are used as follows:
......
Working with forms
==================
> Note: This chapter is under development.
> Note: This section is under development.
The primary way of using forms in Yii is through [[yii\widgets\ActiveForm]]. This approach should be preferred when
the form is based upon a model. Additionally, there are some useful methods in [[yii\helpers\Html]] that are typically
......
Model validation reference
==========================
> Note: This chapter is under development.
> Note: This section is under development.
As a model both represents data and defines the business rules to which that data must adhere, comprehending data validation is key to using Yii. In order to learn model validation basics, please refer to [Model, Validation subsection](model.md#Validation).
......
......@@ -2,8 +2,8 @@ What is Yii
===========
Yii is a high performance, component-based PHP framework for rapidly developing modern Web applications.
The name Yii (pronounced `Yee` or `[ji:]`) means simple and evolutionary in Chinese. It can also
be considered as the acronym for **Yes It Is**!
The name Yii (pronounced `Yee` or `[ji:]`) means "simple and evolutionary" in Chinese. It can also
be thought of as an acronym for **Yes It Is**!
What is Yii Best for?
......@@ -22,17 +22,17 @@ How does Yii Compare with Other Frameworks?
organization based on this pattern.
- Yii takes the philosophy that code should be written in a simple yet elegant way. It will never try to
over-design things mainly for the purpose of following some design pattern.
- Yii is a full-stack framework providing many proven and ready-to-use features, such as query builders
and ActiveRecord supporting relational and NoSQL databases, RESTful API development support, multi-tier
caching support, etc.
- Yii is a full-stack framework providing many proven and ready-to-use features, such as: query builders
and ActiveRecord, for both relational and NoSQL databases; RESTful API development support; multi-tier
caching support; and more.
- Yii is extremely extensible. You can customize or replace nearly every piece of core code. You can also
take advantage of its solid extension architecture, use or develop redistributable extensions.
take advantage of its solid extension architecture, to use or develop redistributable extensions.
- High performance is always a primary goal of Yii.
Yii is not a one-man show, it is backed up by a [strong core developer team][] as well as a large community
with many professionals who are constantly contributing to the development of Yii. The Yii developer team
is keeping a close eye on the latest trends of Web development and the best practices and features
found in other frameworks and projects. They are being carefully incorporated into the core framework and exposed
with many professionals constantly contributing to the development of Yii. The Yii developer team
keeps a close eye on the latest trends of Web development, and on the best practices and features
found in other frameworks and projects. The most relevant best practices and features found elsewhere are regularly incorporated into the core framework and exposed
via simple and elegant interfaces.
[strong core developer team]: http://www.yiiframework.com/about/
......@@ -40,9 +40,8 @@ via simple and elegant interfaces.
Yii Versions
------------
Yii has two major versions available currently: 1.1 and 2.0. Version 1.1 is the old generation and is
currently under maintenance mode. Version 2.0 is a complete rewrite of Yii by adopting the latest
technologies and protocols, such as Composer, PSR, namespaces, traits, etc. Version 2.0 represents the latest
Yii currently has two major versions available: 1.1 and 2.0. Version 1.1 is the old generation and is now in maintenance mode. Version 2.0 is a complete rewrite of Yii, adopting the latest
technologies and protocols, including Composer, PSR, namespaces, traits, and so forth. Version 2.0 represents the latest
generation of the framework and will receive our main development efforts in the next few years.
This guide is mainly about version 2.0.
......@@ -50,11 +49,10 @@ This guide is mainly about version 2.0.
Requirements and Prerequisites
------------------------------
Yii 2.0 requires PHP 5.4.0 or above. You may find out more detailed requirements for individual features
by running the requirement checker included in every release.
Yii 2.0 requires PHP 5.4.0 or above. You can find more detailed requirements for individual features
by running the requirement checker included in every Yii release.
Using Yii requires basic knowledge about object-oriented programming (OOP), as Yii is a pure OOP-based framework.
Yii 2.0 also makes use of the latest features of PHP, such as [namespaces](http://www.php.net/manual/en/language.namespaces.php),
[traits](http://www.php.net/manual/en/language.oop5.traits.php). Understanding these concepts will help
you pick up Yii 2.0 more easily.
Yii 2.0 also makes use of the latest features of PHP, such as [namespaces](http://www.php.net/manual/en/language.namespaces.php) and [traits](http://www.php.net/manual/en/language.oop5.traits.php). Understanding these concepts will help
you more easily pick up Yii 2.0.
Managing assets
===============
> Note: This chapter is under development.
> Note: This section is under development.
An asset in Yii is a file that is included into the page. It could be CSS, JavaScript or
any other file. The framework provides many ways to work with assets from basics such as adding `<script src="...">` tags
......
Data providers
==============
> Note: This chapter is under development.
> Note: This section is under development.
Data provider abstracts data set via [[yii\data\DataProviderInterface]] and handles pagination and sorting.
It can be used by [grids](data-grid.md), [lists and other data widgets](data-widgets.md).
......
Data widgets
============
> Note: This chapter is under development.
> Note: This section is under development.
ListView
--------
......
Implementing RESTful Web Service APIs
=====================================
> Note: This chapter is under development.
> Note: This section is under development.
Yii provides a whole set of tools to greatly simplify the task of implementing RESTful Web Service APIs.
In particular, Yii provides support for the following aspects regarding RESTful APIs:
......@@ -315,7 +315,7 @@ For API endpoints about resource collections, pagination is supported out-of-box
through query parameters `page` and `per-page`, an API consumer may specify which page of data
to return and how many data items should be included in each page. The corresponding response
will include the pagination information by the following HTTP headers (please also refer to the first example
in this chapter):
in this section):
* `X-Pagination-Total-Count`: The total number of data items;
* `X-Pagination-Page-Count`: The number of pages;
......@@ -701,7 +701,7 @@ Authorization
After a user is authenticated, you probably want to check if he has the permission to perform the requested
action for the requested resource. This process is called *authorization* which is covered in detail in
the [Authorization chapter](authorization.md).
the [Authorization section](authorization.md).
You may use the Role-Based Access Control (RBAC) component to implementation authorization.
......
URL Management
==============
> Note: This chapter is under development.
> Note: This section is under development.
The concept of URL management in Yii is fairly simple. URL management is based on the premise that the application uses
internal routes and parameters everywhere. The framework itself will then translate routes into URLs, and vice versa, according to the URL manager's configuration. This approach allows you to change site-wide URLs merely by
......
Authentication
==============
> Note: This chapter is under development.
> Note: This section is under development.
Authentication is the act of verifying who a user is, and is the basis of the login process. Typically, authentication uses the combination of an identifier--a username or email address--and a password. The user submits these values through a form, and the application then compares the submitted information against that previously stored (e.g., upon registration).
In Yii, this entire process is performed semi-automatically, leaving the developer to merely implement [[yii\web\IdentityInterface]], the most important class in the authentication system. Typically, implementation of `IdentityInterface` is accomplished using the `User` model.
You can find a fully featured example of authentication in the
[advanced application template](installation.md). Below, only the interface methods are listed:
[advanced application template](tutorial-advanced-app.md). Below, only the interface methods are listed:
```php
class User extends ActiveRecord implements IdentityInterface
......
Authorization
=============
> Note: This chapter is under development.
> Note: This section is under development.
Authorization is the process of verifying that a user has enough permission to do something. Yii provides two authorization
methods: Access Control Filter (ACF) and Role-Based Access Control (RBAC).
......
Security
========
> Note: This chapter is under development.
> Note: This section is under development.
Good security is vital to the health and success of any application. Unfortunately, many developers cut corners when it comes to security, either due to a lack of understanding or because implementation is too much of a hurdle. To make your Yii powered application as secure as possible, Yii has included several excellent and easy to use security features.
......
Basic application template
==========================
> Note: This chapter is under development.
> Note: This section is under development.
The basic Yii application template is a perfect fit for small projects or when you're just learning the framework.
......
Installation
============
> Note: This chapter is under development.
> Note: This section is under development.
There are two ways you can install the Yii framework:
......
Request Lifecycle
=================
> Note: This chapter is under development.
> Note: This section is under development.
The following diagram shows a typical workflow of a Yii application handling a user request:
......
Application Structure
=====================
> Note: This chapter is under development.
> Note: This section is under development.
Yii implements the model-view-controller (MVC) design pattern, which is
widely adopted in Web and other application programming. MVC aims to separate business logic from
......
Controller
==========
> Note: This chapter is under development.
> Note: This section is under development.
Controller is one of the key parts of the application. It determines how to handle incoming request and creates a response.
......
Entry Scripts
=============
> Note: This chapter is under development.
> Note: This section is under development.
Configuring options in the bootstrap file
-----------------------------------------
......
Model
=====
> Note: This chapter is under development.
> Note: This section is under development.
In keeping with the MVC approach, a model in Yii is intended for storing or temporarily representing application data, as well as defining the busines rules by which the data must abide.
......
View
====
> Note: This chapter is under development.
> Note: This section is under development.
The view component is an important part of MVC. The view acts as the interface to the application, making it responsible
for presenting data to end users, displaying forms, and so forth.
......
Fixtures
========
> Note: This chapter is under development.
> Note: This section is under development.
Fixtures are important part of testing. Their main purpose is to set up the environment in a fixed/known state
so that your tests are repeatable and run in an expected way. Yii provides a fixture framework that allows
......
Debug toolbar and debugger
==========================
> Note: This chapter is under development.
> Note: This section is under development.
Yii2 includes a handy toolbar, and built-in debugger, for faster development and debugging of your applications. The toolbar displays information
about the currently opened page, while the debugger can be used to analyze data you've previously collected (i.e., to confirm the values of variables).
......
The Gii code generation tool
============================
> Note: This chapter is under development.
> Note: This section is under development.
Yii includes a handy tool, named Gii, that provides rapid prototyping by generating commonly used code snippets
as well as complete CRUD controllers.
......
Advanced application template
=============================
> Note: This chapter is under development.
> Note: This section is under development.
This template is for large projects developed in teams where the backend is divided from the frontend, application is deployed
to multiple servers etc. This application template also goes a bit further regarding features and provides essential
......@@ -74,16 +74,20 @@ Root directory contains a set of files.
Predefined path aliases
-----------------------
- @yii - framework directory.
- @app - base path of currently running application.
- @common - common directory.
- @frontend - frontend web application directory.
- @backend - backend web application directory.
- @console - console directory.
- @runtime - runtime directory of currently running web application.
- @vendor - Composer vendor directory.
- @web - base URL of currently running web application.
- @webroot - web root directory of currently running web application.
- `@yii` - framework directory.
- `@app` - base path of currently running application.
- `@common` - common directory.
- `@frontend` - frontend web application directory.
- `@backend` - backend web application directory.
- `@console` - console directory.
- `@runtime` - runtime directory of currently running web application.
- `@vendor` - Composer vendor directory.
- `@web` - base URL of currently running web application.
- `@webroot` - web root directory of currently running web application.
The aliases specific to the directory structure of the advanced application
(`@common`, `@frontend`, `@backend`, and `@console`) are defined in `common/config/aliases.php`.
Applications
------------
......
Console applications
====================
> Note: This chapter is under development.
> Note: This section is under development.
Yii has full featured support for console applications, whose structure is very similar to a Yii web application. A console application
consists of one or more [[yii\console\Controller]] classes, which are often referred to as "commands" in the console environment. Each controller can also have one or more actions, just like web controllers.
......
Error Handling
==============
> Note: This chapter is under development.
> Note: This section is under development.
Error handling in Yii is different than handling errors in plain PHP. First of all, Yii will convert all non-fatal errors
to *exceptions*:
......
Internationalization
====================
> Note: This chapter is under development.
> Note: This section is under development.
Internationalization (I18N) refers to the process of designing a software application so that it can be adapted to
various languages and regions without engineering changes. For Web applications, this is of particular importance
......
Logging
=======
> Note: This chapter is under development.
> Note: This section is under development.
Yii provides flexible and extensible logger that is able to handle messages according to severity level or their type.
You may filter messages by multiple criteria and forward them to files, email, debugger etc.
......
Performance Tuning
==================
> Note: This chapter is under development.
> Note: This section is under development.
The performance of your web application is based upon two parts. First is the framework performance
and the second is the application itself. Yii has a pretty low performance impact
......
Creating your own Application structure
=======================================
> Note: This chapter is under development.
> Note: This section is under development.
While [basic](apps-basic.md) and [advanced](apps-advanced.md) application templates are great for most of your needs
you may want to create your own application template to start your projects with.
......
Using template engines
======================
> Note: This chapter is under development.
> Note: This section is under development.
By default, Yii uses PHP as its template language, but you can configure Yii to support other rendering engines, such as
[Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/).
......@@ -44,36 +44,65 @@ That code would be added to the `require` section of `composer.json`. After maki
Twig
----
To use Twig, you need to create templates in files that have the `.twig` extension (or use another file extension but configure the component accordingly).
Unlike standard view files, when using Twig you must include the extension in your `$this->render()`
or `$this->renderPartial()` controller calls:
To use Twig, you need to create templates in files that have the `.twig` extension (or use another file extension but
configure the component accordingly). Unlike standard view files, when using Twig you must include the extension
in your `$this->render()` or `$this->renderPartial()` controller calls:
```php
echo $this->render('renderer.twig', ['username' => 'Alex']);
```
### Additional syntax
### Template syntax
Yii adds some extra syntax constructs additionally to standard Twig ones.
The best resource to learn Twig basics is its official documentation you can find at
[twig.sensiolabs.org](http://twig.sensiolabs.org/documentation). Additionally there are Yii-specific addtions
described below.
#### Method and function calls
###
If you need result you can call a method or a function using the following syntax:
{{registerAssetBundle('AppAsset')}} - Registers asset bundle of a given name
```
{% set result = my_function({'a' : 'b'}) %}
{% set result = myObject.my_function({'a' : 'b'}) %}
```
If you need to echo result instead of assigning it to a variable:
### Forms
```
{{ my_function({'a' : 'b'}) }}
{{ myObject.my_function({'a' : 'b'}) }}
```
In case you don't need result you shoud use `void` wrapper:
```
{% set form = form_begin({ ... }) %}
{{ form.field(...) }}
{% form.end() %}
{{ void(my_function({'a' : 'b'})) }}
{{ void(myObject.my_function({'a' : 'b'})} }}
```
#### Forms
#### Getting URL for a route
There are two form helper functions `form_begin` and `form_end` to make using forms more convenient:
There are two functions you can use for URLs:
```
{% set form = form_begin({
'id' : 'login-form',
'options' : {'class' : 'form-horizontal'},
}) %}
{{ form.field(model, 'username') | raw }}
{{ form.field(model, 'password').passwordInput() | raw }}
<div class="form-group">
<input type="submit" value="Login" class="btn btn-primary" />
</div>
{{ form_end() }}
```
#### URLs
There are two functions you can use for building URLs:
```php
<a href="{{ path('blog/view', {'alias' : post.alias}) }}">{{ post.title }}</a>
......@@ -82,22 +111,28 @@ There are two functions you can use for URLs:
`path` generates relative URL while `url` generates absolute one. Internally both are using [[\yii\helpers\Url]].
### Additional variables
#### Additional variables
Within Twig templates, you can also make use of these variables:
Within Twig templates the following variables are always defined:
- `app`, which equates to `\Yii::$app`
- `this`, which equates to the current `View` object
### Globals
### Additional configuration
Yii Twig extension allows you to define your own syntax and bring regular helper classes into templates. Let's review
configuration options.
You can add global helpers or values via the application configuration's `globals` variable. You can define both Yii helpers and your own
variables there:
#### Globals
You can add global helpers or values via the application configuration's `globals` variable. You can define both Yii
helpers and your own variables there:
```php
'globals' => [
'html' => '\yii\helpers\Html',
'name' => 'Carsten',
'GridView' => '\yii\grid\GridView',
],
```
......@@ -105,9 +140,29 @@ Once configured, in your template you can use the globals in the following way:
```
Hello, {{name}}! {{ html.a('Please login', 'site/login') | raw }}.
{{ GridView.widget({'dataProvider' : provider}) | raw }}
```
#### Functions
You can define additional functions like the following:
```php
'functions' => [
'rot13' => 'str_rot13',
'truncate' => '\yii\helpers\StringHelper::truncate',
],
```
In template they could be used like the following:
```
`{{ rot13('test') }}`
`{{ truncate(post.text, 100) }}`
```
### Additional filters
#### Filters
Additional filters may be added via the application configuration's `filters` option:
......@@ -117,7 +172,7 @@ Additional filters may be added via the application configuration's `filters` op
],
```
Then in the template you can use:
Then in the template you can apply filter using the following syntax:
```
{{ model|jsonEncode }}
......
Theming
=======
> Note: This chapter is under development.
> Note: This section is under development.
A theme is a directory of view and layout files. Each file of the theme overrides corresponding file of an application
when rendered. A single application may use multiple themes and each may provide totally different experience. At any
......
......@@ -139,7 +139,6 @@ class Foo
### 4.5 Constructors
- `__construct` should be used instead of PHP 4 style constructors.
- When instantiating class it should be `new MyClass();` instead of `new MyClass;`.
## 5 PHP
......
......@@ -11,13 +11,13 @@ use yii\helpers\Html;
use yii\helpers\ArrayHelper;
/**
* A Bootstrap 3 enhanced version of [[yii\widgets\ActiveField]].
* A Bootstrap 3 enhanced version of [[\yii\widgets\ActiveField]].
*
* This class adds some useful features to [[yii\widgets\ActiveField|ActiveField]] to render all
* This class adds some useful features to [[\yii\widgets\ActiveField|ActiveField]] to render all
* sorts of Bootstrap 3 form fields in different form layouts:
*
* - [[inputTemplate]] is an optional template to render complex inputs, for example input groups
* - [[horizontalClass]] defines the CSS grid classes to add to label, wrapper, error and hint
* - [[horizontalCssClasses]] defines the CSS grid classes to add to label, wrapper, error and hint
* in horizontal forms
* - [[inline]]/[[inline()]] is used to render inline [[checkboxList()]] and [[radioList()]]
* - [[enableError]] can be set to `false` to disable to the error
......
......@@ -12,7 +12,7 @@ use yii\helpers\Html;
use yii\base\InvalidConfigException;
/**
* A Bootstrap 3 enhanced version of [[yii\widgets\ActiveForm]].
* A Bootstrap 3 enhanced version of [[\yii\widgets\ActiveForm]].
*
* This class mainly adds the [[layout]] property to choose a Bootstrap 3 form layout.
* So for example to render a horizontal form you would:
......
......@@ -6,6 +6,7 @@ Yii Framework 2 gii extension Change Log
- Bug #1263: Fixed the issue that Gii and Debug modules might be affected by incompatible asset manager configuration (qiangxue)
- Bug #3265: Fixed incorrect controller class name validation (suralc)
- Enh #2018: Search model is not required anymore in CRUD generator (johonunu)
- Enh #3088: The gii module will manage their own URL rules now (qiangxue)
- Enh #3222: Added `useTablePrefix` option to the model generator for Gii (horizons2)
......
......@@ -35,7 +35,7 @@ class Generator extends \yii\gii\Generator
public $controllerClass;
public $baseControllerClass = 'yii\web\Controller';
public $indexWidgetType = 'grid';
public $searchModelClass;
public $searchModelClass = '';
/**
* @inheritdoc
......@@ -61,7 +61,7 @@ class Generator extends \yii\gii\Generator
{
return array_merge(parent::rules(), [
[['moduleID', 'controllerClass', 'modelClass', 'searchModelClass', 'baseControllerClass'], 'filter', 'filter' => 'trim'],
[['modelClass', 'searchModelClass', 'controllerClass', 'baseControllerClass', 'indexWidgetType'], 'required'],
[['modelClass', 'controllerClass', 'baseControllerClass', 'indexWidgetType'], 'required'],
[['searchModelClass'], 'compare', 'compareAttribute' => 'modelClass', 'operator' => '!==', 'message' => 'Search Model Class must not be equal to Model Class.'],
[['modelClass', 'controllerClass', 'baseControllerClass', 'searchModelClass'], 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'],
[['modelClass'], 'validateClass', 'params' => ['extends' => BaseActiveRecord::className()]],
......@@ -162,15 +162,22 @@ class Generator extends \yii\gii\Generator
public function generate()
{
$controllerFile = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\')) . '.php');
$searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php'));
$files = [
new CodeFile($controllerFile, $this->render('controller.php')),
new CodeFile($searchModel, $this->render('search.php')),
];
if (!empty($this->searchModelClass)) {
$searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php'));
$files[] = new CodeFile($searchModel, $this->render('search.php'));
}
$viewPath = $this->getViewPath();
$templatePath = $this->getTemplatePath() . '/views';
foreach (scandir($templatePath) as $file) {
if (empty($this->searchModelClass) && $file === '_search.php') {
continue;
}
if (is_file($templatePath . '/' . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
$files[] = new CodeFile("$viewPath/$file", $this->render("views/$file"));
}
......@@ -438,7 +445,7 @@ class Generator extends \yii\gii\Generator
if (is_subclass_of($class, 'yii\mongodb\ActiveRecord')) {
return "'id' => (string)\$model->{$pks[0]}";
} else {
return "'id' => \$model->{$pks[0]}";
return "'id' => \$model->{$pks[0]}";
}
} else {
$params = [];
......@@ -446,7 +453,7 @@ class Generator extends \yii\gii\Generator
if (is_subclass_of($class, 'yii\mongodb\ActiveRecord')) {
$params[] = "'$pk' => (string)\$model->$pk";
} else {
$params[] = "'$pk' => \$model->$pk";
$params[] = "'$pk' => \$model->$pk";
}
}
......
......@@ -31,7 +31,11 @@ namespace <?= StringHelper::dirname(ltrim($generator->controllerClass, '\\')) ?>
use Yii;
use <?= ltrim($generator->modelClass, '\\') ?>;
<?php if (!empty($generator->searchModelClass)): ?>
use <?= ltrim($generator->searchModelClass, '\\') . (isset($searchModelAlias) ? " as $searchModelAlias" : "") ?>;
<?php else: ?>
use yii\data\ActiveDataProvider;
<?php endif; ?>
use <?= ltrim($generator->baseControllerClass, '\\') ?>;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
......@@ -59,6 +63,7 @@ class <?= $controllerClass ?> extends <?= StringHelper::basename($generator->bas
*/
public function actionIndex()
{
<?php if (!empty($generator->searchModelClass)): ?>
$searchModel = new <?= isset($searchModelAlias) ? $searchModelAlias : $searchModelClass ?>;
$dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());
......@@ -66,6 +71,15 @@ class <?= $controllerClass ?> extends <?= StringHelper::basename($generator->bas
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
<?php else: ?>
$dataProvider = new ActiveDataProvider([
'query' => <?= $modelClass ?>::find(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
<?php endif; ?>
}
/**
......
......@@ -20,7 +20,7 @@ use <?= $generator->indexWidgetType === 'grid' ? "yii\\grid\\GridView" : "yii\\w
/**
* @var yii\web\View $this
* @var yii\data\ActiveDataProvider $dataProvider
* @var <?= ltrim($generator->searchModelClass, '\\') ?> $searchModel
<?= !empty($generator->searchModelClass) ? " * @var " . ltrim($generator->searchModelClass, '\\') . " \$searchModel\n" : '' ?>
*/
$this->title = <?= $generator->generateString(Inflector::pluralize(Inflector::camel2words(StringHelper::basename($generator->modelClass)))) ?>;
......@@ -29,8 +29,9 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="<?= Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-index">
<h1><?= "<?= " ?>Html::encode($this->title) ?></h1>
<?= "<?php " . ($generator->indexWidgetType === 'grid' ? "// " : "") ?>echo $this->render('_search', ['model' => $searchModel]); ?>
<?php if(!empty($generator->searchModelClass)): ?>
<?= " <?php " . ($generator->indexWidgetType === 'grid' ? "// " : "") ?>echo $this->render('_search', ['model' => $searchModel]); ?>
<?php endif; ?>
<p>
<?= "<?= " ?>Html::a(<?= $generator->generateString('Create {modelClass}', ['modelClass' => Inflector::camel2words(StringHelper::basename($generator->modelClass))]) ?>, ['create'], ['class' => 'btn btn-success']) ?>
......@@ -39,8 +40,7 @@ $this->params['breadcrumbs'][] = $this->title;
<?php if ($generator->indexWidgetType === 'grid'): ?>
<?= "<?= " ?>GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
<?= !empty($generator->searchModelClass) ? "'filterModel' => \$searchModel,\n 'columns' => [\n" : "'columns' => [\n"; ?>
['class' => 'yii\grid\SerialColumn'],
<?php
......
......@@ -112,7 +112,7 @@ class Generator extends \yii\gii\Generator
return [
'vendorName' => 'This refers to the name of the publisher, your GitHub user name is usually a good choice, eg. <code>myself</code>.',
'packageName' => 'This is the name of the extension on packagist, eg. <code>yii2-foobar</code>.',
'namespace' => 'PSR-4, eg. <code>myself\foobar\</code> This will be added to your autoloading by composer. Do not use yii or yii2 in the namespace.',
'namespace' => 'PSR-4, eg. <code>myself\foobar\</code> This will be added to your autoloading by composer. Do not use yii, yii2 or yiisoft in the namespace.',
'keywords' => 'Comma separated keywords for this extension.',
'outputPath' => 'The temporary location of the generated files.',
'title' => 'A more descriptive name of your application for the README file.',
......
......@@ -11,7 +11,7 @@ $this->title = 'Welcome to Gii';
?>
<div class="default-index">
<div class="page-header">
<h1>Welcome to Gii <small>a magic tool that can write code for you</small></h1>
<h1>Welcome to Gii <small>a magical tool that can write code for you</small></h1>
</div>
<p class="lead">Start the fun with the following code generators:</p>
......
......@@ -39,7 +39,7 @@ use yii\helpers\Html;
* 'label' => 'Ajax tab',
* 'url' => ['ajax/content'],
* ],
* ),
* ],
* 'options' => ['tag' => 'div'],
* 'itemOptions' => ['tag' => 'div'],
* 'headerOptions' => ['class' => 'my-class'],
......
......@@ -5,6 +5,7 @@ Yii Framework 2 twig extension Change Log
--------------------------
- Bug #2925: Fixed throwing exception when accessing AR property with null value (samdark)
- Enh #1799: Added `form_begin`, `form_end` to twig extension (samdark)
2.0.0-beta April 13, 2014
......
......@@ -7,19 +7,20 @@ To use this extension, simply add the following code in your application configu
```php
return [
//....
'components' => [
'view' => [
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
//'cachePath' => '@runtime/Twig/cache',
//'options' => [], /* Array of twig options */
// ... see ViewRenderer for more options
],
],
],
],
//....
'components' => [
'view' => [
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
// set cachePath to false in order to disable template caching
//'cachePath' => '@runtime/Twig/cache',
//'options' => [], /* Array of twig options */
// ... see ViewRenderer for more options
],
],
],
],
];
```
......
......@@ -11,6 +11,7 @@ use Yii;
use yii\base\View;
use yii\base\ViewRenderer as BaseViewRenderer;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
/**
* TwigViewRenderer allows you to use Twig templates in views.
......@@ -115,11 +116,6 @@ class ViewRenderer extends BaseViewRenderer
$this->setLexerOptions($this->lexerOptions);
}
// $this->addFunctions([
// 'rot13' => 'str_rot13',
// 'jsonEncode' => '\yii\helpers\Json::encode',
// ]);
// Adding global 'void' function (usage: {{void(App.clientScript.registerScriptFile(...))}})
$this->twig->addFunction('void', new \Twig_Function_Function(function ($argument) {
}));
......@@ -132,6 +128,14 @@ class ViewRenderer extends BaseViewRenderer
return Url::to(array_merge([$path], $args), true);
}));
$this->twig->addFunction('form_begin', new \Twig_Function_Function(function ($args = []) {
return ActiveForm::begin($args);
}));
$this->twig->addFunction('form_end', new \Twig_Function_Function(function () {
ActiveForm::end();
}));
$this->twig->addGlobal('app', \Yii::$app);
}
......
......@@ -23,6 +23,8 @@ Yii Framework 2 Change Log
- Bug #3236: Return value for DateTime->format('U') casted to double to allow correct date formatting (pgaultier)
- Bug #3268: Fixed the bug that the schema name in a table name was not respected by `yii\db\mysql\Schema` (terazoid, qiangxue)
- Bug #3311: Fixed the bug that `yii\di\Container::has()` did not return correct value (mgrechanik, qiangxue)
- Bug #3327: Fixed "Unable to find debug data" when logging objects with circular references (jarekkozak, samdark)
- Bug #3368: Fix for comparing numeric attributes in JavaScript (technixp)
- Enh #2264: `CookieCollection::has()` will return false for expired or removed cookies (qiangxue)
- Enh #2837: Error page now shows arguments in stack trace method calls (samdark)
- Enh #2906: Added support for using conditional comments for js and css files registered through asset bundles and Html helper (exromany, qiangxue)
......@@ -42,6 +44,7 @@ Yii Framework 2 Change Log
- Enh: Supported adding a new response formatter without the need to reconfigure existing formatters (qiangxue)
- Enh: Added `yii\web\UrlManager::addRules()` to simplify adding new URL rules (qiangxue)
- Enh: Added support to insert an event handler at the beginning of class-level event handler queue (qiangxue)
- Chg #2913: RBAC `DbManager` is now initialized via migration (samdark)
- Chg #3036: Upgraded Twitter Bootstrap to 3.1.x (qiangxue)
- Chg #3175: InvalidCallException, InvalidParamException, UnknownMethodException are now extended from SPL BadMethodCallException (samdark)
- Chg: Replaced `clearAll()` and `clearAllAssignments()` in `yii\rbac\ManagerInterface` with `removeAll()`, `removeAllRoles()`, `removeAllPermissions()`, `removeAllRules()` and `removeAllAssignments()` (qiangxue)
......
......@@ -203,16 +203,16 @@ yii.validation = (function ($) {
valid = value !== compareValue;
break;
case '>':
valid = value > compareValue;
valid = value > parseFloat(compareValue);
break;
case '>=':
valid = value >= compareValue;
valid = value >= parseFloat(compareValue);
break;
case '<':
valid = value < compareValue;
valid = value < parseFloat(compareValue);
break;
case '<=':
valid = value <= compareValue;
valid = value <= parseFloat(compareValue);
break;
default:
valid = false;
......
......@@ -49,7 +49,7 @@ class Controller extends \yii\base\Controller
* @param resource $stream the stream to check.
* @return boolean Whether to enable ANSI style in output.
*/
public function isColorEnabled($stream = STDOUT)
public function isColorEnabled($stream = \STDOUT)
{
return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
}
......@@ -192,13 +192,13 @@ class Controller extends \yii\base\Controller
*/
public function stderr($string)
{
if ($this->isColorEnabled(STDERR)) {
if ($this->isColorEnabled(\STDERR)) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return fwrite(STDERR, $string);
return fwrite(\STDERR, $string);
}
/**
......
......@@ -64,7 +64,7 @@ class ErrorHandler extends \yii\base\ErrorHandler
*/
protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
{
$stream = (PHP_SAPI === 'cli') ? STDERR : STDOUT;
$stream = (PHP_SAPI === 'cli') ? \STDERR : \STDOUT;
// try controller first to allow check for --color switch
if (Yii::$app->controller instanceof \yii\console\Controller && Yii::$app->controller->isColorEnabled($stream)
|| Yii::$app instanceof \yii\console\Application && Console::streamSupportsAnsiColors($stream)) {
......
......@@ -114,7 +114,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
/**
* @inheritdoc
* @return static[]|array an array of ActiveRecord instance, or an empty array if nothing matches.
* @return static[] an array of ActiveRecord instance, or an empty array if nothing matches.
*/
public static function findAll($condition)
{
......
......@@ -401,7 +401,7 @@ class BaseArrayHelper
* `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
* Please refer to [PHP manual](http://php.net/manual/en/function.sort.php)
* for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
* @throws InvalidParamException if the $descending or $sortFlag parameters do not have
* @throws InvalidParamException if the $direction or $sortFlag parameters do not have
* correct number of elements as that of $key.
*/
public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
......@@ -414,7 +414,7 @@ class BaseArrayHelper
if (is_scalar($direction)) {
$direction = array_fill(0, $n, $direction);
} elseif (count($direction) !== $n) {
throw new InvalidParamException('The length of $descending parameter must be the same as that of $keys.');
throw new InvalidParamException('The length of $direction parameter must be the same as that of $keys.');
}
if (is_scalar($sortFlag)) {
$sortFlag = array_fill(0, $n, $sortFlag);
......
......@@ -628,7 +628,7 @@ class BaseConsole
*/
public static function stdin($raw = false)
{
return $raw ? fgets(STDIN) : rtrim(fgets(STDIN), PHP_EOL);
return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL);
}
/**
......@@ -639,7 +639,7 @@ class BaseConsole
*/
public static function stdout($string)
{
return fwrite(STDOUT, $string);
return fwrite(\STDOUT, $string);
}
/**
......@@ -650,7 +650,7 @@ class BaseConsole
*/
public static function stderr($string)
{
return fwrite(STDERR, $string);
return fwrite(\STDERR, $string);
}
/**
......
......@@ -10,6 +10,7 @@ namespace yii\log;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\VarDumper;
use yii\web\Request;
/**
......@@ -115,7 +116,7 @@ abstract class Target extends Component
$context = [];
foreach ($this->logVars as $name) {
if (!empty($GLOBALS[$name])) {
$context[] = "\${$name} = " . var_export($GLOBALS[$name], true);
$context[] = "\${$name} = " . VarDumper::dumpAsString($GLOBALS[$name]);
}
}
......
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii message' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return array (
'An internal server error occurred.' => 'S\'ha produït un error intern al servidor.',
'Are you sure to delete this item?' => '¿Estás segur d\'eliminar aquest element?',
'Are you sure you want to delete this item?' => 'Estas segur que vols eliminar aquest element?',
'{attribute} cannot be blank.' => '{attribute} no pot estar buit.',
'{attribute} is invalid.' => '{attribute} és invalid.',
'{attribute} is not a valid email address.' => '{attribute} no es una direcció de correu valida.',
'{attribute} is not a valid URL.' => '{attribute} no és una URL valida.',
'{attribute} must be an integer.' => '{attribute} ha de ser un nombre enter.',
'{attribute} must be a number.' => '{attribute} ha de ser un nombre.',
'{attribute} must be a string.' => '{attribute} ha de ser una cadena de caràcters.',
'{attribute} must be either "{true}" or "{false}".' => '{attribute} ha de ser "{true}" o "{false}".',
'{attribute} must be greater than "{compareValue}".' => '{attribute} ha de ser major que "{compareValue}',
'{attribute} must be greater than or equal to "{compareValue}".' => '{attribute} ha de ser major o igual que "{compareValue}".',
'{attribute} must be less than "{compareValue}".' => '{attribute} ha de ser menor que "{compareValue}".',
'{attribute} must be less than or equal to "{compareValue}".' => '{attribute} ha de ser menor o igual que "{compareValue}".',
'{attribute} must be no greater than {max}.' => '{attribute} no pot ser major que {max}.',
'{attribute} must be no less than {min}.' => '{attribute} no pot ser menor que {min}.',
'{attribute} must be repeated exactly.' => '{attribute} ha de ser repetit exactament igual.',
'{attribute} must be "{requiredValue}".' => '{attribute} ha de ser "{requiredValue}".',
'{attribute} must not be equal to "{compareValue}".' => '{attribute} no pot ser igual que "{compareValue}".',
'{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.' => '{attribute} hauria de contenir com a mínim {min, number} {min, plural, one{lletra} other{lletres}}.',
'{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' => '{attribute} hauria de contenir com a màxim {max, number} {max, plural, one{lletra} other{lletres}}.',
'{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '{attribute} hauria contenir {length, number} {length, plural, one{lletra} other{lletres}}.',
'{attribute} "{value}" has already been taken.' => '{attribute} "{value}" ja ha sigut utilitzat.',
'Delete' => 'Eliminar',
'{delta, plural, =1{a day} other{# days}} ago' => 'hace {delta, plural, =1{un dia} other{# dies}}',
'{delta, plural, =1{a minute} other{# minutes}} ago' => 'fa {delta, plural, =1{un minut} other{# minuts}}',
'{delta, plural, =1{a month} other{# months}} ago' => 'fa {delta, plural, =1{un mes} other{# mesos}}',
'{delta, plural, =1{an hour} other{# hours}} ago' => 'fa {delta, plural, =1{una hora} other{# hores}}',
'{delta, plural, =1{a second} other{# seconds}} ago' => 'fa {delta, plural, =1{un segon} other{# segons}}',
'{delta, plural, =1{a year} other{# years}} ago' => 'fa {delta, plural, =1{un any} other{# anys}}',
'Error' => 'Error',
'File upload failed.' => 'Ha fallat la pujada del fitxer.',
'Home' => 'Inici',
'in {delta, plural, =1{a day} other{# days}}' => 'en {delta, plural, =1{un dia} other{# dies}}',
'in {delta, plural, =1{a minute} other{# minutes}}' => 'en {delta, plural, =1{un minut} other{# minuts}}',
'in {delta, plural, =1{a month} other{# months}}' => 'en {delta, plural, =1{un mes} other{# mesos}}',
'in {delta, plural, =1{an hour} other{# hours}}' => 'en {delta, plural, =1{una hora} other{# hores}}',
'in {delta, plural, =1{a second} other{# seconds}}' => 'en {delta, plural, =1{un segon} other{# segons}}',
'in {delta, plural, =1{a year} other{# years}}' => 'en {delta, plural, =1{un any} other{# anys}}',
'Invalid data received for parameter "{param}".' => 'S\'han rebut dades errònies pel paràmetre "{param}"',
'Login Required' => 'Login Requerit',
'Missing required arguments: {params}' => 'Falten arguments requerits: {params}',
'Missing required parameters: {params}' => 'Falten paràmetres requerits: {params}',
'{n} B' => '{n} B',
'{n} GB' => '{n} GB',
'{n} KB' => '{n} KB',
'{n} MB' => '{n} MB',
'No help for unknown command "{command}".' => 'No hi ha ajuda per l\'ordre desconeguda "{command}"',
'No help for unknown sub-command "{command}".' => 'No hi ha ajuda per la sub-ordre desconeguda "{command}"',
'No' => 'No',
'No results found.' => 'No s\'han trobat resultats.',
'(not set)' => '(no establert)',
'{n} PB' => '{n} PB',
'{n, plural, =1{# byte} other{# bytes}}' => '{n, plural, =1{# byte} other{# bytes}}',
'{n, plural, =1{# gigabyte} other{# gigabytes}}' => '{n, plural, =1{# gigabyte} other{# gigabytes}}',
'{n, plural, =1{# kilobyte} other{# kilobytes}}' => '{n, plural, =1{# kilobyte} other{# kilobytes}}',
'{n, plural, =1{# megabyte} other{# megabytes}}' => '{n, plural, =1{# megabyte} other{# megabytes}}',
'{n, plural, =1{# petabyte} other{# petabytes}}' => '{n, plural, =1{# petabyte} other{# petabytes}}',
'{n, plural, =1{# terabyte} other{# terabytes}}' => '{n, plural, =1{# terabyte} other{# terabytes}}',
'{n} TB' => '{n} TB',
'Only files with these extensions are allowed: {extensions}.' => 'Només s\'accepten arxius amb les seguents extensions: {extensions}',
'Only files with these mimeTypes are allowed: {mimeTypes}.' => 'Només s\'accepten arxius amb els seguents tipus MIME: {mimeTypes}',
'Only files with these MIME types are allowed: {mimeTypes}.' => 'Només s\'accepten arxius amb els següents tipus MIME: {mimeTypes}.',
'Page not found.' => 'No s\'ha trobat la pàgina.',
'Please fix the following errors:' => 'Si us plau corregeix els següents errors:',
'Please upload a file.' => 'Si us plau puja un arxiu.',
'Showing <b>{begin, number}-{end, number}</b> of <b>{totalCount, number}</b> {totalCount, plural, one{item} other{items}}.' => 'Mostrant <b>{begin, number}-{end, number}</b> de <b>{totalCount, number}</b> {totalCount, plural, one{element} other{elements}}.',
'The file "{file}" is not an image.' => 'L\'arxiu "{file}" no és una imatge.',
'The file "{file}" is too big. Its size cannot exceed {limit, number} {limit, plural, one{byte} other{bytes}}.' => 'L\'arxiu "{file}" és massa gran. El seu tamany no pot excedir {limit, number} {limit, plural, one{byte} other{bytes}}.',
'The file "{file}" is too small. Its size cannot be smaller than {limit, number} {limit, plural, one{byte} other{bytes}}.' => 'L\'arxiu "{file}" és massa petit. El seu tamany no pot ser menor que {limit, number} {limit, plural, one{byte} other{bytes}}.',
'The format of {attribute} is invalid.' => 'El format de {attribute} és invalid.',
'The image "{file}" is too large. The height cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'La imatge "{file}" és massa gran. L\'altura no pot ser major que {limit, number} {limit, plural, one{píxel} other{píxels}}.',
'The image "{file}" is too large. The width cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'La imatge "{file}" és massa gran. L\'amplada no pot ser major que {limit, number} {limit, plural, one{píxel} other{píxels}}.',
'The image "{file}" is too small. The height cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'La imatge "{file}" és massa petita. L\'altura no pot ser menor que {limit, number} {limit, plural, one{píxel} other{píxels}}.',
'The image "{file}" is too small. The width cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'La imatge "{file}" és massa petita. L\'amplada no pot ser menor que {limit, number} {limit, plural, one{píxel} other{píxels}}.',
'the input value' => 'el valor d\'entrada',
'The verification code is incorrect.' => 'El codi de verificació és incorrecte.',
'Total <b>{count, number}</b> {count, plural, one{item} other{items}}.' => 'Total <b>{count, number}</b> {count, plural, one{element} other{elements}}.',
'Unable to verify your data submission.' => 'No s\'ha pogut verificar les dades enviades.',
'Unknown command "{command}".' => 'Ordre desconeguda "{command}".',
'Unknown option: --{name}' => 'Opció desconeguda: --{name}',
'Update' => 'Actualitzar',
'View' => 'Veure',
'Yes' => 'Sí',
'You are not allowed to perform this action.' => 'No tems permís per executar aquesta acció.',
'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => 'Pots pujar com a màxim {limit, number} {limit, plural, one{arxiu} other{arxius}}.',
);
......@@ -7,7 +7,7 @@ return [
'messagePath' => __DIR__,
// array, required, list of language codes that the extracted messages
// should be translated to. For example, ['zh-CN', 'de'].
'languages' => ['ar', 'bg', 'da', 'de', 'el', 'es', 'fa-IR', 'fi', 'fr', 'hu', 'it', 'ja', 'kk', 'lv', 'nl', 'pl', 'pt-BR', 'pt-PT', 'ro', 'ru', 'sk', 'sr', 'sr-Latn', 'uk', 'vi', 'zh-CN'],
'languages' => ['ar', 'bg', 'ca', 'da', 'de', 'el', 'es', 'fa-IR', 'fi', 'fr', 'hu', 'it', 'ja', 'kk', 'lt', 'lv', 'nl', 'pl', 'pt-BR', 'pt-PT', 'ro', 'ru', 'sk', 'sr', 'sr-Latn', 'uk', 'vi', 'zh-CN'],
// string, the name of the function for translating messages.
// Defaults to 'Yii::t'. This is used as a mark to find the messages to be
// translated. You may use a string for single function name or an array for
......
......@@ -17,10 +17,35 @@
* NOTE: this file must be saved in UTF-8 encoding.
*/
return array (
'the input value' => 'de invoerwaarde',
'Are you sure you want to delete this item?' => 'Ben je zeker dat je dit item wilt verwijderen?',
'Only files with these MIME types are allowed: {mimeTypes}.' => 'Alleen bestanden met de volgende MIME types zijn toegelaten: {mimeTypes}',
'The requested view "{name}" was not found.' => 'De gevraagde view "{view}" werd niet gevonden.',
'in {delta, plural, =1{a day} other{# days}}' => 'binnen {delta, plural, =1{een dag} other{# dagen}}',
'in {delta, plural, =1{a minute} other{# minutes}}' => 'binnen {delta, plural, =1{een minuut} other{# minuten}}',
'in {delta, plural, =1{a month} other{# months}}' => 'binnen {delta, plural, =1{een maand} other{# maanden}}',
'in {delta, plural, =1{a second} other{# seconds}}' => 'binnen {delta, plural, =1{een seconde} other{# seconden}}',
'in {delta, plural, =1{a year} other{# years}}' => 'binnen {delta, plural, =1{een jaar} other{# jaren}}',
'in {delta, plural, =1{an hour} other{# hours}}' => 'binnen {delta, plural, =1{een uur} other{# uren}}',
'{delta, plural, =1{a day} other{# days}} ago' => '{delta, plural, =1{een dag} other{# dagen}} geleden',
'{delta, plural, =1{a minute} other{# minutes}} ago' => '{delta, plural, =1{een minuut} other{# minuten}} geleden',
'{delta, plural, =1{a month} other{# months}} ago' => '{delta, plural, =1{a month} other{# months}} geleden',
'{delta, plural, =1{a second} other{# seconds}} ago' => '{delta, plural, =1{een seconde} other{# seconden}} geleden',
'{delta, plural, =1{a year} other{# years}} ago' => '{delta, plural, =1{een jaar} other{# jaren}} geleden',
'{delta, plural, =1{an hour} other{# hours}} ago' => '{delta, plural, =1{een uur} other{# uren}} geleden',
'{n, plural, =1{# byte} other{# bytes}}' => '{n, plural, =1{# byte} other{# bytes}}',
'{n, plural, =1{# gigabyte} other{# gigabytes}}' => '{n, plural, =1{# gigabyte} other{# gigabytes}}',
'{n, plural, =1{# kilobyte} other{# kilobytes}}' => '{n, plural, =1{# kilobyte} other{# kilobytes}}',
'{n, plural, =1{# megabyte} other{# megabytes}}' => '{n, plural, =1{# megabyte} other{# megabytes}}',
'{n, plural, =1{# petabyte} other{# petabytes}}' => '{n, plural, =1{# petabyte} other{# petabytes}}',
'{n, plural, =1{# terabyte} other{# terabytes}}' => '{n, plural, =1{# terabyte} other{# terabytes}}',
'{n} B' => '{n} B',
'{n} GB' => '{n} GB',
'{n} KB' => '{n} KB',
'{n} MB' => '{n} MB',
'{n} PB' => '{n} PB',
'{n} TB' => '{n} TB',
'(not set)' => '(niet ingesteld)',
'An internal server error occurred.' => 'Er is een interne serverfout opgetreden.',
'Are you sure to delete this item?' => 'Weet u zeker dat u dit item wilt verwijderen?',
'Delete' => 'Verwijderen',
'Error' => 'Fout',
'File upload failed.' => 'Bestand uploaden mislukt.',
......@@ -34,7 +59,6 @@ return array (
'No help for unknown sub-command "{command}".' => 'Geen hulp voor onbekend sub-commando "{command}".',
'No results found.' => 'Geen resultaten gevonden',
'Only files with these extensions are allowed: {extensions}.' => 'Alleen bestanden met de volgende extensies zijn toegestaan: {extensions}.',
'Only files with these mimeTypes are allowed: {mimeTypes}.' => 'Alleen bestanden met de volgende mimeTypes zijn toegestaan: {mimeTypes}.',
'Page not found.' => 'Pagina niet gevonden.',
'Please fix the following errors:' => 'Corrigeer de volgende fouten:',
'Please upload a file.' => 'Upload een bestand.',
......@@ -57,6 +81,7 @@ return array (
'Yes' => 'Ja',
'You are not allowed to perform this action.' => 'U bent niet gemachtigd om deze actie uit te voeren.',
'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => 'U kunt maximaal {limit, number} {limit, plural, one{ander bestand} other{andere bestander}} uploaden.',
'the input value' => 'de invoerwaarde',
'{attribute} "{value}" has already been taken.' => '{attribute} "{value}" is reeds in gebruik.',
'{attribute} cannot be blank.' => '{attribute} mag niet leeg zijn.',
'{attribute} is invalid.' => '{attribute} is ongeldig.',
......
......@@ -18,9 +18,13 @@ use yii\di\Instance;
/**
* DbManager represents an authorization manager that stores authorization information in database.
*
* The database connection is specified by [[db]]. And the database schema
* should be as described in "framework/rbac/*.sql". You may change the names of
* the three tables used to store the authorization data by setting [[itemTable]],
* The database connection is specified by [[db]]. The database schema could be initialized by applying migration:
*
* ```
* yii migrate --migrationPath=/vendor/yiisoft/yii2/rbac/migrations/
* ```
*
* You may change the names of the three tables used to store the authorization data by setting [[itemTable]],
* [[itemChildTable]] and [[assignmentTable]].
*
* @author Qiang Xue <qiang.xue@gmail.com>
......
<?php
use yii\db\Schema;
class m140506_102106_rbac_init extends \yii\db\Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('{{%auth_rule}}', [
'name' => Schema::TYPE_STRING . '(64) NOT NULL',
'data' => Schema::TYPE_TEXT,
'created_at' => Schema::TYPE_INTEGER,
'updated_at' => Schema::TYPE_INTEGER,
], $tableOptions);
$this->addPrimaryKey('pk-auth_rule', '{{%auth_rule}}', 'name');
$this->createTable('{{%auth_item}}', [
'name' => Schema::TYPE_STRING . '(64) NOT NULL',
'type' => Schema::TYPE_INTEGER . ' NOT NULL',
'description' => Schema::TYPE_TEXT,
'rule_name' => Schema::TYPE_STRING . '(64)',
'data' => Schema::TYPE_TEXT,
'created_at' => Schema::TYPE_INTEGER,
'updated_at' => Schema::TYPE_INTEGER,
], $tableOptions);
$this->addPrimaryKey('pk-auth_item', '{{%auth_item}}', 'name');
$this->addForeignKey('fk-auth_item-rule_name', '{{%auth_item}}', 'rule_name', '{{%auth_rule}}', 'name', 'SET NULL', 'CASCADE');
$this->createIndex('idx-auth_item-type', '{{%auth_item}}', 'type');
$this->createTable('{{%auth_item_child}}', [
'parent' => Schema::TYPE_STRING . '(64) NOT NULL',
'child' => Schema::TYPE_STRING . '(64) NOT NULL',
], $tableOptions);
$this->addPrimaryKey('pk-auth_item_child', '{{%auth_item_child}}', ['parent', 'child']);
$this->addForeignKey('fk-auth_item_child-parent', '{{%auth_item_child}}', 'parent', '{{%auth_item}}', 'name', 'CASCADE', 'CASCADE');
$this->addForeignKey('fk-auth_item_child-child', '{{%auth_item_child}}', 'child', '{{%auth_item}}', 'name', 'CASCADE', 'CASCADE');
$this->createTable('{{%auth_assignment}}', [
'item_name' => Schema::TYPE_STRING . '(64) NOT NULL',
'user_id' => Schema::TYPE_STRING . '(64) NOT NULL',
'created_at' => Schema::TYPE_INTEGER,
], $tableOptions);
$this->addPrimaryKey('pk-auth_assignment', '{{%auth_assignment}}', ['item_name', 'user_id']);
$this->addForeignKey('fk-auth_assignment-item_name', '{{%auth_assignment}}', 'item_name', '{{%auth_item}}', 'name', 'CASCADE', 'CASCADE');
}
public function down()
{
$this->dropTable('{{%auth_assignment}}');
$this->dropTable('{{%auth_item_child}}');
$this->dropTable('{{%auth_item}}');
$this->dropTable('{{%auth_rule}}');
}
}
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists [auth_assignment];
drop table if exists [auth_item_child];
drop table if exists [auth_item];
drop table if exists [auth_rule];
create table [auth_rule]
(
[name] varchar(64) not null,
[data] text,
[created_at] integer,
[updated_at] integer,
primary key ([name])
);
create table [auth_item]
(
[name] varchar(64) not null,
[type] integer not null,
[description] text,
[rule_name] varchar(64),
[data] text,
[created_at] integer,
[updated_at] integer,
primary key ([name]),
foreign key ([rule_name]) references [auth_rule] ([name]) on delete set null on update cascade,
key [type] ([type])
);
create table [auth_item_child]
(
[parent] varchar(64) not null,
[child] varchar(64) not null,
primary key ([parent],[child]),
foreign key ([parent]) references [auth_item] ([name]) on delete cascade on update cascade,
foreign key ([child]) references [auth_item] ([name]) on delete cascade on update cascade
);
create table [auth_assignment]
(
[item_name] varchar(64) not null,
[user_id] varchar(64) not null,
[created_at] integer,
primary key ([item_name], [user_id]),
foreign key ([item_name]) references [auth_item] ([name]) on delete cascade on update cascade
);
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;
create table `auth_rule`
(
`name` varchar(64) not null,
`data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`)
) engine InnoDB;
create table `auth_item`
(
`name` varchar(64) not null,
`type` integer not null,
`description` text,
`rule_name` varchar(64),
`data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`),
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
key `type` (`type`)
) engine InnoDB;
create table `auth_item_child`
(
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`, `child`),
foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
create table `auth_assignment`
(
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`created_at` integer,
primary key (`item_name`, `user_id`),
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
drop table if exists "auth_rule";
create table "auth_rule"
(
"name" varchar(64) not null,
"data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name")
);
create table "auth_item"
(
"name" varchar(64) not null,
"type" integer not null,
"description" text,
"rule_name" varchar(64),
"data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade,
key "type" ("type")
);
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"created_at" integer,
primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
drop table if exists "auth_rule";
create table "auth_rule"
(
"name" varchar(64) not null,
"data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name")
);
create table "auth_item"
(
"name" varchar(64) not null,
"type" integer not null,
"description" text,
"rule_name" varchar(64),
"data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
);
create index auth_item_type_idx on "auth_item" ("type");
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"created_at" integer,
primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
drop table if exists "auth_rule";
create table "auth_rule"
(
"name" varchar(64) not null,
"data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name")
);
create table "auth_item"
(
"name" varchar(64) not null,
"type" integer not null,
"description" text,
"rule_name" varchar(64),
"data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
);
create index "auth_item_type_idx" on "auth_item" ("type");
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"created_at" integer,
primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
......@@ -36,6 +36,8 @@ class ContainerTest extends TestCase
$this->assertTrue($foo instanceof $Foo);
$this->assertTrue($foo->bar instanceof $Bar);
$this->assertTrue($foo->bar->qux instanceof $Qux);
$foo2 = $container->get($Foo);
$this->assertFalse($foo === $foo2);
// full wiring
$container = new Container;
......@@ -80,5 +82,12 @@ class ContainerTest extends TestCase
$this->assertTrue($foo instanceof $Foo);
$this->assertTrue($foo->bar instanceof $Bar);
$this->assertTrue($foo->bar->qux instanceof $Qux);
// wiring by closure
$container = new Container;
$container->set('qux', new Qux);
$qux1 = $container->get('qux');
$qux2 = $container->get('qux');
$this->assertTrue($qux1 === $qux2);
}
}
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