Table of Contents
Hello Slim World
Home php教程 php手册 搭配修身写一个RESTful Web服务

搭配修身写一个RESTful Web服务

Jun 13, 2016 am 10:51 AM
i restful web world Write create delete app match Serve of want default

要创建一个Hello World应用程序,删除默认的index.php文件在应用程序目录,并创建一个新的index.php文件用下面的代码:

01 02 require "Slim/Slim.php";
03
04 // create new Slim instance
05 $app = new Slim();
06
07 // add new Route
08 $app->get("/", function () {
09     echo "

Hello Slim World

";
10 });
11
12 // run the Slim app
13 $app->run();

现在是准备你的第一个修身应用。如果你通过浏览器访问index.php文件,你应该看到一个大的“Hello斯利姆世界。”
在您的应用程序中使用的Slim,你需要包括Slim.php和斯利姆,会自动加载,它需要的所有其他文件。然后,您可以创建一个或多个实例修身对象,并添加您的路线。
苗条的构造函数接受一个应用程序的配置值的数组。模式,TEMPLATES.PATH和观看一些重要的,我们经常使用的配置。使用模式设置要像开发或生产,使用的应用环境。TEMPLATES.PATH设置使用模板文件的位置。斯利姆使用Slim_View的,默认情况下,呈现的观点,但您可以编写自定义的视图处理程序,并通过使用附加苗条价值。下面的示例演示如何创建一个新的自定义修身实例TEMPLATES.PATH和设置环境的发展模式。

1 2 $app = new Slim(array(
3     "MODE" => "development",
4     "TEMPLATES.PATH' => "./templates"
5 ));

创建一个应用程序使用斯利姆是创建路线的最重要组成部分。路由帮助一个URI映射到一个特定的请求方法的回调函数。斯利姆提供一个简单而直观的方式,以相同的URI映射的方法不同的要求。它将调用的回调函数,符合当前的URI和请求方法,或产生一个404错误,如果它是无法比拟的。加入航线后,你需要调用的run()方法修身实例运行的应用程序。
写一个图书馆服务
在更深入的运动,让我们创建一个简单的图书馆管理Web服务应用程序使用超薄。在此应用中,我们就可以列出,添加,删除,更新本书详细介绍了使用Web服务调用。
下表列出了将支持Web服务的端点:
对于数据库的交互中,我将使用NotORM书面JakubVrána作为替代ORM,它提供了一个简单而直观的API来与数据库中的数据,PHP库。NotORM使用PHP的PDO扩展来访问数据库,所以PDO的实例传递给NotORM的构造。

1 2 require "NotORM.php";
3
4 $pdo = new PDO($dsn, $username, $password);
5 $db = new NotORM($pdo);

上市书籍
第一个端点列出库中所有的书籍,让我们的使用超薄创建端点并返回JSON格式的编码数据。

01 02 ...
03 $app = new Slim(
04     "MODE" => "developement",
05     "TEMPLATES.PATH' => "./templates"
06 );
07
08 $app->get("/books", function () use ($app, $db) {
09     $books = array();
10     foreach ($db->books() as $book) {
11         $books[]  = array(
12             "id" => $book["id"],
13             "title" => $book["title"],
14             "author" => $book["author"],
15             "summary" => $book["summary"]
16         );
17     }
18     $app->response()->header("Content-Type", "application/json");
19     echo json_encode($books);
20 });

()是修身的方法,路线到指定的URI上的GET请求。它的第一个参数是URI和最后一个参数是一个回调函数。使用关键字,使我们能够从匿名函数的范围内访问外部变量。
在函数中,我们创建,遍历数据库返回的每个记录(书的数组$ DB->图书()返回一个遍历参考的书籍表)。发送响应的Content-Type头为“应用程序/ json”我们发出的编码书数据阵列。
现在让我们写一本书与一个给定的ID的详细信息端点:

01 02 ...
03 $app->get("/book/:id", function ($id) use ($app, $db) {
04     $app->response()->header("Content-Type", "application/json");
05     $book = $db->books()->where("id", $id);
06     if ($data = $book->fetch()) {
07         echo json_encode(array(
08             "id" => $data["id"],
09             "title" => $data["title"],
10             "author" => $data["author"],
11             "summary" => $data["summary"]
12             ));
13     }
14     else{
15         echo json_encode(array(
16             "status" => false,
17             "message" => "Book ID $id does not exist"
18             ));
19     }
20 });

在这里,我们添加了一个参数,本书的ID传递路线。在执行这条路线,斯利姆将调用的回调函数作为参数的参数值。
请注意该参数是强制性的。您可以通过它放在像括号内可选:/书(/ ID),如果你正在做一个参数可选,不过,你将不能够指定的回调函数的参数。在这种情况下,你可以使用func_get_args()以任何参数传递给回调函数来获得。
添加和编辑书籍
现在,让我们的地址端点添加和更新图书信息负责。我们将使用后()方法来添加新的数据,并把()来更新现有的数据。

01 02 ...
03 $app->post("/book", function () use($app, $db) {
04     $app->response()->header("Content-Type", "application/json");
05     $book = $app->request()->post();
06     $result = $db->books->insert($book);
07     echo json_encode(array("id" => $result["id"]));
08 });
09
10 $app->put("/book/:id", function ($id) use ($app, $db) {
11     $app->response()->header("Content-Type", "application/json");
12     $book = $db->books()->where("id", $id);
13     if ($book->fetch()) {
14         $post = $app->request()->put();
15         $result = $book->update($post);
16         echo json_encode(array(
17             "status" => (bool)$result,
18             "message" => "Book updated successfully"
19             ));
20     }
21     else{
22         echo json_encode(array(
23             "status" => false,
24             "message" => "Book id $id does not exist"
25         ));
26     }
27 });

为应用程序请求()返回当前请求对象(Slim_Http_Request的使用POST)或把数据。你可以得到的POST值员额()这个对象的方法,使用()方法的沽值。在这里,我们假设两个POST和PUT数据信息表的列名作为键的键/值对。在现实世界的应用程序,你将需要添加一些验证和错误处理,但我已经为简单起见,这里省略。
如果你打算从浏览器访问您的修身应用,你将不能够很容易地使PUT请求,浏览器通常不公开通过HTML的方法。为了克服这个问题,修身有一个规定,它可以让你覆盖POST请求将放置在一个隐藏字段的形式。字段的名称应该是“_method”设置为“PUT”的价值。

1



3  Title:

4  Author:

5  Summary:



8

删除书籍
我们需要的下一个显而易见的事情,现在我们有添加,编辑和书单,在我们的Web服务端点,端点删除书籍。它应该接受书要删除的ID,并从数据库中删除相应的记录。
01 02 ...
03 $app->delete("/book/:id", function ($id) use($app, $db) {
04     $app->response()->header("Content-Type", "application/json");
05     $book = $db->books()->where("id", $id);
06     if ($book->fetch()) {
07         $result = $book->delete();
08         echo json_encode(array(
09             "status" => true,
10             "message" => "Book deleted successfully"
11         ));
12     }
13     else{
14         echo json_encode(array(
15             "status" => false,
16             "message" => "Book id $id does not exist"
17         ));
18     }
19 });
一切都非常简单。首先,我们取给定的ID从数据库中相应的行,就像我们已经做了的时候本书详细介绍了。行对象上调用的delete()方法从数据库中删除该记录。www.2cto.com
我们已经建立了相关的所有书籍进行必要的终点。在某些情况下,您可能希望有一个单一的路线,将响应多个请求方法。它可以实现使用的地图()的斯利姆方法。

总结

在这篇文章中,我们已经讨论了创建一个RESTful Web服务,使用超薄框架。现在,你应该能够创建自己的Web服务应用程序,没有太多的麻烦。
当然,也有很多事情比这里讨论的简单的事情可以做。你可以有很多参数,数据验证等航线。因此,深入和喜欢苗条和NoORM来帮助你实现你的目标使用的工具。


作者:ssoftware
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete Xiaohongshu notes How to delete Xiaohongshu notes Mar 21, 2024 pm 08:12 PM

How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

How to connect Apple Vision Pro to PC How to connect Apple Vision Pro to PC Apr 08, 2024 pm 09:01 PM

The Apple Vision Pro headset is not natively compatible with computers, so you must configure it to connect to a Windows computer. Since its launch, Apple Vision Pro has been a hit, and with its cutting-edge features and extensive operability, it's easy to see why. Although you can make some adjustments to it to suit your PC, and its functionality depends heavily on AppleOS, so its functionality will be limited. How do I connect AppleVisionPro to my computer? 1. Verify system requirements You need the latest version of Windows 11 (Custom PCs and Surface devices are not supported) Support 64-bit 2GHZ or faster fast processor High-performance GPU, most

Is it true that you can be blocked and deleted on WeChat and permanently unable to be added? Is it true that you can be blocked and deleted on WeChat and permanently unable to be added? Apr 08, 2024 am 11:41 AM

1. First of all, it is false to block and delete someone permanently and not add them permanently. If you want to add the other party after you have blocked them and deleted them, you only need the other party's consent. 2. If a user blocks someone, the other party will not be able to send messages to the user, view the user's circle of friends, or make calls with the user. 3. Blocking does not mean deleting the other party from the user's WeChat contact list. 4. If the user deletes the other party from the user's WeChat contact list after blocking them, there is no way to recover after deletion. 5. If the user wants to add the other party as a friend again, the other party needs to agree and add the user again.

Shazam app not working in iPhone: Fix Shazam app not working in iPhone: Fix Jun 08, 2024 pm 12:36 PM

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

How to delete Xiaohongshu releases? How to recover after deletion? How to delete Xiaohongshu releases? How to recover after deletion? Mar 21, 2024 pm 05:10 PM

As a popular social e-commerce platform, Xiaohongshu has attracted a large number of users to share their daily life and shopping experiences. Sometimes we may inadvertently publish some inappropriate content, which needs to be deleted in time to better maintain our personal image or comply with platform regulations. 1. How to delete Xiaohongshu releases? 1. Log in to your Xiaohongshu account and enter your personal homepage. 2. At the bottom of the personal homepage, find the "My Creations" option and click to enter. 3. On the "My Creations" page, you can see all published content, including notes, videos, etc. 4. Find the content that needs to be deleted and click the "..." button on the right. 5. In the pop-up menu, select the "Delete" option. 6. After confirming the deletion, the content will disappear from your personal homepage and public page.

How to completely delete TikTok chat history How to completely delete TikTok chat history May 07, 2024 am 11:14 AM

1. Open the Douyin app, click [Message] at the bottom of the interface, and click the chat conversation entry that needs to be deleted. 2. Long press any chat record, click [Multiple Select], and check the chat records you want to delete. 3. Click the [Delete] button in the lower right corner and select [Confirm deletion] in the pop-up window to permanently delete these records.

How can I retrieve someone else's deleted comment on Xiaohongshu? Will it be displayed if someone else's comment is deleted? How can I retrieve someone else's deleted comment on Xiaohongshu? Will it be displayed if someone else's comment is deleted? Mar 21, 2024 pm 10:46 PM

Xiaohongshu is a popular social e-commerce platform, and interactive comments between users are an indispensable method of communication on the platform. Occasionally, we may find that our comments have been deleted by others, which can be confusing. 1. How can I retrieve someone else’s deleted comments on Xiaohongshu? When you find that your comments have been deleted, you can first try to directly search for relevant posts or products on the platform to see if you can still find the comment. If the comment is still displayed after being deleted, it may have been deleted by the original post owner. At this time, you can try to contact the original post owner to ask the reason for deleting the comment and request to restore the comment. If a comment has been completely deleted and cannot be found on the original post, the chances of it being reinstated on the platform are relatively slim. You can try other ways

How to send files to others on TikTok? How to delete files sent to others? How to send files to others on TikTok? How to delete files sent to others? Mar 22, 2024 am 08:30 AM

On Douyin, users can not only share their life details and talents, but also interact with other users. In this process, sometimes we need to send files to other users, such as pictures, videos, etc. So, how to send files to others on Douyin? 1. How to send files to others on Douyin? 1. Open Douyin and enter the chat interface where you want to send files. 2. Click the "+" sign in the chat interface and select "File". 3. In the file options, you can choose to send pictures, videos, audio and other files. After selecting the file you want to send, click "Send". 4. Wait for the other party to accept your file. Once the other party accepts it, the file will be transferred successfully. 2. How to delete files sent to others on Douyin? 1. Open Douyin and enter the text you sent.

See all articles