-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
139: Practice Exercise: Building a RESTful API with Slim Framework
A few years ago, I worked with a developer named Marcus who was building a backend for a niche mobile app. He didn't want the overhead of a full-stack framework, so he decided to "keep it simple" by using vanilla PHP. He ended up with a directory full of files like get_user.php, update_user.php, and delete_post.php. Whenever he wanted to change a URL structure or add a middleware check for authentication, he had to manually edit dozens of files. It was a maintenance nightmare. He eventually came to me exhausted, asking why his "simple" approach felt so complex. That's when I introduced him to Slim.
Slim is what we call a micro-framework. It doesn't try to give you an ORM, a template engine, or a complex folder structure. Instead, it does one thing exceptionally well: it maps an HTTP request to a specific piece of code. In the world of RESTful APIs, this is exactly what you need. You get a clean way to define your endpoints, handle different HTTP methods (GET, POST, PUT, DELETE), and manage the request and response cycle without getting bogged down in the plumbing of PHP's global variables.
Defining Clean API Endpoints
In a RESTful architecture, the URL should represent the resource, and the HTTP method should represent the action. When you're using Slim, you stop thinking about "files" and start thinking about "routes." Instead of routing a user to /api/books/delete.php?id=12, you define a route for DELETE /books/{id}. This makes your API intuitive for whoever is consuming it.
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// A simple GET endpoint to fetch a list of books
$app->get('/books', function (Request $request, Response $response) {
$books = [
['id' => 1, 'title' => 'The Pragmatic Programmer', 'author' => 'Hunt & Thomas'],
['id' => 2, 'title' => 'Clean Code', 'author' => 'Robert C. Martin'],
];
$payload = json_encode($books);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
});
$app->run();
I love how explicit this is. You can see at a glance that /books handles GET requests. If you tried to send a POST request to that same URL, Slim would automatically handle the 405 Method Not Allowed response for you, saving you from writing that logic yourself.
Managing the Request-Response Cycle
One of the biggest hurdles for developers moving from vanilla PHP to Slim is the shift toward PSR-7. In the old way, you'd just echo a string and call exit(). In Slim, you work with Request and Response objects. This might feel like extra work at first, but it's actually a superpower. Because the response is an object, you can pass it through various middleware—like an authentication layer—that can modify the headers or the body before it ever reaches the user.
When building a REST API, you'll frequently deal with JSON payloads. Instead of accessing $_POST, you'll use the request object to parse the body. This ensures that your API can handle application/json content types, which is the standard for modern front-ends. You wrap your data in json_encode(), write it to the response body, and crucially, set the Content-Type header so the client knows how to parse the result.
📋 Practical Task
Exercise: Building a Gadget Inventory API
Your task is to build a small RESTful API using the Slim Framework to manage a collection of electronic gadgets. You don't need a database for this; a simple hard-coded array will suffice to simulate your data store.
Requirements:
- GET /gadgets: Return a JSON list of all gadgets. Each gadget should have an
id,name, andcategory. - GET /gadgets/{id}: Return a single gadget based on the ID provided in the URL. If the ID doesn't exist in your array, return a 404 Not Found response.
- POST /gadgets: Accept a JSON payload containing a
nameandcategory, and return the created gadget along with a 201 Created status code.
Constraint: Ensure all responses are sent with the Content-Type: application/json header. Use PSR-7 Request and Response objects throughout your routes.
There are no comments for now.