This SitePoint series has explored REST principles. This article demonstrates building a RESTful web service using Slim, a PHP micro-framework inspired by Sinatra (Ruby). Slim's lightweight nature, with core components like routing, request/response handling, and minimal view support, makes it ideal for simple REST APIs.
Key Concepts:
- Slim is a PHP micro-framework perfect for straightforward RESTful services, supporting PHP 5.2 and both procedural and (5.3 ) functional programming styles.
- Routes map URIs to callback functions for specific HTTP methods. Slim efficiently handles multiple methods for the same URI.
- A library management application example showcases listing, adding, deleting, and updating book details via web service calls. NotORM, a lightweight PHP database library, handles database interaction.
- Endpoints use
post()
,put()
, anddelete()
methods for creating, updating, and deleting book records respectively.
Introducing Slim:
Begin by downloading Slim. This example uses the 5.3 style. Create index.php
:
<?php require "Slim/Slim.php"; $app = new Slim(); $app->get("/", function () { echo "<h1 id="Hello-Slim-World">Hello Slim World</h1>"; }); $app->run(); ?>
Accessing index.php
in your browser displays "Hello Slim World". Slim autoloads necessary files. The Slim constructor accepts configuration (e.g., MODE
, TEMPLATES.PATH
, VIEW
). MODE
sets the environment (development/production), and TEMPLATES.PATH
specifies the template directory. Custom view handlers can replace the default Slim_View
. Example:
<?php $app = new Slim(array( "MODE" => "development", "TEMPLATES.PATH" => "./templates" )); ?>
Route creation is crucial. Routes map URIs to callback functions based on HTTP methods. Slim prioritizes the first matching route; unmatched requests result in a 404 error. After defining routes, call run()
to start the application.
Building a Library Service:
Let's create a library management service. NotORM simplifies database interaction (requires a PDO instance).
<?php require "NotORM.php"; $pdo = new PDO($dsn, $username, $password); // Replace with your database credentials $db = new NotORM($pdo); ?>
Listing Books:
This endpoint lists all books in JSON format:
<?php // ... (previous code) ... $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); }); // ... (rest of the code) ...
get()
handles GET requests. use
allows accessing external variables within the anonymous function. The response header is set to application/json
, and the book data is encoded as JSON.
Getting Book Details:
Retrieve a book by ID:
<?php // ... (previous code) ... $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" )); } }); // ... (rest of the code) ...
The route parameter :id
is passed to the callback function. Optional parameters use /book(/:id)
. For optional parameters without explicit callback arguments, use func_get_args()
.
Adding and Editing Books:
post()
adds, and put()
updates books:
<?php require "Slim/Slim.php"; $app = new Slim(); $app->get("/", function () { echo "<h1 id="Hello-Slim-World">Hello Slim World</h1>"; }); $app->run(); ?>
$app->request()->post()
and $app->request()->put()
retrieve POST and PUT data respectively. For browser-based PUT requests, use a hidden field _METHOD
with value "PUT" in your form.
Deleting Books:
Delete a book by ID:
<?php $app = new Slim(array( "MODE" => "development", "TEMPLATES.PATH" => "./templates" )); ?>
The delete()
method removes the database record. The map()
method handles multiple HTTP methods on a single route (not shown here).
Conclusion:
This article demonstrates building a basic RESTful web service with Slim. Further development should include robust error handling and input validation. The source code (not included here) can be found on GitHub (link not provided in original text). The FAQs section of the original text is omitted as it provides basic information readily available through Slim's documentation.
The above is the detailed content of PHP Master | Writing a RESTful Web Service with Slim. For more information, please follow other related articles on the PHP Chinese website!

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool