Browse Source

Worked on several Guide docs

tags/2.0.0-alpha
Larry Ullman 11 years ago
parent
commit
94c0b27845
  1. 16
      docs/guide/authentication.md
  2. 38
      docs/guide/composer.md
  3. 20
      docs/guide/form.md
  4. 78
      docs/guide/installation.md
  5. 61
      docs/guide/mvc.md
  6. 8
      docs/guide/security.md
  7. 48
      docs/guide/url.md

16
docs/guide/authentication.md

@ -1,12 +1,10 @@
Authentication
==============
Authentication is basically what happens when one is trying to sign in. Typically login and passwords are read from
the form and then application checks if there's such user with such password.
Authentication is the act of verifying who a user is, and is the basis of the login process. Typically, authentication uses an identifier--a username or email address--and password, submitted through a form. The application then compares this information against that previously stored.
In Yii all this is done semi-automatically and what's left to developer is to implement [[\yii\web\IdentityInterface]].
Typically it is being implemented in `User` model. You can find a full featured example in
[advanced application template](installation.md). Below only interface methods are listed:
In Yii all this is done semi-automatically, leaving the developer to merely implement [[\yii\web\IdentityInterface]]. Typically, implementation is accomplished using the `User` model. You can find a full featured example in the
[advanced application template](installation.md). Below only the interface methods are listed:
```php
class User extends ActiveRecord implements IdentityInterface
@ -51,10 +49,8 @@ class User extends ActiveRecord implements IdentityInterface
}
```
First two methods are simple. `findIdentity` given ID returns model instance while `getId` returns ID itself.
`getAuthKey` and `validateAuthKey` are used to provide extra security to the "remember me" cookie.
`getAuthKey` should return a string that is unique for each user. A good idea is to save this value when user is
created using `Security::generateRandomKey()`:
Two of the outlined methods are simple: `findIdentity` is provided with an ID and returns a model instance represented by that ID. The `getId` method returns the ID itself.
Two of the other methods--`getAuthKey` and `validateAuthKey`--are used to provide extra security to the "remember me" cookie. `getAuthKey` should return a string that is unique for each user. A good idea is to save this value when the user is created by using Yii's `Security::generateRandomKey()`:
```php
public function beforeSave($insert)
@ -69,4 +65,4 @@ public function beforeSave($insert)
}
```
`validateAuthKey` just compares `$authKey` passed as parameter (got from cookie) with the value got from database.
The `validateAuthKey` method just compares the `$authKey` variable, passed as parameter (itself retrieved from a cookie), with the value fetched from database.

38
docs/guide/composer.md

@ -1,20 +1,28 @@
Composer
========
Yii2 uses Composer as its package manager. It is a PHP utility that allows you to automatically install libraries and
extensions keeping them up to date and handling dependencies.
Yii2 uses Composer as its package manager. 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.
Installing Composer
-------------------
Check the official guide for [linux](http://getcomposer.org/doc/00-intro.md#installation-nix) or
[Windows](http://getcomposer.org/doc/00-intro.md#installation-windows).
In order to install Composer, check the official guide for your operating system:
* [Linux](http://getcomposer.org/doc/00-intro.md#installation-nix)
* [Windows](http://getcomposer.org/doc/00-intro.md#installation-windows)
All of the details can be found in the guide, but you'll either download Composer directly from [http://getcomposer.org/](http://getcomposer.org/), or run the following command:
```
curl -s http://getcomposer.org/installer | php
```
Adding more packages to your project
------------------------------------
After [installing an application](installing.md) you will find `composer.json` in the root directory of your project.
This file lists packages that your application uses. The part we're interested in is `require` section.
The act of [installing a Yii application](installing.md) creates the `composer.json` file in the root directory of your project.
In this file you list the packages that your application requires. For Yii sites, the most important part of the file is `require` the section:
```
{
@ -25,23 +33,29 @@ This file lists packages that your application uses. The part we're interested i
}
```
Here you can specify package name and version. Additionally to Yii extensions you may check
[packagist](http://packagist.org/) repository for general purpose PHP packages.
Within the `require` section, you specify the name and version of each required package. The above example says that a version greater than or equal to 1.3 of Michaelf's PHP-Markdown package is required, as is version 4.5 or greater of Ezyang's HTMLPurifier. For details of this syntax, see the [official Composer documentation](http://getcomposer.org).
After packages are specified you can type either
The full list of available Composer-supported PHP packages can be found at [packagist](http://packagist.org/). Any Yii extension can also be explicitly named using the syntax:
???
Once you have edited the `composer.json`, you can invoke Composer to install the identified dependencies. For the first installation of the dependencies, use this command:
```
php composer.phar install
```
or
This must be executed within your Yii project's directory, where the `composer.json` file can be found. Depending upon your operating system and setup, you may need to provide paths to the PHP executable and to the `composer.phar` script.
For an existing installation, you can have Composer update the dependencies using:
```
php composer.phar update
```
depending if you're doing it for the first time or not. Then, after some waiting, packages will be installed and ready
to use. You don't need anything to be configured additionally.
Again, you may need to provide specific path references.
In both cases, after some waiting, the required packages will be installed and ready to use in your Yii application. No additional configuration of those packages will be required.
See also

20
docs/guide/form.md

@ -1,12 +1,9 @@
Working with forms
==================
The primary way of using forms in Yii is [[\yii\widgets\ActiveForm]]. It should be preferred when you have a model
behind a form. Additionally there are some useful methods in [[\yii\helpers\Html]] that are typically used for adding
buttons and help text.
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 used for adding buttons and help text to any form.
First step creating a form is to create a model. It can be either Active Record or regular Model. Let's use regular
login model as an example:
When creating model-based forms, the first step is to define the model itself. The model can be either based upon the Active Record class, or the more generic Model class. For this login example, a generic model will be used:
```php
use yii\base\Model;
@ -57,7 +54,7 @@ class LoginForm extends Model
}
```
In controller we're passing model to view where Active Form is used:
The controller will pass an instance of that model to the view, wherein the Active Form widget is used:
```php
use yii\helpers\Html;
@ -78,14 +75,11 @@ use yii\widgets\ActiveForm;
<?php ActiveForm::end() ?>
```
In the code above `ActiveForm::begin()` not only creates form instance but marks the beginning of the form. All the content
that is located between `ActiveForm::begin()` and `ActiveForm::end()` will be wrapped with appropriate `<form>` tag.
Same as with any other widget you can specify some options passing an array to `begin` method. In our case we're adding
extra CSS class and specifying ID that will be used in the tag.
In the above code, `ActiveForm::begin()` not only creates a form instance, but also marks the beginning of the form. All of the content
placed between `ActiveForm::begin()` and `ActiveForm::end()` will be wrapped within the `<form>` tag. As with any widget, you can specify some options as to how the widget should be configured by passing an array to the `begin` method. In this case, an extra CSS class and identifying ID are passed to be used in the opening `<form>` tag.
In order to insert a form field along with its label all necessary validation JavaScript we're calling `field` method
and it gives back `\yii\widgets\ActiveField`. It it's echoed directly it creates a regular input. In case you want to
customize it you can add a chain of additional methods:
In order to create a form element in the form, along with the element's label, and any application JavaScript validation, the `field` method of the Active Form widget is called. When the invocation of this method is echoed directly, the result is a regular (text) input. To
customize the output, you can chain additional methods to this call:
```php
<?= $form->field($model, 'password')->passwordInput() ?>

78
docs/guide/installation.md

@ -1,85 +1,83 @@
Installation
============
There are two ways you can install the Yii framework:
* Using [Composer](http://getcomposer.org/)
* Via manual download
Installing via Composer
-----------------------
The recommended way of installing Yii is by using [Composer](http://getcomposer.org/) package manager. If you do not
have it, you may download it from [http://getcomposer.org/](http://getcomposer.org/) or run the following command:
The recommended way to install Yii is to use the [Composer](http://getcomposer.org/) package manager. If you do not already
have Composer installed, you may download it from [http://getcomposer.org/](http://getcomposer.org/) or run the following command:
```
curl -s http://getcomposer.org/installer | php
```
Yii provides a few ready-to-use application templates. Based on your needs, you may choose one of them to bootstrap
your project.
For problems or more information, see the official Composer guide:
* [Linux](http://getcomposer.org/doc/00-intro.md#installation-nix)
* [Windows](http://getcomposer.org/doc/00-intro.md#installation-windows)
There are two application templates available:
With Composer installed, you can create a new Yii site using one of Yii's ready-to-use application templates. Based on your needs, choosing the right template can help bootstrap your project.
- [basic](https://github.com/yiisoft/yii2-app-basic) that is just a basic frontend application template.
- [advanced](https://github.com/yiisoft/yii2-app-advanced) that is a set of frontend, backend, console, common
(shared code) and environments support.
Currently, there are two application templates available:
Please refer to installation instructions on these pages. To read more about ideas behing these application templates and
proposed usage refer to [basic application template](apps-basic.md) and [advanced application template](apps-advanced.md).
- [basic](https://github.com/yiisoft/yii2-app-basic), just a basic frontend application template.
- [advanced](https://github.com/yiisoft/yii2-app-advanced), consisting of a frontend, a backend, console resources, common (shared code), and support for environments.
For installation instructions for these templates, see the above linked pages. To read more about ideas behind these application templates and
proposed usage, refer to the [basic application template](apps-basic.md) and [advanced application template](apps-advanced.md) documents.
Installing from zip
-------------------
Installation from zip mainly involves the following two steps:
Installation from a zip file involves two steps:
1. Download Yii Framework from [yiiframework.com](http://www.yiiframework.com/).
2. Unpack the Yii release file to a Web-accessible directory.
1. Downloading the Yii Framework from [yiiframework.com](http://www.yiiframework.com/).
2. Unpacking the downloaded file.
> Tip: Yii does not need to be installed under a Web-accessible directory.
A Yii application has one entry script which is usually the only file that
needs to be exposed to Web users. Other PHP scripts, including those from
Yii, should be protected from Web access; otherwise they might be exploited
by hackers.
> Tip: The Yii framework itself does not need to be installed under a web-accessible directory.
A Yii application has one entry script which is usually the only file that absolutely must be exposed to web users (i.e., placed within the web directory). Other PHP scripts, including those part of the
Yii framework, should be protected from web access to prevent possible exploitation by hackers.
Requirements
------------
After installing Yii, you may want to verify that your server satisfies
Yii's requirements. You can do so by accessing the requirement checker
script via the following URL in a Web browser:
~~~
http://hostname/path/to/yii/requirements/index.php
~~~
Yii's requirements. You can do so by running the requirement checker
script in a web browser.
Yii requires PHP 5.4.0, so the server must have PHP 5.4.0 or above installed and
available to the web server. Yii has been tested with [Apache HTTP server](http://httpd.apache.org/)
on Windows and Linux. It may also run on other Web servers and platforms,
provided PHP 5.4 is supported.
1. Copy the `requirements` folder from the downloaded Yii directory to your web directory.
2. Access `http://hostname/path/to/yii/requirements/index.php` in your browser.
Yii 2 requires PHP 5.4.0 or higher. Yii has been tested with the [Apache HTTP server](http://httpd.apache.org/) on Windows and Linux. Yii may also be usable on other web servers and platforms, provided that PHP 5.4 or higher is supported.
Recommended Apache Configuration
--------------------------------
Yii is ready to work with a default Apache web server configuration.
The `.htaccess` files in Yii framework and application folders deny
access to the restricted resources. To hide the bootstrap file (usually `index.php`)
in your URLs you can add `mod_rewrite` instructions to the `.htaccess` file
in your document root or to the virtual host configuration:
Yii is ready to work with a default Apache web server configuration. As a security measure, Yii comes with `.htaccess` files in the Yii framework and application folders to deny access to thoe restricted resources.
By default, requests for pages in a Yii-based site go through the boostrap file, usually named `index.php`, and placed in the application's root directory. The result will be URLs in the format `http://hostname/index.php/controller/action/param/value`.
To hide the bootstrap file in your URLs, add `mod_rewrite` instructions to the `.htaccess` file found in your web document root (or add the instructions to the virtual host configuration in Apache's `httpd.conf` file). The applicable instructions are:
~~~
RewriteEngine on
# if a directory or a file exists, use it directly
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
# Otherwise forward it to index.php
RewriteRule . index.php
~~~
Recommended Nginx Configuration
-------------------------------
You can use Yii with [Nginx](http://wiki.nginx.org/) and PHP with [FPM SAPI](http://php.net/install.fpm).
Here is a sample host configuration. It defines the bootstrap file and makes
Yii to catch all requests to nonexistent files, which allows us to have nice-looking URLs.
Yii can also be used with the popular [Nginx](http://wiki.nginx.org/) web server, so long it has PHP installed as an [FPM SAPI](http://php.net/install.fpm). Below is a sample host configuration for a Yii-based site on Nginx. The configuration identifies tells the server to send all requests for non-existent resources through the bootstrap file, resulting in "prettier" URLs without the need for `index.php` references.
~~~
server {
@ -107,4 +105,4 @@ server {
}
~~~
Make sure to set `cgi.fix_pathinfo=0` in php.ini to avoid many unnecessary system `stat()` calls.
When using this configuration, you should set `cgi.fix_pathinfo=0` in the `php.ini` file in order to avoid many unnecessary system `stat()` calls.

61
docs/guide/mvc.md

@ -2,17 +2,17 @@ MVC Overview
============
Yii implements the model-view-controller (MVC) design pattern, which is
widely adopted in Web programming. MVC aims to separate business logic from
user interface considerations, so that developers can more easily change
each part without affecting the other. In MVC, the model represents the
information (the data) and the business rules; the view contains elements
of the user interface such as text, form inputs; and the controller manages
the communication between the model and the view.
Besides implementing MVC, Yii also introduces a front-controller, called
`application`, which encapsulates the execution context for the processing
of a request. Application collects information about a user request and
then dispatches it to an appropriate controller for further handling.
widely adopted in web and other application programming. MVC aims to separate business logic from
user interface considerations, allowing developers to more easily change individual components of an application without affecting, or even touching, another.
In MVC, the *model* represents the
information (the data) and the business rules to which the data must adhere. The *view* contains elements
of the user interface, such as text, images, and form elements. The *controller* manages
the communication between the model and the view, acting as an agent.
Besides implementing the MVC design pattern, Yii also introduces a *front-controller*, called
`application`. The front-controller encapsulates the *execution context* for the processing of a request. This means that the front-controller collects information about a user request, and
then dispatches it to an appropriate controller for actual handling of that request. In other words, the front-controller is the primary application manager, handling all requests and delegating action accordingly.
The following diagram shows the static structure of a Yii application:
@ -22,31 +22,20 @@ The following diagram shows the static structure of a Yii application:
A Typical Workflow
------------------
The following diagram shows a typical workflow of a Yii application when
it is handling a user request:
The following diagram shows a typical workflow of a Yii application handling a user request:
![Typical workflow of a Yii application](flow.png)
1. A user makes a request with the URL `http://www.example.com/index.php?r=post/show&id=1`
and the Web server handles the request by executing the bootstrap script `index.php`.
2. The bootstrap script creates an [Application](/doc/guide/basics.application)
instance and runs it.
3. The Application obtains detailed user request information from
an [application component](/doc/guide/basics.application#application-component)
named `request`.
4. The application determines the requested [controller](/doc/guide/basics.controller)
and [action](/doc/guide/basics.controller#action) with the help
of an application component named `urlManager`. For this example, the controller
is `post`, which refers to the `PostController` class; and the action is `show`,
whose actual meaning is determined by the controller.
5. The application creates an instance of the requested controller
to further handle the user request. The controller determines that the action
`show` refers to a method named `actionShow` in the controller class. It then
creates and executes filters (e.g. access control, benchmarking) associated
with this action. The action is executed if it is allowed by the filters.
6. The action reads a `Post` [model](/doc/guide/basics.model) whose ID is `1` from the database.
7. The action renders a [view](/doc/guide/basics.view) named `show` with the `Post` model.
8. The view reads and displays the attributes of the `Post` model.
9. The view executes some [widgets](/doc/guide/basics.view#widget).
10. The view rendering result is embedded in a [layout](/doc/guide/basics.view#layout).
11. The action completes the view rendering and displays the result to the user.
1. A user makes a request of the URL `http://www.example.com/index.php?r=post/show&id=1`. The Web server handles the request by executing the bootstrap script `index.php`.
2. The bootstrap script creates an [Application](/doc/guide/basics.application) instance and runs it.
3. The Application instance obtains the detailed user request information from an [application component](/doc/guide/basics.application#application-component) named `request`.
4. The application determines which [controller](/doc/guide/basics.controller) and which [action](/doc/guide/basics.controller#action) of that controller was requested. This is accomplished with the help
of an application component named `urlManager`. For this example, the controller is `post`, which refers to the `PostController` class; and the action is `show`, whose actual meaning is determined by the controller.
5. The application creates an instance of the requested controller
to further handle the user request. The controller determines that the action `show` refers to a method named `actionShow` in the controller class. It then creates and executes filters (e.g. access control, benchmarking) associated with this action. The action is then executed, if execution is allowed by the filters (e.g., if the user has permission to execute that action).
6. The action creates a `Post` [model](/doc/guide/basics.model) instance, using the underlying database table, where the ID value of the corresponding record `1`.
7. The action renders a [view](/doc/guide/basics.view) named `show`, providing to the view the `Post` model instance.
8. The view reads the attributes of the `Post` model instance and displays the values of those attributes.
9. The view executes some [widgets](/doc/guide/basics.view#widget).
10. The view rendering result--the output from the previous steps--is embedded in a [layout](/doc/guide/basics.view#layout) to create a complete page.
11. The action completes the view rendering and displays the result to the user.

8
docs/guide/security.md

@ -1,6 +1,8 @@
Security
========
Good security is vital to the health and success of many websites. Unfortunately, many developers may cut corners when it comes to security due to a lack of understanding or too large of an implementation hurdle. To make your Yii-based site as secure as possible, the Yii framework has baked in several excellent, and easy to use, security features.
Hashing and verifying passwords
------------------------------
@ -28,7 +30,7 @@ if (Security::validatePassword($password, $hash)) {
```
Random data
Creating random data
-----------
Random data is useful in many cases. For example, when resetting a password via email you need to generate a token,
@ -63,9 +65,11 @@ Then when user want to read it:
$data = \yii\helpers\Security::decrypt($encryptedData, $secretWord);
```
Making sure data wasn't modified
Confirming data integrity
--------------------------------
Making sure data wasn't modified
hashData()
validateData()

48
docs/guide/url.md

@ -1,57 +1,61 @@
URL Management
==============
The concept of URL management in Yii fairly simple. The idea is that application uses internal routes and parameters
everywhere. Framework takes care of translating routes into URLs and back according to URL manager configuration.
This approach allows you to adjust URLs in a single config file without touching application code.
The concept of URL management in Yii fairly simple. URL management is based on the premise that the application uses internal routes and parameters
everywhere. The framework itself will then translates routes into URLs, and translate URLs into routs, according to the URL manager's configuration.
This approach allows you to change site-wide URLs merely by edited a single config file, without ever touching the application code.
Internal route
--------------
Internal routes and parameters are what you're dealing with when implementing an application using Yii.
Each controller and its action has a corresponding internal route such as `site/index`. Here `site` is referred to as
controller ID while `index` is referred to as action ID. If controller belongs to a module, internal route is prefixed
with the module ID such as `blog/post/index` for a blog module.
When implementing an application using Yii, you'll deal with internal routes and parameters. Each controller and controller action has a corresponding internal route, such as `site/index` or `user/create`. In the former, `site` is referred to as the *controller ID* while `index` is referred to as the *action ID*. In the second example, `user` is the controller ID and `create` is the action ID. If controller belongs to a *module*, the internal route is prefixed with the module ID, such as `blog/post/index` for a blog module (with `post` being the controller ID and `index` being the action ID).
Creating URLs
-------------
As was already mentioned, the most important rule is to always use URL manager to create URLs. Url manages is an
application component with `urlManager` id that is accessible both from web and console applications via
`\Yii::$app->urlManager` and has two following URL creation methods available:
The most important rule for creating URLs in your site is to always do so using the URL manager. The URL manager is an
application component with the `urlManager` ID. This component is accessible both from web and console applications via
`\Yii::$app->urlManager`. The component makes availabe the two following URL creation methods:
- createUrl($route, $params = [])
- createAbsoluteUrl($route, $params = [])
- `createUrl($route, $params = [])`
- `createAbsoluteUrl($route, $params = [])`
First one creates URL relative to the application root while the second one creates URL prefixed with protocol and
hostname. The former is suitable for internal application URLs while the latter is used when you need to create rules
for outside the website. For example, when sending emails or generating RSS feed.
The `createUrl` method creates a URL relative to the application root, such as `/index.php/site/index/`. The `createAbsoluteUrl` method creates URL prefixed with the proper protocol and
hostname: `http://www.example.com/index.php/site/index`. The former is suitable for internal application URLs, while the latter is used when you need to create rules for outside the website, such as when sending emails or generating an RSS feed.
Some examples:
```php
echo \Yii::$app->urlManager->createUrl('site/page', ['id' => 'about']);
// /index.php/site/page/id/about/
echo \Yii::$app->urlManager->createAbsoluteUrl('blog/post/index');
// http://www.example.com/index.php/blog/post/index/
```
Inside web application controller you can use its own `createUrl` shortcut method in the following forms:
The exact format of the outputted URL will depend upon how the URL manager is configured (which is the point). The above examples may also output:
* `/site/page/id/about/`
* `/index.php?r=site/page&id=about`
* `http://www.example.com/blog/post/index/`
* `http://www.example.com/index.php?r=blog/post/index`
Inside a web application controller, you can use the controller's own `createUrl` shortcut method. Unlike the global `createUrl` method, the controller version is context sensitive:
```php
echo $this->createUrl(''); // currently active route
echo $this->createUrl('view', ['id' => 'contact']); // same controller, different action
echo $this->createUrl('post/index'); // same module, different controller and action
echo $this->createUrl('/site/index'); // absolute route no matter which controller we're in
echo $this->createUrl('/site/index'); // absolute route no matter what controller is making this call
```
> **Tip**: In order to generate URL with a hashtag, for example `/index.php?r=site/page&id=100#title`, you need to
specify parameter named `#` using `$this->createUrl('post/read', ['id' => 100, '#' => 'title'])`.
specify the parameter named `#` using `$this->createUrl('post/read', ['id' => 100, '#' => 'title'])`.
Customizing URLs
----------------
By default Yii uses a query string format URLs such as `/index.php?r=news/view&id=100`. In order to make URLs
human-friendly you need to configure `urlManager` component like the following:
By default, Yii uses a query string format for URLs, such as `/index.php?r=news/view&id=100`. In order to make URLs
human-friendly (i.e., more readable), you need to configure the `urlManager` component in the application's configuration file. Enabling "pretty" URLs will convert the query string format to a directory-based format: `/index.php/news/view/id/100`. Disabling the `showScriptName` parameter means that `index.php` will not be part of the URLs. Here's the relevant part of the application's configuration file.
```php
<?php
@ -66,7 +70,7 @@ return [
];
```
Note that
Note that this configuration will only work if the web server has been properly configured for Yii, see (installation)[installation.md#recommended-apache-configuration].
### Named parameters

Loading…
Cancel
Save