PHPackages                             liuxingwei/simple-api-framework - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. liuxingwei/simple-api-framework

ActiveLibrary[Framework](/categories/framework)

liuxingwei/simple-api-framework
===============================

A simple API framework.

0.0.53(6y ago)212MITPHPPHP &gt;=5.6.0

Since Sep 21Pushed 6y ago1 watchersCompare

[ Source](https://github.com/Liuxingwei/php-simple-api-framework)[ Packagist](https://packagist.org/packages/liuxingwei/simple-api-framework)[ RSS](/packages/liuxingwei-simple-api-framework/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (2)Versions (54)Used By (0)

SAF 框架使用说明
==========

[](#saf-框架使用说明)

零、概述
----

[](#零概述)

`SAF（Simple Api Framework）`是一个极简单的`PHP` `API`开发框架，适用于前后端分离架构的`web`项目，作为后端`PHP` `API`服务的框架。

说其极简，一方面是因为它只有很少的核心类和几个支持文件，另一方面是因为它只支持有限的场景，当然，也是说它非常易于使用。

`SAF`没有`Beautiful URL`路由，`GET`请求的参数是通过形如`name=zhangsan&sex=male`的`QueryString`参数传递的。

`SAF`遵循了惯例优于配置的理念，`API`必须放在指定的目录（项目目录的`Application\Api`）下，且`GET`请求对应的`API`类要放在`Get`子目录，而`POST`请求对应的`API`类要放在`Post`子目录，其他类型的`HTTP`请求对应的`API`，也放在与其`HTTP METHOD`相对应的子目录。

数据库方面，`SAF`有一个简单的`DB`类，它是以`PDO`为底层的，理论上它可以支持多种数据库服务，但是目前只在`MySQL`上做过测试。因此最适合的数据库搭配就是`MySQL5.7+`。

对于`PHP`，由于`7.2.*`和其前的版本，在`trait`特性支持上有缺陷（引用继承了同一`trait`的多个`trait`时，会导致重复定义方法的致命错误），因此建议`PHP 7.3+`。

一、环境要求
------

[](#一环境要求)

支持`PHP 5.6`，建议`PHP 7.3+`，`MySQL 5.7+`。

二、下载
----

[](#二下载)

### 1. composer

[](#1-composer)

```
composer create-project liuxingwei/simple-api-framework
```

### 2. github

[](#2-github)

```
git clone https://github.com/Liuxingwei/php-simple-api-framework.git
```

三、环境搭建
------

[](#三环境搭建)

有如下几种方式，任选其一（前两种方式仅适用于开发、测试环境）：

### 1、PHP Built-in Server

[](#1php-built-in-server)

使用`PHP`内建服务时，无需`nginx`、`apache`，只需`PHP`。

在命令行下，切换至`public`文件夹（`safpath`指`SAF`的路径），执行`php -S localhost:xxxx index.php`即可，其中`xxxx`为端口号。

示例：

```
>cd safpath/public
>php -S localhost:xxxx index.php
```

浏览器打开`localhost:xxxx`，看到如下内容，服务启动成功：

```
Please access detail API.
```

### 2、借助 VSCode 中 PHP Server 插件

[](#2借助-vscode-中-php-server-插件)

安装`PHP Server`插件，打开`File > Preferences > Settings`，找到`Extensions > PHP Server Configuration`，将`Relative Path`改为`./public`。

如果`PHP`可执行文件没加到系统路径中，可以将其填写在`PHP Server`插件的`PHP Path`配置项中。

打开`public/index.php`文件，在文件窗口右键，选`PHP Server： Server Project`。

浏览器打开`localhost:xxxx`，看到如下内容，服务启动成功：

```
Please access detail API.
```

`PHP Server: Stop`可以停止服务。

`PHP Server: Reload Server`可以重启服务。

### 3、使用 WAMP

[](#3使用-wamp)

启动`WAMP`，点进托盘区`WAMP`图标，选择`Apache > httpd-vhosts.conf`文件。

在打开的文件中，复制`VirtualHost`段，修改端口，并将路径修改为项目目录的`public`文件夹。

示例（`safpath`即指`SAF`的路径）：

要复制的段：

```

  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"

    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local

```

复制后修改`IP`和`DocumentRoot`、`Directory`路径：

```

  ServerName localhost
  ServerAlias localhost
  DocumentRoot "safpath/public"

    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local

```

修改后的完整文件：

```

  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"

    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local

  ServerName localhost
  ServerAlias localhost
  DocumentRoot "safpath/public"

    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local

```

重启`Apache`。

浏览器打开`localhost:xxxx`，看到如下内容，服务启动成功：

```
Please access detail API.
```

### 4. nginx

[](#4-nginx)

添加一个`server`配置：

```
server {
        listen xxxx default_server;
        listen [::]:xxxx default_server;

        server_name _;

        root safpath/public;

        location / {
                try_files $uri $uri/ =404;
                if (!-e $request_filename) {
                    rewrite  ^(.*)$  /index.php$1  last;
                }
        }

        location ~ \.php(.*)$ {
                include snippets/fastcgi-php.conf;
                fastcgi_split_path_info ^(.+\.php)(/.*)$;
                # With php-fpm (or other unix sockets):
                fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
                # With php-cgi (or other tcp sockets):
                # fastcgi_pass 127.0.0.1:9000;
        }

        location ~ /\.ht {
                deny all;
        }
}
```

重启`nginx`。

四、目录结构
------

[](#四目录结构)

初始的项目目录结构如下：

```
+ application
  + Api
    + Delete
      + Example
        - Index.php
    + Get
      + Example
        - Index.php
    + Patch
      + Example
        - Index.php
    + Post
      + Example
        - Index.php
    + Put
      + Example
        - Index.php
  + Model
    - SafExample.php
  + Validations
    - MyValidation.php
+ conf
  + err_define
    - cn.php.sample
    - default.php
  - config.php.sample
  - di_config.php.sample
  - env.php.sample
+ doc
  - DB-Class-Usage.md
+ lib
  + Core
    - App.php
    - BaseApiInterface.php
    - BaseModel.php
    - bootstrap.php
    - DB.php
    - ErrorCode.php
    - ErrorCodeTrait.php
    - Request.php
    - Response.php
    - SafException.php
  + Validations
    - AbstractValidation.php
    - Length.php
    - Limit.php
    - NotEmpty.php
    - Required.php
    - Rule.php
+ public
  - .htaccess
  - index.html
  - index.php
+ vendor
  + bin
  + composer
  + doctrine
  + jeremeamia
  + liuxingwei
  + nikic
  + php-di
  + psr
  + symfony
  - autoload.php
- .gitignore
- composer.json
- composer.lock
- LICENSE
- README.md
```

五、创建`API`
---------

[](#五创建api)

在`application/Api/Get`或`application/Api/Post`中根据业务需要创建一个子文件夹（也可以是多级文件夹），在其中创建一个`API`类。

该类实现`Lib\Core\Interfaces\BaseApi`接口，并实现`run()`方法，该方法签名为：`run(array $param):mixed`。

例如，在`Get`文件夹创建`Example`文件夹，并在其中创建`Index.php`，文件内容如下：

```
