# 入门（Getting started）

> 原文：[Getting started](https://github.com/zircote/swagger-php/blob/master/docs/Getting-started.md)\
> 翻译：小虾米（QQ:509129）

## 入门（Getting started）

swagger-php 的目的是使用phpdoc注释来生成一个swagger.json。

输出（To output）:

```
{
   "swagger": "2.0",
   "schemes": ["http"],
   "host": "example.com",
   "basePath": "/api"
}
```

写（Write）:

```php
/**
 * @SWG\Swagger(
 *   schemes={"http"},
 *   host="example.com",
 *   basePath="/api"
 * )
 */
```

注意，教条注释支持数组，但是使用 `{` 和 `}` 而不是 `[`和 `]`。

虽然教条也支持对象，但也使用 `{`和 `}`，要求将属性名用 `“` 包围。

不要写（**DON'T** write）:

```php
/**
 * @SWG\Swagger(
 *   info={
 *     "title"="My first swagger documented API",
 *     "version"="1.0.0"
 *   }
 * )
 */
```

但可以使用与属性同名的注释，例如 @SWG\Info 为 info：

```php
/**
 * @SWG\Swagger(
 *   @SWG\Info(
 *     title="My first swagger documented API",
 *     version="1.0.0"
 *   )
 * )
 */
```

这增加了验证，因此当您误拼属性或忘记了所需的属性时，它将触发php警告。例如，如果你写 `titel="My first ...` swagger-php 会产生一个 "Unexpected field "titel" for @SWG\Info(), expecting "title", ..."的notice。

使用变量注释

### 使用变量注释（Using variables in annotations）

你可以在教条注解中使用常数。

```php
define("API_HOST", ($env === "production") ? "example.com" : "localhost");
```

```php
/**
 * @SWG\Swagger(host=API_HOST)
 */
```

当您使用CLI时，您需要使用 `--bootstrap` 选项将php文件包含在其中。

```
$ swagger --bootstrap constants.php
```

### 注释的位置（Annotation placement）

您不应该将所有注释放在一个大的 `@SWG\Swagger()` 注释块中，而是将它们分散到整个代码库中。swagger-php 将扫描您的项目并将所有注释合并到一个 `@SWG\Swagger` 注释中。

最大好处是swagger-php提供文档贴近实现api的代码。

#### 对象和数组（Arrays and Objects）

将同一类型的多个注释放置在一个对象数组中。对于对象，属性的约定是使用与注释相同的字段名：response 在 `@SWG\Response`，property 在 `@SWG\Property`，等等

```php
/**
 * @SWG\Get(
 *   path="/products",
 *   summary="list products",
 *   @SWG\Response(
 *     response=200,
 *     description="A list with products"
 *   ),
 *   @SWG\Response(
 *     response="default",
 *     description="an ""unexpected"" error"
 *   )
 * )
 */
```

生成（Generates）:

```php
{
  "swagger": "2.0",
  "paths": {
    "/products": {
      "get": {
        "summary": "list products",
        "responses": {
          "200": {
            "description": "A list with products"
          },
          "default": {
            "description": "an \"unexpected\" error"
          }
        }
      }
    }
  },
  "definitions": []
}
```

#### Swagger-PHP 检测基于上下文的值（Swagger-PHP detects values based on context）

Swagger-PHP着眼于减少重复的注释上下文。

```php
/**
 * @SWG\Definition()
 */
class Product {

    /**
     * The product name
     * @var string
     * @SWG\Property()
     */
    public $name;
}
```

结果（results in）:

```php
{
  "swagger": "2.0",
  "definitions": {
    "Product": {
      "properties": {
        "name": {
          "type": "string",
          "description": "The product name"
        }
      }
    }
  }
}
```

如果你写成（As if you'd written）：

```php
    /**
     * The product name
     * @var string
     *
     * @SWG\Property(
     *   property="name",
     *   type="string",
     *   description="The product name"
     * )
     */
    public $name;
```

### 不要重复自己（Don't Repeat Yourself）：

在请求或响应中，多个请求有一些重叠是很常见的。该规范通过使用 `$ref S`解决了大多数问题

```php
    /**
     * @SWG\Definition(
     *   definition="product_id",
     *   type="integer",
     *   format="int64",
     *   description="The unique identifier of a product in our catalog"
     * )
     */
```

结果（results in）:

```php
{
    "swagger": "2.0",
    "paths": {},
    "definitions": {
        "product_id": {
            "description": "The unique identifier of a product in our catalog",
            "type": "integer",
            "format": "int64"
        }
    }
}
```

它本身什么都不做但是现在你可以用json的路径 `#/definitions/product_id` 来引用这篇文章

```php
    /**
     * @SWG\Property(ref="#/definitions/product_id")
     */
    public $id;
```

要了解更多关于refs的技巧，请浏览 [using-refs](https://github.com/zircote/swagger-php/tree/master/Examples/using-refs) 示例。

### Vendor 扩展（Vendor extensions）

该规范允许自定义属性（[custom properties](http://swagger.io/specification/#vendorExtensions)），只要它们以 “x-” 开头，所有的大小写php注释都有一个 `x` 属性，将展开为 “x-” 属性。

```php
/**
 * @SWG\Info(
 *   title="Example",
 *   version=1,
 *   x={"some-name":"a-value", "another": 2}
 * )
 */
```

结果（results in）:

```php
"info": {
    "title": "Example",
    "version": 1,
    "x-some-name": "a-value",
    "x-another": 2
},
```

例如，Amazon API网关（[Amazon API Gateway](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html)）就利用了这些。

### 关于Swagger的更多信息（More information about Swagger）

要查看哪个输出映射到哪个注释签查看[swagger-explained](http://bfanger.github.io/swagger-explained/)，这也包含了[swagger 规范](http://swagger.io/specification/)的片段


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/swagger/swagger-php-wen-dang/ru-men-ff08-getting-started.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
