search
HomeBackend DevelopmentPHP Tutorial浅谈使用 PHP 进行手机 APP 开发(API 接口开发)_php实例

一、先简单回答两个问题:

1、PHP 可以开发客户端?

答:可以,因为PHP是脚本语言,是负责完成 B/S架构 或 C/S架构 的S部分,即:主要用于服务端的开发。但是,PHP可不仅仅只能在互联网站上发展,一个PHP for Android(PFA)站点表示他们将可以发布编程模型、工具盒文档让PHP在Android上实现应用。该项目的主要赞助商是开源公司IronTec,PFA使用Scripting Layer for Android (SL4A),也就是Androd Scripting Environment(ASE)来实现这一点,您可以参看他们的网站来了解更多技术内幕。

如果有兴趣你可以参考一些相关的技术文档,比如:http://so.jb51.net/cse/search?q=php+for+android&s=10520733385329581432

2、为什么选择 PHP 作为开发服务端的首选?

答:跨平台(可以运行在UNIX、LINUX、WINDOWS、Mac OS下)、低消耗(PHP消耗相当少的系统资源)、运行效率高(相对而言)、MySQL的完美搭档,本身是免费开源的,......

二、如何使用 PHP 开发 API(Application Programming Interface,应用程序编程接口) 呢?

做过 API 的人应该了解,其实开发 API 比开发 WEB 更简洁,但可能逻辑更复杂,因为 API 其实就是数据输出,不用呈现页面,所以也就不存在 MVC(API 只有 M 和 C),

1、和 WEB 开发一样,首先需要一些相关的参数,这些参数,都会由客户端传过来,也许是 GET 也许是 POST,这个需要开发团队相互之间约定好,或者制定统一规范。

2、有了参数,根据应用需求,完成数据处理,例如:任务进度更新、APP内购、一局游戏结束数据提交等等

3、数据逻辑处理完之后,返回客户端所需要用到的相关数据,例如:任务状态、内购结果、玩家信息等等

数据怎么返给客户端?

直接输出的形式,如:JSON、XML、TEXT 等等。

4、客户端获取到你返回的数据后,在客户端本地和用户进行交互

临时写的一个简单 API 例子:

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

点击测试(对于客户端而言,也是直接调用这样的地址):

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 时,不能有任何其它输出,否则,客户端将会获取错误的数据信息,98%直接导致客户端 Crash!

5、开发 API 和 WEB 有一定的区别,如果是 WEB 的话,可能代码出错了,不会导致特别严重的错误,也许只是导致数据写入和查询失败,也许导致 WEB 的某个部分错位或乱码。但如果是 API,99%的情况都是客户端直接Crash、闪退!

6、做接口开发,不建议使用框架开发,原因概括起来有两点(其实我有点冒风险的,本人也是 TPer 一枚,毕竟这是TP的官网):

客户端一般对服务端的响应速度有极高要求,因此,使用最原生态的 PHP完成接口开发,是最高效的,假如用到了框架,还需要加载各种不需要多余的文件,就好比夏天穿了件冬天的衣服。试想,你在玩手机的时候,使用一个应用随便一个操作,等半天才有动静,你受的了吗?
就是上面第4点提到的,框架对于WEB开发,是件很幸福的事,但对于 API 而言,你实在不敢想象它会给你出什么岔子!最后你将痛苦不堪~~因为很多框架都是为 WEB 诞生的(我也很期待有一天能看到专门为开发 API 而生的框架或者扩展)
说到这,不得不说扯一下,风靡互联网的开放平台。其实那些开放平台,所谓的开放,就是给你提供一个这样的接口,你根据他们提供的技术文档,按他们制定的格式和要求,调它们提供的接口文件(一般都是返回JSON或者XML),你就可以获取到他们的相关信息,例如:QQ用户基本信息、淘宝店铺、商品消息等等。然后在根据这些消息,在你的应用里完成交互。

其实,ajax 也是调用 API 的一种体现形式,你觉得呢? 呵呵~~

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use