Home  >  Article  >  Backend Development  >  Detailed explanation of how to call interfaces and write interface code in php

Detailed explanation of how to call interfaces and write interface code in php

伊谢尔伦
伊谢尔伦Original
2018-05-18 10:13:1016147browse

For example: http://localhost/openUser.php?act=get_user_list&type=json
Here openUser.php is equivalent to an interface, where get_user_list is an API (Get user list), Pay attention to the data type returned being in JSON format.
You only need to execute this link in your PHP code and it will return.
Direct use of GET method

$file_contents = file_get_content('http://localhost/openUser.php?act=get_user_list&type=json')

POST method must use the following (PHP curl support needs to be enabled).

$url = 'http://localhost/openUser.php?act=get_user_list&type=json';
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt ( $ch, CURLOPT_POST, 1 ); //启用POST提交
$file_contents = curl_exec ( $ch );
curl_close ( $ch );

Writing interfaces in PHP

1. First, briefly answer two questions:
1. Can PHP develop clients?
Answer: No, because PHP is a scripting language and is responsible for completing the S part of the B/S architecture or C/S architecture, that is, the development of the server. (Don’t worry about GTK and WinBinder)
2. Why choose PHP as your first choice for server development?
Answer: Cross-platform (can run under UNIX, LINUX, WINDOWS, Mac OS), low consumption (PHP consumes very few system resources), high operating efficiency (relatively speaking), and the perfect partner of MySQL. It is Free and open source,...

2. How to use PHP to develop API (Application Programming Interface, Application Programming Interface)?

People who have done API should understand that actually developing API is simpler than developing WEB, but the logic may be more complex, because API is actually data output without rendering the page, so there is no MVC ( API only has M and C),
1. Just like WEB development, you first need some relevant parameters. These parameters will be passed by the client, maybe GET or POST. This needs to be agreed upon by the development team. , or develop unified specifications.
2. With parameters, complete data processing according to application requirements, such as: task progress update, APP in-app purchase, data submission at the end of a game, etc.
3. After the data logic is processed, return to the client Related data that need to be used, such as: mission status, in-app purchase results, player information, etc.
How to return the data to the client?
Direct output form, such as: JSON, XML, TEXT, etc.
4. After the client obtains the data you returned, it interacts with the user locally
A simple API example written temporarily:

<?php
$output = array();
$a = @$_GET[&#39;a&#39;] ? $_GET[&#39;a&#39;] : &#39;&#39;;
$uid = @$_GET[&#39;uid&#39;] ? $_GET[&#39;uid&#39;] : 0;
if (empty($a)) {
    $output = array(&#39;data&#39;=>NULL, &#39;info&#39;=>&#39;坑爹啊!&#39;, &#39;code&#39;=>-201);
    exit(json_encode($output));
}
//走接口
if ($a == &#39;get_users&#39;) {
    //检查用户
    if ($uid == 0) {
        $output = array(&#39;data&#39;=>NULL, &#39;info&#39;=>&#39;The uid is null!&#39;, &#39;code&#39;=>-401);
        exit(json_encode($output));
    }
    //假设 $mysql 是数据库
    $mysql = array(
        10001 => array(
            &#39;uid&#39;=>10001,
            &#39;vip&#39;=>5,
            &#39;nickname&#39; => &#39;Shine X&#39;,
            &#39;email&#39;=>&#39;979137@qq.com&#39;,
            &#39;qq&#39;=>979137,
            &#39;gold&#39;=>1500,
            &#39;powerplay&#39;=> array(&#39;2xp&#39;=>12,&#39;gem&#39;=>12,&#39;bingo&#39;=>5,&#39;keys&#39;=>5,&#39;chest&#39;=>8),
            &#39;gems&#39;=> array(&#39;red&#39;=>13,&#39;green&#39;=>3,&#39;blue&#39;=>8,&#39;yellow&#39;=>17),
            &#39;ctime&#39;=>1376523234,
            &#39;lastLogin&#39;=>1377123144,
            &#39;level&#39;=>19,
            &#39;exp&#39;=>16758,
        ),
        10002 => array(
            &#39;uid&#39;=>10002,
            &#39;vip&#39;=>50,
            &#39;nickname&#39; => &#39;elva&#39;,
            &#39;email&#39;=>&#39;elva@ezhi.net&#39;,
            &#39;qq&#39;=>NULL,
            &#39;gold&#39;=>14320,
            &#39;powerplay&#39;=> array(&#39;2xp&#39;=>1,&#39;gem&#39;=>120,&#39;bingo&#39;=>51,&#39;keys&#39;=>5,&#39;chest&#39;=>8),
            &#39;gems&#39;=> array(&#39;red&#39;=>13,&#39;green&#39;=>3,&#39;blue&#39;=>8,&#39;yellow&#39;=>17),
            &#39;ctime&#39;=>1376523234,
            &#39;lastLogin&#39;=>1377123144,
            &#39;level&#39;=>112,
            &#39;exp&#39;=>167588,
        ),
        10003 => array(
            &#39;uid&#39; => 10003,
            &#39;vip&#39; => 5,
            &#39;nickname&#39; => &#39;Lily&#39;,
            &#39;email&#39; => &#39;Lily@ezhi.net&#39;,
            &#39;qq&#39; => NULL,
            &#39;gold&#39; => 1541,
            &#39;powerplay&#39;=> array(&#39;2xp&#39;=>2,&#39;gem&#39;=>112,&#39;bingo&#39;=>4,&#39;keys&#39;=>7,&#39;chest&#39;=>8),
            &#39;gems&#39; => array(&#39;red&#39;=>13,&#39;green&#39;=>3,&#39;blue&#39;=>9,&#39;yellow&#39;=>7),
            &#39;ctime&#39; => 1376523234,
            &#39;lastLogin&#39;=> 1377123144,
            &#39;level&#39; => 10,
            &#39;exp&#39; => 1758,
        ),
    );
    
    $uidArr = array(10001,10002,10003);
    if (in_array($uid, $uidArr, true)) {
        $output = array(&#39;data&#39; => NULL, &#39;info&#39;=>&#39;The user does not exist!&#39;, &#39;code&#39; => -402);
        exit(json_encode($output));
    }
    //查询数据库
    $userInfo = $mysql[$uid];
    
    //输出数据
    $output = array(
        &#39;data&#39; => array(
            &#39;userInfo&#39; => $userInfo,
            &#39;isLogin&#39; => true,//是否首次登陆
            &#39;unread&#39; => 4,//未读消息数量
            &#39;untask&#39; => 3,//未完成任务
        ), 
        &#39;info&#39; => &#39;Here is the message which, commonly used in popup window&#39;, //消息提示,客户端常会用此作为给弹窗信息。
        &#39;code&#39; => 200, //成功与失败的代码,一般都是正数或者负数
    );
    exit(json_encode($output));
} elseif ($a == &#39;get_games_result&#39;) {
    //...
    die(&#39;您正在调 get_games_result 接口!&#39;);
} elseif ($a == &#39;upload_avatars&#39;) {
    //....
    die(&#39;您正在调 upload_avatars 接口!&#39;);
}

Copy code

Click test (for the client, this address is also called directly):

http://www.ezhi.net/api/test/index.php
http://www.ezhi.net/api/test/index.php?a=get_users
http://www.ezhi.net/api/test/index.php?a=get_users&uid=10001
http://www.ezhi.net/api/test/index.php?a=get_users&uid=10002
http://www.ezhi.net/api/test/index.php?a=get_users&uid=10003

三、实际项目中,我们在开发 API 应该注意的几个事项(仅供参考):
1、单文件实现多接口的形式有很多种,例如:if..elseif.. 或 switch 或 动态方法 (也就是TP的这种访问函数体的形式)
2、对于数据的输出最好用json,json具有相当强大的跨平台性,市场上各大主流编程语言都支持json解析,json正在逐步取代xml,成为网络数据的通用格式
3、接口安全,一定要增加接口验证。例如,客户端和服务端针对不同接口统一做好加密方式,服务端在对于每次接口需要都要进行验证。以保证防止接口被恶意刷新或黑客恶意调用,尤其是大型商业应用。
4、对于线上的 API 必须保证所有接口正常且关闭所有的错误信息 => error_reporting(0),在输出JSON 时,不能有任何其它输出,否则,客户端将解析数据失败,直接 Crash!
5、开发 API 和 WEB 有一定的区别,如果是 WEB 的话,可能代码出错了,不会导致特别严重的错误,也许只是导致数据写入和查询失败,也许导致 WEB 的某个部分错位或乱码。但如果是 API,直接 Crash!
6、做接口开发,不建议使用框架开发,原因概括起来有两点(其实我有点冒风险的,本人也是 TPer 一枚,毕竟这是TP的官网):
  1)客户端一般对服务端的响应速度有极高要求,因此,使用最原生态的 PHP 完成接口开发,是最高效的,假如用到了框架,还需要加载各种不需要多余的文件,就好比夏天穿了件冬天的衣服。试想,你在玩手机的时候,使用一个应用随便一个操作,等半天才有动静,你受的了吗?

  2)就是上面第4点提到的,框架对于WEB开发,是件很幸福的事,但对于 API 而言,你实在不敢想象它会给你出什么岔子!最后你将痛苦不堪~~因为很多框架都是为 WEB 诞生的(我也很期待有一天能看到专门为开发 API 而生的框架或者扩展)

  这个也有人纠结,接口效率与稳定性,还得看编码的人,有的人可能写的还不如框架跑的快,也有人觉得用框架没什么问题,这里只是建议,关键看自己的实际情况,同时建议代码上线前压测一下

  说到这,不得不说扯一下,腾讯微博淘宝等开放平台。其实那些开放平台,所谓的开放,就是给你提供一个这样的接口,你根据他们提供的技术文档,按他们制定的格式和要求,调它们提供的接口文件(一般都是返回JSON或者XML),你就可以获取到他们的相关信息,例如:QQ用户基本信息、淘宝店铺、商品消息等等。然后在根据这些消息,在你的应用里完成交互。

  其实,ajax 也是调用 API 的接口

The above is the detailed content of Detailed explanation of how to call interfaces and write interface code in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn