好的 PHP Rest Api 库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15327745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:03:20  来源:igfitidea点击:

Good PHP Rest Api library

phprestopen-source

提问by OptimusCrime

I am developing a cross-platform system and I need to make a rest API to tie them together. I have long experience in PHP and I want to use this for this service.

我正在开发一个跨平台系统,我需要制作一个休息 API 来将它们联系在一起。我在 PHP 方面有很长的经验,我想将它用于此服务。

I could develop a API 100% manually, but I am hoping there is some great libraries out there that could ease my development.

我可以 100% 手动开发 API,但我希望有一些很棒的库可以简化我的开发。

Does anyone have any experience with libraries like this? Anything you could recommend?

有没有人有这样的图书馆的经验?你有什么可以推荐的吗?

回答by OptimusCrime

I got the badge Popular questionfor this question, so I feel it's about time I elaborate how I did my REST-soluton.

我得到了Popular question这个问题的徽章,所以我觉得是时候详细说明我是如何做我的 REST 解决方案的了。

I did look at both Laravel, Sympfony2 and Codeigniter for this REST Api. They all had some elements I liked and some I disliked. My main concern was how to do the authentication because I had a rather complex algorithm where my users can log in with the apps' access_token or access_tokens served by Google or Facebook. I also perfer being in complete control of my framework and the frameworks mentioned above had some elements I felt unnecessary and hard to work around. Because of this I decided to make my own REST-solution. It is not as hard as one might expect, and it can be done in several ways. The way I did it requires some knowledge about OOP-programming.

对于这个 REST Api,我确实查看了 Laravel、Sympfony2 和 Codeigniter。他们都有一些我喜欢的元素和一些我不喜欢的元素。我主要关心的是如何进行身份验证,因为我有一个相当复杂的算法,我的用户可以使用 Google 或 Facebook 提供的应用程序的 access_token 或 access_tokens 登录。我也更喜欢完全控制我的框架,上面提到的框架有一些我觉得没有必要和难以解决的元素。因此,我决定制作自己的 REST 解决方案。它并不像人们想象的那么难,并且可以通过多种方式完成。我这样做的方式需要一些关于 OOP 编程的知识。

Okey, so starting out a made a base-class called REST. This class takes care of all the stuff that is in common for every call. Like authentication, parsing the requested path to a method, checking access_tokenetc.

好的,所以开始创建一个名为 REST 的基类。这个类负责处理每次调用的所有共同点。像身份验证,解析请求的方法路径,检查access_token等。

One of the central things in this class is the requested path and how this is translated into a method. I did this inspired by Laravel. I have a array with key=> valuewhere the key is the url it should match and the value is the actual method to call. I also included the way Lavavel parses variables in the URL like so:

此类中的核心内容之一是请求的路径以及如何将其转换为方法。我在 Laravel 的启发下做了这个。我有一个带有key=>的数组,value其中键是它应该匹配的 url,值是要调用的实际方法。我还包括 Lavavel 解析 URL 中变量的方式,如下所示:

'/user/(:id)' => 'user_id',

This would match any /user/[number]. It also checks what type of request this is, so if this is a simple get-method it would try to call get_user_id. Anything parsed with (:id)would be used as an argument when calling that method (so it is actually calling get_user_id($id)).

这将匹配任何 /user/[number]。它还检查这是什么类型的请求,因此如果这是一个简单的 get 方法,它会尝试调用get_user_id. (:id)在调用该方法时,任何解析的内容都将用作参数(因此它实际上是在调用get_user_id($id))。

After authentication the actual method-call gets evaluated. I did not want all the methods (like get_user_id) in the REST-class itself, so I broke these up in different controllers that extends the REST-class. This is done by looking at the url being requested. If it is /user/(:id)the script will check if there is a controller named userController.php. If it exists, check if the method we are going to call exists. If it does, check if the number of arguments matches what we have. If everything is good, execute the method, if not return an error message. Structure and error-messages are very important when making a API like this.

认证后,实际的方法调用被评估。我不想要get_user_idREST 类本身中的所有方法(如),所以我将它们分解到扩展 REST 类的不同控制器中。这是通过查看请求的 url 来完成的。如果是/user/(:id),脚本将检查是否有名为userController.php. 如果存在,检查我们要调用的方法是否存在。如果是,请检查参数的数量是否与我们拥有的数量相匹配。如果一切正常,则执行该方法,否则返回错误消息。在制作这样的 API 时,结构和错误消息非常重要。

In the different controllers I call the constructor for the REST-class to get the authentication, parsing of the url etc resolved. The tricky part here is that I did not want to do:

在不同的控制器中,我调用 REST 类的构造函数来获取身份验证、解析 url 等。这里棘手的部分是我不想做:

$controller = new MyController();
$controller->printResponse();

In the bottom of every controller. So I made a little hack and a script called run.phpthat does this dynamically for every controller-class. Before I include the run.phpI save the path for the controller by simply doing $path = explode('/',__FILE__);. This is used in the run-script. The run-script looks like this:

在每个控制器的底部。所以我做了一个小技巧和一个名为的脚本run.php,它为每个控制器类动态地执行此操作。在我包含之前,我run.php只需执行$path = explode('/',__FILE__);. 这在运行脚本中使用。运行脚本如下所示:

// Splitting the file-name, removing the extension
$name = explode('.',$path[count($path)-1]);

// Uppercasing the first letter to be nice and OOP-ish
$classToCall = ucfirst($name[0]);

// Creating a new instance
$controller = new $classToCall();

// Logging
$controller->doLog();

// Printing the final response
$controller->printResponse();

I found this to be a perfect solution for how I wanted to build my API. I can easily add new methods by supplying it in the array that parses urls to methods, and I can add new methods in the nicely broken apart controllers for maximum cleanness.

我发现这是我想要构建 API 的完美解决方案。我可以通过在解析 url 到方法的数组中提供它来轻松添加新方法,并且我可以在很好地分开的控制器中添加新方法以获得最大的清洁度。

Some people might think this is too much work, but it actually took me only a few hours to get it up and running. I'd also call this highly dynamic as I can just add new controllers and the system will recognize them if they are valid url-patterns.

有些人可能认为这工作量太大,但实际上我只用了几个小时就可以启动并运行它。我也称之为高度动态,因为我可以添加新的控制器,如果它们是有效的 url-patterns,系统就会识别它们。



A few friendly advices.

一些友好的建议。

If you decide to go with something resembling this solution, these can be some good tips. In each controller, do something like this:

如果您决定采用类似于此解决方案的方法,这些可能是一些不错的提示。在每个控制器中,执行如下操作:

public function __construct() {
    // Loading the class-name, setting it in the REST-class, so we can check if it holds the method being called
    $this->className = get_class($this);

    // Calling RESTs constructor
    parent::__construct();
}

We will need to store what class we are currently working from. This would be UserControlleror something like that.

我们需要存储我们当前正在使用的类。这将是UserController或类似的东西。

In the REST-class I can then use this variable to check if the actual method getting called does exist in this controller. I've done that this way:

在 REST 类中,我可以使用这个变量来检查实际调用的方法是否存在于这个控制器中。我是这样做的:

// Checking if the method exists
if (method_exists($this->className,$method_name)) {
    // Check to see if we have the required number of arguments represented
    $ReflectionClass = new ReflectionClass($this->className);

    if ($ReflectionClass->getMethod($method_name)->getNumberOfParameters() == count($this->methodUrl['args'])) {
        $this->response['response'] = call_user_func_array(array($this, $method_name), $this->methodUrl['args']);

I hope that can get you all going.

我希望这能让你们一切顺利。

Happy codin'

快乐编码

回答by Gaz_Edge

I had the same question three months ago. I spent many hours researching the best PHP frameworks to use. In the end I settled on Laravel.

三个月前我也有同样的问题。我花了很多时间研究最好的 PHP 框架。最后我选择了Laravel

Right out of the box it comes with RESTful routes and controllers, and easy to use authentication. I had a simple REST API up and running in about a day

它开箱即用,带有 RESTful 路由和控制器,以及易于使用的身份验证。我在大约一天内启动并运行了一个简单的 REST API

http://laravel.com/docs/routing#the-basics

http://laravel.com/docs/routing#the-basics

http://laravel.com/docs/controllers#restful-controllers

http://laravel.com/docs/controllers#restful-controllers

It also comes with a great ORM which makes setting up resources super easy

它还带有一个很棒的 ORM,这使得设置资源变得非常容易

http://laravel.com/docs/database/eloquent

http://laravel.com/docs/database/eloquent

I am using version 3.2 and it works like a charm and is stable. Version 4 is still in beta, but does have a lot more REST orientated features (i think one is that it makes it easier to create resources from within your controllers)

我使用的是 3.2 版,它的工作原理很吸引人,而且很稳定。版本 4 仍处于测试阶段,但确实有更多面向 REST 的功能(我认为其中之一是它可以更轻松地从控制器中创建资源)

Great tutorial here http://net.tutsplus.com/tutorials/php/laravel-4-a-start-at-a-restful-api/

很棒的教程http://net.tutsplus.com/tutorials/php/laravel-4-a-start-at-a-restful-api/