在没有框架的情况下路由 REST 请求? [英] Routing REST requests without framework?

查看:34
本文介绍了在没有框架的情况下路由 REST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读这篇文章来学习如何构建一个rest API:

I have been reading the article to learn how to build a rest API:

http://www.gen-x-design.com/archives/create-a-rest-api-with-php/

有一次它说假设您已将请求路由到正确的用户控制器"

At one point it says "Assuming you’ve routed your request to the correct controller for users"

没有框架我怎么能做到这一点?

How can I do this without a framework?

我正在编写一个 REST API,我可以从不同的应用程序中与之交互.我准备了上面的教程,它主要是有道理的,但我不完全理解将我的请求路由到用户的正确控制器意味着什么.

I am writing a REST API that I can interact with from a different application. I ready the tutorial above, and it makes sense mostly, but I don't exactly understand what it means to route my request to the correct controller for users.

推荐答案

假设您使用的是 Apache,您可以使用 mod_rewrite 和一些 PHP 的组合轻松完成此操作基于逻辑.例如,在您的 .htaccess 或 vhost 定义中,您可以通过单个处理程序路由所有请求,可能是 index.php:

Assuming you are using Apache, you can accomplish this easily using a combination of mod_rewrite and some PHP-based logic. For example, in your .htaccess or vhost definition, you could route all requests through a single handler, possibly index.php:

# Don't rewrite requests for e.g. assets
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*+)$ index.php?q=$1 [L]

...然后在您的 index.php 文件中执行以下操作:

...then in your index.php file do something like:

$target = $_REQUEST['q'];
/* parse the request and include the appropriate controller PHP */

例如,对 /products/1234 的请求可能会导致包含一个 controllers/products.php 处理程序.然后该处理程序可以对产品 1234 采取行动.因为您使用的是 REST,所以您不需要关心具有查询字符串参数的原始请求.

For example, a request for /products/1234 might result in a controllers/products.php handler being included. That handler could then act on product 1234. Because you're using REST, you shouldn't need to be concerned with the original request having a query string parameter.

有多种方法可以完成听起来像是您想要做的事情,这只是其中之一.最终你选择什么取决于你的具体要求.上面的模式很常见,但是很多框架都在使用它或类似的东西.

There are multiple ways to accomplish what it sounds like you're trying to do, this is just one of them. Ultimately what you go with will depend on what your specific requirements dictate. The above pattern is fairly common however, many frameworks use it or something like it.

这篇关于在没有框架的情况下路由 REST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆