简体   繁体   English

处理多个PHP脚本作为后端REST服务的最佳方法?

[英]Best approach for handling multiple PHP scripts as a backend REST service?

I have a typical website setup where I'm using AJAX to communicate with PHP scripts which are then reading and writing data to a MySQL database. 我有一个典型的网站设置,其中使用AJAX与PHP脚本进行通信,然后这些PHP脚本将数据读取和写入MySQL数据库。 In my previous projects, the amount PHP scripts I needed to make were small since there weren't many variations in the data that I needed to read or write. 在我以前的项目中,我需要制作的PHP脚本数量很少,因为我需要读取或写入的数据没有太多变化。 This site is a bit different, and my normal approach of creating a different PHP script for each AJAX call has resulted in a large amount of PHP scripts. 这个站点有些不同,我为每个AJAX调用创建不同的PHP脚本的常规方法导致了大量的PHP脚本。

I decided to take a different approach and group similar queries in the same PHP script. 我决定采用不同的方法,并在同一PHP脚本中对相似的查询进行分组。 For example, if I have the following calls: 例如,如果我有以下电话:

getGroupById getGroupById
getAllGroups getAllGroups
createNewGroup createNewGroup

In my previous approach, I would have three separate php files, but now I have one that does all three of these. 在我以前的方法中,我将有三个单独的php文件,但是现在我有一个可以完成所有这三个文件。

The second approach I have taken is proving to be unmaintainable as the project is grows. 事实证明,随着项目的发展,我采取的第二种方法无法维持。 For example, if I want to have multiple GET calls in the same script, I'd have to now pass in another parameter to the script from the AJAX call so that the PHP script knows which query to perform. 例如,如果我想在同一个脚本中进行多个GET调用,则现在必须从AJAX调用中向脚本传递另一个参数,以便PHP脚本知道要执行的查询。

Which of these two approaches would be better? 这两种方法中哪一种更好? Are there any well known practices or design patterns for handling this? 是否有任何众所周知的实践或设计模式来处理?

If you really want to be RESTful, try to make your PHP file structure independent of the way you want your AJAX requests to be. 如果您确实想成为RESTful,请尝试使PHP文件结构独立于您希望AJAX请求的方式。

One common design pattern is to make a representation for each separate entity of data you have and then define the CRUD -operations on that representation. 一种常见的设计模式是为您拥有的每个数据实体创建一个表示,然后在该表示上定义CRUD操作。 The HTTP method header then serves as the identifier of which operation should be performed. 然后,HTTP方法标头用作应执行的操作的标识符。

For example, lets say you have the following "pieces" of data: 例如,假设您具有以下“部分”数据:

  • user : a member of your website 用户 :您网站的成员
  • group : a group of members :一组成员

If possible, use something like Apache's mod_rewrite in a .htaccess to create some nice looking URLs like this: 如果可能,请在.htaccess中使用类似Apache的mod_rewrite之类的东西来创建一些看起来不错的URL,如下所示:

Next, pass your parameters in a GET , PUT , DELETE or POST request using AJAX to one of these URLs. 接下来,使用AJAX将参数传递给GETPUTDELETEPOST请求中的其中一个URL。 Usually the AJAX library allows you define operations other than GET or POST . 通常,AJAX库允许您定义除GETPOST之外的其他操作。 For example to delete user named Bob with ID 415 in jQuery you could write something like: 例如,要删除jQuery中ID为415的名为Bob的用户,您可以编写以下内容:

$.ajax ({
  url: 'http://example.com/api/user'
  method: 'DELETE',
  data: { id: 415 }
  success: {
    // it works!
  }
});

Next thing is to catch the data with PHP. 下一步是使用PHP捕获数据。 I'd suggest creating a separate file for each "piece" of data but you can change this when your scripts are getting bigger. 我建议为每个“数据”段创建一个单独的文件,但是当脚本越来越大时,可以更改此文件。 It's just a matter of adjusting the rewrite rules of your HTTP server. 只需调整HTTP服务器的重写规则即可

api/user.php api / user.php

// determine what operation was requested
switch ($_SERVER['REQUEST_METHOD'])
{
  case 'POST':
    $data = $_POST;
    // ...
  case 'GET':
    $data = $_GET;
    // e.g. if an ID was provided, fetch one user, else fetch all of the users
    if (isset ($data ['id']))
      fetch_user ($id);
    else
      fetch_users ();
    break;
  case 'PUT':
    $data = parse_str (file_get_contents('php://input'), $put_vars); // see below
    // ...
  case 'DELETE':
    $data = parse_str (file_get_contents('php://input'), $put_vars); // see below
    // ...
  default:
   // 405 = Method Not Allowed
   http_response_code(405); // for PHP >= 5.4.0
   exit;
}

// a whole list of functions to add, retrieve, delete and manipulate users

function fetch_user ($id)
{
  $query = "SELECT * FROM users WHERE id = ...";
  // ...
}

function fetch_users ()
{
  // ...
}

Sources: 资料来源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM