Commit 011284dd by Qiang Xue

guide WIP

parent d622442a
......@@ -30,7 +30,7 @@ Getting Started
Application Structure
---------------------
* **TBD** [Entry Scripts](structure-entry-scripts.md)
* [Entry Scripts](structure-entry-scripts.md)
* **TBD** [Applications](structure-applications.md)
* [Controllers and Actions](structure-controllers.md)
* [Views](structure-views.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).
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
action for the requested resource. This process is called *authorization* which is covered in detail in
......
......@@ -25,8 +25,7 @@ will be described in detail in the next few sections:
* 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
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).
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
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]].
### Customizing Actions
### Customizing Actions <a name="customizing-actions"></a>
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.
### 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
to access and manipulate the requested resource(s). With [[yii\rest\ActiveController]], this can be done
......
......@@ -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.
Creating a Controller
---------------------
## Creating a Controller <a name="creating-controller"></a>
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.
Configuring URL Rules
---------------------
## Configuring URL Rules <a name="configuring-url-rules"></a>
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.
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
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.
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
a controller to organize the actions that implement the endpoints for a single type of resource.
......
......@@ -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.
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:
......@@ -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
[[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`.
### Overriding `extraFields()`
### Overriding `extraFields()` <a name="overriding-extra-fields"></a>
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.
......@@ -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,
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
of the same type.
......
......@@ -3,16 +3,15 @@ Entry Scripts
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
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
can be accessed by end users. They are often named as `index.php`, but can also be any other names,
provided Web servers can locate them. For example, the URL `http://hostname/index.php` will execute
the entry script `index.php`.
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.
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
so that users can run console applications with command `./yii <route> [arguments] [options]`.
of applications and are named as `yii` (with the `.php` suffix). They should be made executable
so that users can run console applications through the command `./yii <route> [arguments] [options]`.
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;
* 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).
```php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
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
console applications, the bootstrap file is `yii`. Both bootstrap files perform nearly the same job:
defined('YII_DEBUG') or define('YII_DEBUG', true);
1. Setting common constants.
2. Including the Yii framework itself.
3. Including [Composer autoloader](http://getcomposer.org/doc/01-basic-usage.md#autoloading).
4. Reading the configuration file into `$config`.
5. Creating a new application instance, configured via `$config`, and running that instance.
// fcgi doesn't have STDIN and STDOUT defined by default
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
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
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
define('YII_DEBUG', true); // Development only
defined('YII_DEBUG') or define('YII_DEBUG', false);
if (!defined('YII_DEBUG')) {
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
initially. It is the only PHP script that end users can directly request to
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.
Constant definitions should be done at the very beginning of an entry script so that they can take effect
when other PHP files are being included.
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