To create a Hello World application, delete the default index.php file in the application directory and create a new index.php file with the following code:
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 "
Now it’s time to prepare your first slimming application. If you access the index.php file through your browser, you should see a big "Hello Slim World."
To use Slim in your application, you need to include Slim.php and Slim will automatically load all the other files it needs. You can then create one or more instances of the Slim object and add your routes.
The slim constructor accepts an array of application configuration values. mode, TEMPLATES.PATH and watch some important configurations that we often use. The usage mode is set like development or production, the application environment used. TEMPLATES.PATH sets the location of template files to use. Slim uses Slim_View, by default, to render the view, but you can write a custom view handler and attach a Slim value by using it. The following example demonstrates how to create a new custom Slim instance TEMPLATES.PATH and set the environment's development mode.
1
2 $app = new Slim(array(
3 "MODE" => "development",
4 "TEMPLATES.PATH' => "./templates"
5 ));
Creating an app using Slim is the most important part of creating routes. Routers help map a URI to a specific request method callback function. Slim provides a simple and intuitive way to map different requirements to the same URI. It will call the callback function that matches the current URI and request method, or generate a 404 error if it is unmatched. After joining the route, you need to call the run() method of the Slim instance to run the application.
Write a library service
Before moving in more depth, let's create a simple library management web service application using Slim. In this application, we can list, add, delete, and update using Web service calls as detailed in this book.
The following table lists the endpoints that will support web services:
For database interaction, I will use NotORM written by Jakub Vrána as an alternative ORM, which provides a simple and intuitive API to interact with database data, a PHP library. NotORM uses PHP's PDO extension to access the database, so an instance of PDO is passed to NotORM's constructor.
1
2 require "NotORM.php";
3
4 $pdo = new PDO($dsn, $username, $password);
5 $db = new NotORM($pdo);
Books on the market
The first endpoint lists all the books in the library, let's use Slim to create the endpoint and return the encoded data in JSON format.
01
02 ...
03 $app = new Slim(
04 "MODE" => "development",
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 });
() is Slim's method that routes a GET request to a specified URI. Its first parameter is the URI and the last parameter is a callback function. Using keywords enables us to access external variables from the scope of the anonymous function.
In the function, we create an array of books that iterates through the database to return each record ($DB->books() returns a table of books referenced by the iteration). By sending the response with a Content-Type header of "application/json" we emit an array of encoded book data.
Now let's write a book details endpoint with a given 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 });
Here, we add a parameter, the ID delivery route of the book. When executing this route, Slim will call the callback function with the parameter value as the parameter.
Please note that this parameter is mandatory. You can make it optional by placing it within brackets like: /book(/id) if you are making a parameter optional, however, you won't be able to specify the parameters of the callback function. In this case, you can use func_get_args() with any arguments passed to the callback function to get them.
Add and edit books
Now let's let our address endpoint take care of adding and updating book information. We will use the post() method to add new data and post() to update existing data.
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 });
For application request() return the current request object (Slim_Http_Request using POST) or put data. You can get the POST value of the post() method of this object, using the POST() method of the POST value. Here, we assume that both POST and PUT data information tables have column names as key/value pairs. In a real world application, you would need to add some validation and error handling, but I've omitted it here for simplicity.
If you plan to access your Slim app from a browser, you won't be able to make a PUT request easily, browsers generally don't expose the method via HTML. To overcome this problem, Slim has a provision which allows you to override the form where the POST request will be placed in a hidden field. The name of the field should be "_method" set to the value of "PUT".
1
Delete books
The next obvious thing we need is now that we have add, edit and book list endpoints and delete books endpoints in our web service. It should accept the ID of the book to be deleted and delete the corresponding record from the database.
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 });
Everything is very simple. First, we fetch the corresponding row for a given ID from the database, just like we've already done in detail in this book. The delete() method called on the row object deletes the record from the database. www.2cto.com
We have established the necessary endpoints related to all the books. In some cases, you may want to have a single route that will respond to multiple request methods. It can be implemented using the Slim method of map().
Summary
In this article, we have discussed about creating a RESTful web service using Slim Framework. Now, you should be able to create your own web service application without too much trouble.
Of course, there are many things you can do that are simpler than those discussed here. You can have many parameters, data validation, etc. routes. So dig in and use tools like Slim and NoORM to help you achieve your goals.