Browse Source

guide WIP

tags/2.0.0-rc
Qiang Xue 11 years ago
parent
commit
011284dddc
  1. 2
      docs/guide/README.md
  2. 3
      docs/guide/rest-authentication.md
  3. 14
      docs/guide/rest-controllers.md
  4. 12
      docs/guide/rest-quick-start.md
  5. 13
      docs/guide/rest-resources.md
  6. 117
      docs/guide/structure-entry-scripts.md

2
docs/guide/README.md

@ -30,7 +30,7 @@ Getting Started
Application Structure Application Structure
--------------------- ---------------------
* **TBD** [Entry Scripts](structure-entry-scripts.md) * [Entry Scripts](structure-entry-scripts.md)
* **TBD** [Applications](structure-applications.md) * **TBD** [Applications](structure-applications.md)
* [Controllers and Actions](structure-controllers.md) * [Controllers and Actions](structure-controllers.md)
* [Views](structure-views.md) * [Views](structure-views.md)

3
docs/guide/rest-authentication.md

@ -98,8 +98,7 @@ If authentication fails, a response with HTTP status 401 will be sent back toget
(such as a `WWW-Authenticate` header for HTTP Basic Auth). (such as a `WWW-Authenticate` header for HTTP Basic Auth).
Authorization <a name="authorization"></a> ## Authorization <a name="authorization"></a>
-------------
After a user is authenticated, you probably want to check if he or she has the permission to perform the requested After a user is authenticated, you probably want to check if he or she has the permission to perform the requested
action for the requested resource. This process is called *authorization* which is covered in detail in action for the requested resource. This process is called *authorization* which is covered in detail in

14
docs/guide/rest-controllers.md

@ -25,8 +25,7 @@ will be described in detail in the next few sections:
* User authorization in regarding to the requested action and resource. * User authorization in regarding to the requested action and resource.
Creating Controller Classes ## Creating Controller Classes <a name="creating-controller"></a>
---------------------------
When creating a new controller class, a convention in naming the controller class is to use When creating a new controller class, a convention in naming the controller class is to use
the type name of the resource and use singular form. For example, to serve user information, the type name of the resource and use singular form. For example, to serve user information,
@ -46,8 +45,7 @@ public function actionView($id)
``` ```
Filters ## Filters <a name="filters"></a>
-------
Most RESTful API features provided by [[yii\rest\Controller]] are implemented in terms of [filters](runtime-filtering.md). Most RESTful API features provided by [[yii\rest\Controller]] are implemented in terms of [filters](runtime-filtering.md).
In particular, the following filters will be executed in the order they are listed: In particular, the following filters will be executed in the order they are listed:
@ -77,15 +75,15 @@ public function behaviors()
} }
``` ```
Extending `ActiveController`
---------------------------- ## Extending `ActiveController` <a name="extending-active-controller"></a>
If your controller class extends from [[yii\rest\ActiveController]], you should set If your controller class extends from [[yii\rest\ActiveController]], you should set
its [[yii\rest\ActiveController::modelClass||modelClass]] property to be the name of the resource class its [[yii\rest\ActiveController::modelClass||modelClass]] property to be the name of the resource class
that you plan to serve through this controller. The class must extend from [[yii\db\ActiveRecord]]. that you plan to serve through this controller. The class must extend from [[yii\db\ActiveRecord]].
### Customizing Actions ### Customizing Actions <a name="customizing-actions"></a>
By default, [[yii\rest\ActiveController]] provides the following actions: By default, [[yii\rest\ActiveController]] provides the following actions:
@ -122,7 +120,7 @@ public function prepareDataProvider()
Please refer to the class references for individual action classes to learn what configuration options are available. Please refer to the class references for individual action classes to learn what configuration options are available.
### Performing Access Check ### Performing Access Check <a name="performing-access-check"></a>
When exposing resources through RESTful APIs, you often need to check if the current user has the permission When exposing resources through RESTful APIs, you often need to check if the current user has the permission
to access and manipulate the requested resource(s). With [[yii\rest\ActiveController]], this can be done to access and manipulate the requested resource(s). With [[yii\rest\ActiveController]], this can be done

12
docs/guide/rest-quick-start.md

@ -22,8 +22,7 @@ Assume you want to expose the user data via RESTful APIs. The user data are stor
and you have already created the [[yii\db\ActiveRecord|ActiveRecord]] class `app\models\User` to access the user data. and you have already created the [[yii\db\ActiveRecord|ActiveRecord]] class `app\models\User` to access the user data.
Creating a Controller ## Creating a Controller <a name="creating-controller"></a>
---------------------
First, create a controller class `app\controllers\UserController` as follows, First, create a controller class `app\controllers\UserController` as follows,
@ -42,8 +41,7 @@ The controller class extends from [[yii\rest\ActiveController]]. By specifying [
as `app\models\User`, the controller knows what model can be used for fetching and manipulating data. as `app\models\User`, the controller knows what model can be used for fetching and manipulating data.
Configuring URL Rules ## Configuring URL Rules <a name="configuring-url-rules"></a>
---------------------
Then, modify the configuration about the `urlManager` component in your application configuration: Then, modify the configuration about the `urlManager` component in your application configuration:
@ -62,8 +60,7 @@ The above configuration mainly adds a URL rule for the `user` controller so that
can be accessed and manipulated with pretty URLs and meaningful HTTP verbs. can be accessed and manipulated with pretty URLs and meaningful HTTP verbs.
Trying it Out <a name="trying-it-out"></a> ## Trying it Out <a name="trying-it-out"></a>
-------------
With the above minimal amount of effort, you have already finished your task of creating the RESTful APIs With the above minimal amount of effort, you have already finished your task of creating the RESTful APIs
for accessing the user data. The APIs you have created include: for accessing the user data. The APIs you have created include:
@ -160,8 +157,7 @@ For example, the URL `http://localhost/users?fields=id,email` will only return t
> You can and should filter out these fields as described in the [Response Formatting](rest-response-formatting.md) section. > You can and should filter out these fields as described in the [Response Formatting](rest-response-formatting.md) section.
Summary ## Summary <a name="summary"></a>
-------
Using the Yii RESTful API framework, you implement an API endpoint in terms of a controller action, and you use Using the Yii RESTful API framework, you implement an API endpoint in terms of a controller action, and you use
a controller to organize the actions that implement the endpoints for a single type of resource. a controller to organize the actions that implement the endpoints for a single type of resource.

13
docs/guide/rest-resources.md

@ -20,8 +20,7 @@ can specify what data may be returned via RESTful APIs. If the resource class do
then all its public member variables will be returned. then all its public member variables will be returned.
Fields ## Fields <a name="fields"></a>
------
When a resource object is sent in response to a RESTful API request, it involves the following two steps: When a resource object is sent in response to a RESTful API request, it involves the following two steps:
@ -51,7 +50,7 @@ http://localhost/users?fields=id,email&expand=profile
``` ```
### Overriding `fields()` ### Overriding `fields()` <a name="overriding-fileds"></a>
By default, [[yii\base\Model::fields()]] returns all model attributes as fields, while By default, [[yii\base\Model::fields()]] returns all model attributes as fields, while
[[yii\db\ActiveRecord::fields()]] only returns the attributes which have been populated from DB. [[yii\db\ActiveRecord::fields()]] only returns the attributes which have been populated from DB.
@ -98,7 +97,7 @@ public function fields()
> to filter out `auth_key`, `password_hash` and `password_reset_token`. > to filter out `auth_key`, `password_hash` and `password_reset_token`.
### Overriding `extraFields()` ### Overriding `extraFields()` <a name="overriding-extra-fields"></a>
By default, [[yii\base\Model::extraFields()]] returns nothing, while [[yii\db\ActiveRecord::extraFields()]] By default, [[yii\base\Model::extraFields()]] returns nothing, while [[yii\db\ActiveRecord::extraFields()]]
returns the names of the relations that have been populated from DB. returns the names of the relations that have been populated from DB.
@ -136,8 +135,7 @@ the request with `http://localhost/users?fields=id,email&expand=profile` may ret
``` ```
Links ## Links <a name="links"></a>
-----
[HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), an abbreviation for Hypermedia as the Engine of Application State, [HATEOAS](http://en.wikipedia.org/wiki/HATEOAS), an abbreviation for Hypermedia as the Engine of Application State,
promotes that RESTful APIs should return information that allow clients to discover actions supported for the returned promotes that RESTful APIs should return information that allow clients to discover actions supported for the returned
@ -180,8 +178,7 @@ to the user, for example,
``` ```
Collections ## Collections <a name="collections"></a>
-----------
Resource objects can be grouped into *collections*. Each collection contains a list of resource objects Resource objects can be grouped into *collections*. Each collection contains a list of resource objects
of the same type. of the same type.

117
docs/guide/structure-entry-scripts.md

@ -3,16 +3,15 @@ Entry Scripts
Entry scripts are the first chain in the application bootstrapping process. An application (either Entry scripts are the first chain in the application bootstrapping process. An application (either
Web application or console application) has a single entry script. End users make requests to Web application or console application) has a single entry script. End users make requests to
an application by accessing its entry script. entry scripts which instantiate application instances and forward the requests to them.
Entry scripts for Web applications must be stored under Web accessible directories so that they Entry scripts for Web applications must be stored under Web accessible directories so that they
can be accessed by end users. They are often named as `index.php`, but can also be any other names, can be accessed by end users. They are often named as `index.php`, but can also use any other names,
provided Web servers can locate them. For example, the URL `http://hostname/index.php` will execute provided Web servers can locate them.
the entry script `index.php`.
Entry scripts for console applications are usually stored under the [base path](structure-applications.md) Entry scripts for console applications are usually stored under the [base path](structure-applications.md)
of applications. They are often named as `yii` (with the `.php` suffix) and should be made executable of applications and are named as `yii` (with the `.php` suffix). They should be made executable
so that users can run console applications with command `./yii <route> [arguments] [options]`. so that users can run console applications through the command `./yii <route> [arguments] [options]`.
Entry scripts mainly do the following work: Entry scripts mainly do the following work:
@ -23,9 +22,14 @@ Entry scripts mainly do the following work:
* Create and configure an [application](structure-applications.md) instance; * Create and configure an [application](structure-applications.md) instance;
* Call [[yii\base\Application::run()]] to process the incoming request. * Call [[yii\base\Application::run()]] to process the incoming request.
## Web Applications <a name="web-applications"></a>
The following is the code in the entry script for the [Basic Web Application Template](start-installation.md). The following is the code in the entry script for the [Basic Web Application Template](start-installation.md).
```php ```php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true); defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev'); defined('YII_ENV') or define('YII_ENV', 'dev');
@ -43,63 +47,70 @@ $config = require(__DIR__ . '/../config/web.php');
``` ```
Configuring options in the bootstrap file ## Console Applications <a name="console-applications"></a>
-----------------------------------------
Similarly, the following is the code for the entry script of a console application:
```php
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
For each application in Yii there is at least one bootstrap file: a PHP script through which all requests are handled. For web applications, the bootstrap file is typically `index.php`; for defined('YII_DEBUG') or define('YII_DEBUG', true);
console applications, the bootstrap file is `yii`. Both bootstrap files perform nearly the same job:
1. Setting common constants. // fcgi doesn't have STDIN and STDOUT defined by default
2. Including the Yii framework itself. defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
3. Including [Composer autoloader](http://getcomposer.org/doc/01-basic-usage.md#autoloading). defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
4. Reading the configuration file into `$config`.
5. Creating a new application instance, configured via `$config`, and running that instance.
Like any resource in your Yii application, the bootstrap file can be edited to fit your needs. A typical change is to the value of `YII_DEBUG`. This constant should be `true` during development, but always `false` on production sites. // register Composer autoloader
require(__DIR__ . '/vendor/autoload.php');
The default bootstrap structure sets `YII_DEBUG` to `false` if not defined: // load application configuration
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
// load application configuration
$config = require(__DIR__ . '/config/console.php');
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
```
## Defining Constants <a name="defining-constants"></a>
Entry scripts are the best place for defining global constants. Yii supports the following three constants:
* `YII_DEBUG`: specifies whether the application is running in debug mode. When in debug mode, an application
will keep more log information, and will reveal detailed error call stacks if exceptions are thrown. For this
reason, debug mode should be used mainly during development. The default value of `YII_DEBUG` is false.
* `YII_ENV`: specifies which environment the application is running in. This has been described in
more detail in the [Configurations](concept-configurations.md#environment-constants) section.
The default value of `YII_ENV` is `'prod'`, meaning the application is running in production environment.
* `YII_ENABLE_ERROR_HANDLER`: specifies whether to enable the error handler provided by Yii. The default
value of this constant is true.
When defining a constant, we often use the code like the following:
```php ```php
defined('YII_DEBUG') or define('YII_DEBUG', false); defined('YII_DEBUG') or define('YII_DEBUG', true);
``` ```
During development, you can change this to `true`: which is equivalent to the following code:
```php ```php
define('YII_DEBUG', true); // Development only if (!defined('YII_DEBUG')) {
defined('YII_DEBUG') or define('YII_DEBUG', false); define('YII_DEBUG', true);
}
``` ```
Clearly the former is more succinct and easier to understand.
The entry script is the bootstrap PHP script that handles user requests Constant definitions should be done at the very beginning of an entry script so that they can take effect
initially. It is the only PHP script that end users can directly request to when other PHP files are being included.
execute.
In most cases, the entry script of a Yii application contains code that
is as simple as this:
~~~
[php]
// remove the following line when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// include Yii bootstrap file
require_once('path/to/yii/framework/yii.php');
// create application instance and run
$configFile='path/to/config/file.php';
Yii::createWebApplication($configFile)->run();
~~~
The script first includes the Yii framework bootstrap file `yii.php`. It
then creates a Web application instance with the specified configuration
and runs it.
Debug Mode
----------
A Yii application can run in either debug or production mode, as determined by
the value of the constant `YII_DEBUG`. By default, this constant value is defined
as `false`, meaning production mode. To run in debug mode, define this
constant as `true` before including the `yii.php` file. Running the application
in debug mode is less efficient because it keeps many internal logs. On the
other hand, debug mode is also more helpful during the development stage
because it provides richer debugging information when an error occurs.

Loading…
Cancel
Save