slim restful

tech2023-10-21  94

slim restful

Through a series of articles here at SitePoint you’ve learned about what is REST and how it works. In this article, I’d like to show you how to create a RESTful web service using Slim, a PHP micro-framework inspired by Sinatra, a Ruby framework. It’s well-suited for creating simple RESTful web services and comes with some minimal components like Router, Request, Response, and View. It’s very simple, and is easy to understand and use.

通过 SitePoint上的一系列文章 ,您了解了什么是REST及其工作原理。 在本文中,我想向您展示如何使用Slim创建RESTful Web服务,Slim是受Ruby框架Sinatra启发PHP微框架。 它非常适合创建简单的RESTful Web服务,并带有一些最小的组件,如Router,Request,Response和View。 它非常简单,并且易于理解和使用。

向Slim World打个招呼 (Say Hello to Slim World)

To get started with Slim, you’ll need to download it first. It requires PHP 5.2+ and lets you write applications in both procedural style or in 5.3+ style, e.g. using anonymous functions. In this article I’ll be using 5.3 style coding for all examples, assuming you are already familiar with it.

要开始使用Slim,您需要先下载它。 它需要PHP 5.2+,并允许您以过程样式或5.3+样式(例如,使用匿名函数)编写应用程序。 在本文中,假设您已经熟悉5.3,则将对所有示例使用5.3样式编码。

To create a Hello World application, remove the default index.php file in the application directory and create a new index.php file with the following code:

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

<?php require "Slim/Slim.php"; // create new Slim instance $app = new Slim(); // add new Route $app->get("/", function () { echo "<h1>Hello Slim World</h1>"; }); // run the Slim app $app->run();

Your first Slim application is ready now. If you access index.php through your browser, you should see a big “Hello Slim World.”

您的第一个Slim应用程序现已准备就绪。 如果通过浏览器访问index.php ,应该会看到一个很大的“ Hello Slim World”。

To use Slim in your applications, you need to include Slim.php and Slim will autoload all of the other files that it needs. Then you can create one or more instances of the Slim object and add your routes.

要在您的应用程序中使用Slim,您需要包括Slim.php ,Slim将自动加载它需要的所有其他文件。 然后,您可以创建Slim对象的一个​​或多个实例并添加您的路线。

The Slim constructor accepts an array of application configuration values. MODE, TEMPLATES.PATH and VIEW are some important configurations that we often use. Use MODE to set the application environment to be used, like development or production. TEMPLATES.PATH sets the location to use for template files. Slim uses Slim_View to render the view by default, but you can write custom view handlers and attach them to Slim by using the VIEW value. The following example shows how to to create a new Slim instance with a custom TEMPLATES.PATH and sets the environment to development mode.

Slim构造函数接受应用程序配置值的数组。 MODE , TEMPLATES.PATH和VIEW是我们经常使用的一些重要配置。 使用MODE设置要使用的应用程序环境,例如开发或生产。 TEMPLATES.PATH设置用于模板文件的位置。 Slim默认使用Slim_View呈现视图,但是您可以编写自定义视图处理程序,并使用VIEW值将它们附加到Slim。 以下示例显示了如何使用自定义TEMPLATES.PATH创建新的Slim实例并将环境设置为开发模式。

<?php $app = new Slim(array( "MODE" => "development", "TEMPLATES.PATH' => "./templates" ));

The most important part of creating an application using Slim is creating routes. A route helps to map a URI to a callback function for specific request methods. Slim provides a simple and intuitive way to map the same URIs with different requests methods. It will invoke the first callback function that matches the current URI and request method, or produce a 404 error if it is unable to match. After adding the routes, you need to call the run() method on the Slim instance to run the application.

使用Slim创建应用程序最重要的部分是创建路由。 路由有助于将URI映射到特定请求方法的回调函数。 Slim提供了一种简单直观的方法,可以将不同的请求方法映射到相同的URI。 它将调用与当前URI和请求方法匹配的第一个回调函数,如果无法匹配,则将产生404错误。 添加路由后,您需要在Slim实例上调用run()方法以运行应用程序。

编写图书馆服务 (Writing a Library Service)

As a more in-depth exercise, let’s create a simple Library management web service application using Slim. In this application we’ll be able to list, add, delete, and update book details using web service calls.

作为更深入的练习,让我们使用Slim创建一个简单的Library Management Web服务应用程序。 在此应用程序中,我们将能够使用Web服务调用来列出,添加,删除和更新图书详细信息。

The following table lists the endpoints that will be supported by the web service:

下表列出了Web服务将支持的端点:

For database interactions, I’ll use NotORM, a PHP library written by Jakub Vrána as an alternative to ORM which provides a simple and intuitive API to work with data from your database. NotORM uses PHP’s PDO extension to access the database, and so a PDO instance is passed to NotORM‘s constructor.

对于数据库的交互,我将使用NotORM ,书面一个PHP库的Jakub弗拉纳作为替代ORM提供了一个简单而直观的API来工作,从您的数据库中的数据。 NotORM使用PHP的PDO扩展名来访问数据库,因此PDO实例将传递给NotORM的构造函数。

<?php require "NotORM.php"; $pdo = new PDO($dsn, $username, $password); $db = new NotORM($pdo);

上市书 (Listing Books)

The first endpoint lists all of the books in the library, so let’s use Slim to create the endpoint and return the data encoded in JSON format.

第一个端点列出了库中的所有书籍,因此让我们使用Slim创建端点并返回以JSON格式编码的数据。

<?php ... $app = new Slim( "MODE" => "developement", "TEMPLATES.PATH' => "./templates" ); $app->get("/books", function () use ($app, $db) { $books = array(); foreach ($db->books() as $book) { $books[] = array( "id" => $book["id"], "title" => $book["title"], "author" => $book["author"], "summary" => $book["summary"] ); } $app->response()->header("Content-Type", "application/json"); echo json_encode($books); });

get() is a Slim method that routes to a GET request on the given URI. It’s first argument is the URI and last argument is a callback function. The use keyword enables us to access the outer variables from inside the scope of the anonymous function.

get()是一个Slim方法,它路由到给定URI上的GET请求。 它的第一个参数是URI,最后一个参数是回调函数。 use关键字使我们能够从匿名函数范围内访问外部变量。

Within the function, we create an array of books by looping through each record returned by the database ($db->books() returns a traversable reference to the books table). The response’s Content-Type header is sent as “application/json” and we emit the encoded array of book data.

在该函数中,我们通过遍历数据库返回的每个记录来创建书籍数组( $db->books()返回对books表的可遍历引用)。 响应的Content-Type标头作为“ application / json”发送,我们发出编码后的书本数据数组。

Now let’s write the endpoint for getting the details of a book with a given ID:

现在,让我们编写端点以获取具有给定ID的书籍的详细信息:

<?php ... $app->get("/book/:id", function ($id) use ($app, $db) { $app->response()->header("Content-Type", "application/json"); $book = $db->books()->where("id", $id); if ($data = $book->fetch()) { echo json_encode(array( "id" => $data["id"], "title" => $data["title"], "author" => $data["author"], "summary" => $data["summary"] )); } else{ echo json_encode(array( "status" => false, "message" => "Book ID $id does not exist" )); } });

Here we have added a parameter to Route for passing the ID of the book. While executing this route, Slim will invoke the callback function with the value for the parameter as an argument.

在这里,我们为Route添加了一个参数,用于传递书的ID。 在执行此路由时,Slim将使用参数的值作为参数来调用回调函数。

Note that the parameter is mandatory. You can make it optional by placing it inside a parenthesis like: /book(/:id) If you are making a parameter optional, though, you won’t be able to specify parameters for the callback function. In that case you can make use of the func_get_args() function to get any arguments passed to the callback.

请注意,该参数是必需的。 您可以通过将其放在括号内来使其可选,例如: /book(/:id)但是,如果将参数设置为可选,则将无法为回调函数指定参数。 在这种情况下,您可以使用func_get_args()函数来获取传递给回调的所有参数。

添加和编辑书籍 (Adding and Editing Books)

Now let’s address the endpoints responsible for adding and updating book information. We’ll use the post() method to add new data, and put() to update existing data.

现在,让我们解决负责添加和更新图书信息的端点。 我们将使用post()方法添加新数据,并使用put()更新现有数据。

<?php ... $app->post("/book", function () use($app, $db) { $app->response()->header("Content-Type", "application/json"); $book = $app->request()->post(); $result = $db->books->insert($book); echo json_encode(array("id" => $result["id"])); }); $app->put("/book/:id", function ($id) use ($app, $db) { $app->response()->header("Content-Type", "application/json"); $book = $db->books()->where("id", $id); if ($book->fetch()) { $post = $app->request()->put(); $result = $book->update($post); echo json_encode(array( "status" => (bool)$result, "message" => "Book updated successfully" )); } else{ echo json_encode(array( "status" => false, "message" => "Book id $id does not exist" )); } });

$app->request() returns the current request object (Slim_Http_Request) with POST or PUT data. You can get the POST values using the post() method of this object, and the PUT values using the put() method. Here we’re assuming both POST and PUT data is key/value pairs of information with table column names as keys. In a real-world application, you will need to add some validation and error handling, but I’ve omitted it here for the sake of simplicity.

$app->request()返回带有POST或PUT数据的当前请求对象( Slim_Http_Request )。 您可以使用此对象的post()方法获取POST值,并使用put()方法获取PUT值。 在这里,我们假设POST和PUT数据都是键/值信息对,且表列名称为键。 在实际应用程序中,您将需要添加一些验证和错误处理,但是为了简单起见,在此省略了它。

If you plan on accessing your Slim application from a browser, you won’t be able to easily make PUT requests, as browsers don’t normally expose the method via HTML. To overcome this, Slim have a provision that let’s you override POST requests to PUT by placing a hidden field in your form. The field’s name should be “_METHOD” and the value set to “PUT”.

如果您打算从浏览器访问Slim应用程序,则将无法轻松发出PUT请求,因为浏览器通常不会通过HTML公开该方法。 为了克服这个问题,Slim提供了一项规定,让您可以通过在表单中​​放置一个隐藏字段来覆盖对PUT的POST请求。 该字段的名称应为“ _METHOD”,其值应设置为“ PUT”。

<form action="#" method="post"> <input type="hidden" name="_METHOD" value="PUT"> Title: <input type="text" name="title"><br> Author: <input type="text" name="author"><br> Summary: <textarea name="summary"></textarea> <br> <input type="submit" value="Submit"> </form>

删除书籍 (Deleting Books)

Now that we have the endpoints to add, edit, and list books in our web service, the next obvious thing we need to is the endpoint to delete books. It should accept the ID of book to be deleted and remove the corresponding record from the database.

现在我们有了在Web服务中添加,编辑和列出书籍的端点,接下来我们需要做的显而易见的事情是删除书籍的端点。 它应该接受要删除的书籍的ID,并从数据库中删除相应的记录。

<?php ... $app->delete("/book/:id", function ($id) use($app, $db) { $app->response()->header("Content-Type", "application/json"); $book = $db->books()->where("id", $id); if ($book->fetch()) { $result = $book->delete(); echo json_encode(array( "status" => true, "message" => "Book deleted successfully" )); } else{ echo json_encode(array( "status" => false, "message" => "Book id $id does not exist" )); } });

Everything is pretty straightforward here. First we fetch the row corresponding to the given ID from the database, just like we have done when getting book details earlier. Calling the delete() method on the row object will delete that record from database.

这里的一切都非常简单。 首先,我们从数据库中获取与给定ID对应的行,就像我们早先获取书籍详细信息时所做的那样。 在行对象上调用delete()方法将从数据库中删除该记录。

We have created all the necessary endpoints related to books. In some cases you may want to have a single route that will respond to more than one request methods. It can be implemented using the map() method of Slim, which is explained here.

我们已经创建了与书籍相关的所有必要端点。 在某些情况下,您可能希望使用一条路由来响应多个请求方法。 可以使用Slim的map()方法来实现,在此进行说明 。

摘要 (Summary)

In this article we’ve discussed creating a RESTful web service using the Slim framework. Now you should be able to create your own web service applications without much trouble.

在本文中,我们讨论了使用Slim框架创建RESTful Web服务。 现在,您应该可以轻松创建自己的Web服务应用程序。

Of course, there are many more things you can do than the simple things discussed here. You can have routes with many parameters, data validation, and so on. So dig into it and use tools like Slim and NoORM to help you achieve your objectives.

当然,除了这里讨论的简单事情之外,您还可以做更多的事情。 您可以使用带有许多参数的路由,数据验证等。 因此,请深入研究它并使用Slim和NoORM之类的工具来帮助您实现目标。

You can download the source code of this article from GitHub.

您可以从GitHub下载本文的源代码 。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/writing-a-restful-web-service-with-slim/

slim restful

相关资源:slim4-api-skeleton:使用PHP和Slim 4开发RESTful API的有用框架-源码
最新回复(0)