A PHP framework foucs on API fast development.接口,从简单开始!PhalApi简称π框架,一个轻量级PHP开源接口框架,专注于接口服务开发。

Last update: Jun 28, 2022

apic

PhalApi开源接口框架 / PhalApi API Framework

读音:派框架

Latest Stable Version Total Downloads Latest Unstable Version License

Stargazers over time

Stargazers over time

开发文档 / Documents

专为PHPer准备的优雅而详细的开发文档,请看:PhalApi 2.x 开发文档
PhalApi 2.x English Docs.

在线示例 / Demo

快速安装 / Install

composer一键安装 / Install by composer

使用composer创建项目的命令,可实现一键安装。

One-click installation can be achieved by using the command of composer to create a project.

$ composer create-project phalapi/phalapi

温馨提示:关于composer的使用,请参考Composer 中文网 / Packagist 中国全量镜像

手动下载安装 / Download and Install manually

或者,也可以进行手动安装。将此Git项目代码下载解压后,进行可选的composer更新,即:
Alternatively, manual installation is also possible. Download PhalApi Project master-2x branch Source code. After downloading and unzipping, perform an optional composer update:

$ composer update

部署 / Deployment

Nginx配置 / Nginx Configuration

如果使用的是Nginx,可参考以下配置。
If you are using Nginx, you can refer to the following configuration.

server {
    listen 80;
    server_name dev.phalapi.net;
    # 将根目录设置到public目录
    root /path/to/phalapi/public;
    charset utf-8;

    location / {
        index index.php;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # 根据当前环境,选择合适的通讯方式
        # fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

配置时需要将网站根目录设置到public目录,配置保存后重启nginx。
Point the root path of the visit to public folder. Save and reload nginx.

温馨提示:推荐将访问根路径指向/path/to/phalapi/public。
Tips: It is recommended to point the root path of the visit to /path/to/phalapi/public.

数据库配置 / Database Configuration

如何使用的是MySQL数据库,参考修改./config/dbs.php数据库配置。
If you are using MySQL, please edit ./config/dbs.php.

return array(
    /**
     * DB数据库服务器集群 / database cluster
     */
    'servers' => array(
        'db_master' => array(                       // 服务器标记 / database identify
            'type'      => 'mysql',                 // 数据库类型,暂时只支持:mysql, sqlserver / database type
            'host'      => '127.0.0.1',             // 数据库域名 / database host
            'name'      => 'phalapi',               // 数据库名字 / database name
            'user'      => 'root',                  // 数据库用户名 / database user
            'password'  => '',	                    // 数据库密码 / database password
            'port'      => 3306,                    // 数据库端口 / database port
            'charset'   => 'UTF8',                  // 数据库字符集 / database charset
            'pdo_attr_string'   => false,           // 数据库查询结果统一使用字符串,true是,false否
            'driver_options' => array(              // PDO初始化时的连接选项配置
                // 若需要更多配置,请参考官方文档:https://www.php.net/manual/zh/pdo.constants.php
            ),
        ),
    ),

    // 更多代码省略……
);

最后,需要给runtime目录添加写入权限。更多安装说明请参考文档下载与安装
At last, add writeable permission to folder runtime. For more detail about installation, refer to Download and Installation.

使用 / Usage

调用接口 / API Request

在PhalApi,你可以通过service参数(短名字是s参数)指定需要调用的接口服务。例如,访问默认接口服务。

For PhalApi, the default communicate protocol is HTTP/HTTPS. According to the specific implementation of the API service, we could use GET or POST to request. By default, you can specify the service parameter or s for short when requesting. The default API service is App.Site.Index.

对应执行的PHP代码在./src/app/Api/Site.php文件,源码片段如下:
The source PHP code of App.Site.Index API service is at ./src/app/Api/Site.php file.

<?php
namespace App\Api;
use PhalApi\Api;

/**
 * 默认接口服务类
 * @author: dogstar <[email protected]> 2014-10-04
 */
class Site extends Api {
    public function getRules() {
        return array(
            'index' => array(
                'username'  => array('name' => 'username', 'default' => 'PhalApi', 'desc' => '用户名'),
            ),
        );
    }

    /**
     * 默认接口服务
     * @desc 默认接口服务,当未指定接口服务时执行此接口服务
     * @return string title 标题
     * @return string content 内容
     * @return string version 版本,格式:X.X.X
     * @return int time 当前时间戳
     * @exception 400 非法请求,参数传递错误
     */
    public function index() {
        return array(
            'title' => 'Hello ' . $this->username,
            'version' => PHALAPI_VERSION,
            'time' => $_SERVER['REQUEST_TIME'],
        );
    }
}

接口请求后结果输出类似如下:
API result as below after requesting:

{
    "ret": 200,
    "data": {
        "title": "Hello PhalApi",
        "version": "2.4.2",
        "time": 1501079142
    },
    "msg": ""
}

运行效果,截图如下:
Runtime Sreenshot:

_20190201151943

查看在线接口文档 / Visit Online API List Documents

PhalApi会根据你编写的接口的参数配置和代码注释,自动实时生成在线接口文档。在线接口文档链接为:
PhalApi will generate realtime online API documents automatically by PHP code and PHP comments. You can visit them by:

浏览效果类似如下:
Preview:

进入Portal运营平台 / Use Portal Platform

PhalApi采用了当前流行且优秀的layuimin开发全新的管理后台,专门提供给非技术的运营人员使用(技术人员也可使用)。安装Portal前请先配置好数据库连接。如果需要单独升级Portal,可进入应用市场免费下载到本地后安装升级。

PhalApi provides a new management system and we name it Portal.

翻译 / i18n

修改./public/init.php文件,可设置当前语言。
Edit ./public/init.php file to set current language.

// 翻译语言包设定-简体中文
\PhalApi\SL('zh_cn');

// Setting language to English
\PhalApi\SL('en');

一张图告诉你如何使用PhalApi 2.x / All in One Picture

phalapi-install

子项目 / Sub Projects

还有问题,怎么办?/ Any Question?

如发现问题,或者任何问题,欢迎提交Issue到这里,或进入PhalApi开源社区
如果喜欢,请帮忙在Github码云给个Star,也可以对PhalApi进行捐赠哦 ^_^。

Welcome to report any issue here.
If you like PhalApi, welcome to give us a Star at Github.

开源许可协议 / Licence

Apache 2.0,Apache Licence是著名的非盈利开源组织Apache采用的协议。该协议和BSD类似,同样鼓励代码共享和尊重原作者的著作权,同样允许代码修改,再发布(作为开源或商业软件)。

GitHub

https://github.com/phalapi/phalapi
Comments
  • 1. 关于多数据库访问

    我有一组服务器A,B,C,D数据库结构完全一样.

    我有时需要访问服务器A的,有时需要访问的是服务器B的.

    除了为每个服务器的数据库建不同名的MODEL,有没有什么更好的方法?

    我目前是使用同一个MODEL,但在使用之前先判断当前要访问的是哪个数据库,预先修改默认服务器指向.

    但是这样子无法同时调取两个服务器的数据.

    Reviewed by chenall at 2018-05-17 08:08
  • 2. 按照官方手册添加Nginx配置文件api.phalapi.net后无法重启Nginx

    我添加的配置如下:

    server { listen 80 ; server_name api.phalapi.net; #设置成自己的服务器的域名能远程访问了。

        root /home/ubuntu/PhalApi/Public;
        charset utf-8;
    
        # Add index.php to the list if you are using PHP
        index index.html index.htm index.php index.nginx-debian.html;
        location / {
                index index.html index.htm index.php;
                try_files $uri $uri/ =404;
        }
        location ~ \.php$ {
                root /home/ubuntu/PhalApi/Public;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
    

    官方给的参考配置也尝试过,同样无效。

    Reviewed by JamesZhan107 at 2018-11-10 14:37
  • 3. 关于事务操作

    目前的事务操作是类似于这样子的

    \PhalApi\DI()->notorm->beginTransaction('db_demo');
    

    这就要求必须要知道当前操作的数据库名称.

    为什么不改到NotORMModel里面去实现这个功能?

    这样子的话操作事物可能就会比较方便

    直接在Model里面可以快速开启事物

    $this->getORM()->beginTransaction();
    
    Reviewed by chenall at 2018-07-07 09:26
  • 4. 关于请求参数规则(意见)

    使用这个框架有一段时间了,目前有一个小问题,就是关于参数规则的.

    个人觉得目前的参数规则的编写方式应该还有改进的余地,我的考虑主要有两点(主要还是懒^_^)

    1. 复用(可能好几个API里面有参数都是一样的).
    2. 编辑器友好(API参数传递给D之后我希望在D里面可以有代码提示,知道有哪些参数)

    当然了这些只有个人的想法,不知有没有人愿意去实现?

    Reviewed by chenall at 2018-06-26 14:06
  • 5. Response返回data,200为对象,其他为数组

    Response返回data,200为对象,其他(400,401等)为数组 这样会造成app端 json解析有问题, 查看源代码发现,data默认为array,而返回400的时候没有对data进行赋值

    { "ret": 200, "data": { "title": "Hello PhalApi", "version": "2.2.0", "time": 1519691269 }, "msg": "", }

    { "ret": 400, "data": [], "msg": "非法请求:用户不存在." }

    建议在PhalApi类中,第54行增加 $rs->setMsg((object)[]); 对默认值的类型进行修改.

    Reviewed by Jackfinal at 2018-02-27 01:14
  • 6. 可否添加一个“是否在不匹配时显示正则内容”的开关?

    假设 getRules 中的正则如下:

    'regex' => "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i",
    

    我故意输入一个:email=asd,然后会提示:

    非法请求:email无法匹配/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i
    

    一般来说,这样的提示不应该只在开发环境下才会有的么?生产环境暴露正则的具体内容,可能会导致正则被绕过,从而引发安全问题。

    这个提示是 StringFormatter#filterByRegex 发出来的,我没有在里面找到关闭它的方法。

    Reviewed by RexSkz at 2017-09-10 13:22
  • 7. ?s=App.User_User.CheckSession

    " \nFatal error: Uncaught Error: Call to a member function isLogin() on null in /usr/local/nginx/html/phalapi/src/app/Api/User/User.php:103\nStack trace:\n#0 [internal function]: App\Api\User\User->checkSession()\n#1 /usr/local/nginx/html/phalapi/vendor/phalapi/kernal/src/PhalApi.php(53): call_user_func(Array)\n#2 /usr/local/nginx/html/phalapi/public/index.php(9): PhalApi\PhalApi->response()\n#3 {main}\n thrown in /usr/local/nginx/html/phalapi/src/app/Api/User/User.php on line 103 \n"

    这个接口一直报500错误,但是看官方示例没问题。

    Reviewed by pycamel at 2021-01-24 11:38
  • 8. 规则验证require和min先后问题

    'page' => array('name' => 'page', 'type' => 'int', 'min' => 1, 'require' => false, 'default' => 1, 'desc' => '分页'),

    分页参数是可选,但是配置了min,没有传递该参数则报错, 正常逻辑是否应为require为true之后在判断min 这个算是bug? 版本:2.12.2

    Reviewed by HOBERHUNTER at 2020-04-03 09:05
  • 9. https访问docs文档含有http链接的不安全问题

    当我访问在线接口列表的时候,浏览器会提示此页面包含其他不安全的资源,希望将所有http链接诸如"http://cdn7.phalapi.net/20180316214150_f6f390e686d0397f1f1d6a66320864d6"、"http://docs.phalapi.net/#/v2.0/"、"http://www.phalapi.net/"、"http://pro.phalapi.net/"替换为https链接

    Reviewed by gaoweifan at 2020-02-07 03:21
  • 10. 可以贴下详细的报错信息吗?谢谢

    可以贴下详细的报错信息吗?谢谢

    Request URL: http://localhost/phalapi/public/?s=App.Hello.World&debug=1 Request Method: GET Status Code: 500 Internal Server Error Remote Address: [::1]:80 Referrer Policy: no-referrer-when-downgrade Connection: close Content-Length: 0 Content-Type: text/html; charset=UTF-8 Date: Tue, 29 Oct 2019 05:08:42 GMT Server: Apache/2.4.34 (Unix) PHP/7.1.23 X-Powered-By: PHP/7.1.23 s: App.Hello.World debug: 1

    Reviewed by kingswjw at 2019-10-29 05:09
  • 11. 关于notorm的top参数

        protected function topString( $limit){
            if(isset($limit) && ($this->notORM->driver == "dblib" || $this->notORM->driver == "mssql" || $this->notORM->driver == "sqlsrv")){
                return " TOP ($this->limit)"; //! offset is not supported
            }
            return "";
        }
    

    我使用的是freetds+sqlserver, 发现sqlserver不支持这种语法会报错.

    必须去掉括号,这边如果改成以下的对其它数据库会有影响吗?

     return " TOP $this->limit"; //! offset is not supported
    
    Reviewed by chenall at 2019-05-05 09:08
  • 12. 在pgsql数据库中 where 问题

    无巧 16:38:33 @打杂-dogstar 在pgsql数据库中 $where['abc'] = ['2','3']; 应该是abc in ('2','3')

    $where['abc IN'] = '2,3' 应该也是 abc in ('2','3')

    但返回是错误的,请留意新版需要处理一下!

    Reviewed by phalapi at 2019-10-29 08:41
  • 13. URI路由匹配问题

    你好! 我已经开启 'enable_uri_match' => true 并且配置apache如下 RewriteEngine on RewriteBase /

    RewriteCond %{HTTP_HOST} ^dev.api.net$
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    RewriteCond %{REQUEST_URI} !^/phalapi/public/
    RewriteRule ^(.*)$ /phalapi/public/$1
    RewriteRule ^(/)?$ index.php [L]
    

    报错如下: Not Found The requested URL /phalapi/public/App/Hello/World was not found on this server.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    请问怎么配置呢?

    Reviewed by imguoc at 2019-09-18 03:30
  • 14. sqlserver使用limit分页问题

    sqlserver使用limit分页: $this->getORM() ->select('*') ->limit(($page - 1) * $perpage, $perpage) ->fetchAll(); 会出现偏移量不起作用的情况,返回的结果始终是($page - 1) * $perpage的条数

    Reviewed by hp628 at 2019-08-17 15:30
30 seconds of code Short PHP code snippets for all your development needs
30 seconds of code Short PHP code snippets for all your development needs

30 seconds of code Short PHP code snippets for all your development needs Visit our website to view our snippet collection. Use the Search page to fin

Jun 19, 2022
FluxBB is a fast, light, user-friendly forum application for your website.

FluxBB 1.5 Readme About FluxBB is an open source forum application released under the GNU General Public Licence. It is free to download and use and w

Jun 27, 2022
A php API documentation generator, fork of Sami

Doctum, a PHP API documentation generator. Fork of Sami Curious about what Doctum generates? Have a look at the MariaDB MySQL Kbs or Laravel documenta

Jun 20, 2022
phpDocumentor is an application that is capable of analyzing your PHP source code and DocBlock comments to generate a complete set of API Documentation

phpDocumentor What is phpDocumentor? phpDocumentor is an application that is capable of analyzing your PHP source code and DocBlock comments to genera

Jun 23, 2022
An API documentation generator

Sami: an API documentation generator WARNING: Sami is not supported nor maintained anymore. Feel free to fork. Curious about what Sami generates? Have

Jun 20, 2022
Generates documentation for your REST API from annotations

NelmioApiDocBundle The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs. Migrate from 3.x to 4.0 To migrate from

Jun 24, 2022
Yii2 Annotations Generate API Document Extension
 Yii2 Annotations Generate API Document Extension

Generate online api document by code annotation for yii2 easily

Dec 15, 2021
Sami: an API documentation generator

Sami: an API documentation generator WARNING: Sami is not supported nor maintained anymore. Feel free to fork. Curious about what Sami generates? Have

Jun 20, 2022
Generate interactive OpenAPI documentation for your RESTful API using doctrine annotations

Generate interactive OpenAPI documentation for your RESTful API using doctrine annotations

Jun 23, 2022
PHP 7.1 ready Smart and Simple Documentation for your PHP project
PHP 7.1 ready Smart and Simple Documentation for your PHP project

Smart and Readable Documentation for your PHP project ApiGen is the simplest, the easiest to use and the most modern api doc generator. It is all PHP

Jun 6, 2022
PHP 7.1 ready Smart and Simple Documentation for your PHP project
PHP 7.1 ready Smart and Simple Documentation for your PHP project

Smart and Readable Documentation for your PHP project ApiGen is the simplest, the easiest to use and the most modern api doc generator. It is all PHP

Apr 20, 2021
Learn how to implement the most important Design Patterns into your PHP application, uses PHP 8.1
Learn how to implement the most important Design Patterns into your PHP application, uses PHP 8.1

Learn how to implement the most important Design Patterns into your PHP application. This project uses PHP 8.1. it has examples for each Pattern and an Article explaining how to use them step by step, their advantages, and disadvantages.

Jun 24, 2022
Documentation Generator for PHP

phpDocumentor What is phpDocumentor? phpDocumentor is an application that is capable of analyzing your PHP source code and DocBlock comments to genera

Jun 28, 2022
Documentation generator for PHP Code using standard technology (SRC, DOCBLOCK, XML and XSLT)

phpDox phpDox is a documentation generator for PHP projects. This includes, but is not limited to, API documentation. The main focus is on enriching t

Jun 20, 2022
Industrial-strength annotations for PHP

php-annotations Source-code annotations for PHP. Copyright (C) 2011-2015 Rasmus Schultz [email protected] https://github.com/php-annotations/php-anno

Mar 30, 2022
Source Code for 'PHP 8 Solutions' by David Powers
Source Code for 'PHP 8 Solutions' by David Powers

Apress Source Code This repository accompanies PHP 8 Solutions by David Powers (Apress, 2022). Download the files as a zip using the green button, or

Apr 19, 2022
PHP Developer Roadmap
PHP Developer Roadmap

This is PHP Developer Roadmap

Jun 23, 2022
PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.
PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.

PhpMetrics provides metrics about PHP project and classes, with beautiful and readable HTML report.

Jun 21, 2022
li₃ is the fast, flexible and most RAD development framework for PHP

li₃ You asked for a better framework. Here it is. li₃ is the fast, flexible and the most RAD development framework for PHP. A framework of firsts li₃

Jun 30, 2022
Blazing fast macOS PHP development environment
Blazing fast macOS PHP development environment

Introduction Valet+ is a development environment for macOS. No Vagrant, no Docker, no /etc/hosts file. Go here for the valet+ documentation. Credits T

Jun 17, 2022