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 <? Php
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 "10 });
11
12 // run the Slim app
13 $ app-> run ();
Now you are preparing your first SLIM application. If you access the index. php file through a browser, you should see a big "Hello slim world ."
Slim used in your application, you need to include Slim. php and Slim, which will automatically load all other files it requires. Then, you can create one or more instance slim objects and add your routes.
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 to the application environment used for development or production. TEMPLATES. PATH sets the location of the template file. Slim uses Slim_View, which presents the viewpoint by default, but you can write a custom view handler and use additional slim value. The following example shows how to create a new custom instance TEMPLATES. PATH and set the development mode of the environment.
1 <? Php
2 $ app = new Slim (array (
3 "MODE" => "development ",
4 "TEMPLATES. path' =>"./templates"
5 ));
Creating an application using Slim is the most important part of creating a route. Routing helps a URI map to a callback function of a specific request method. Slim provides a simple and intuitive way to map different requirements using the same URI. It will call the callback function, match the current URI and request method, or generate a 404 error, if it is incomparable. After joining the route, you need to call the run () method to slim the application running on the instance.
Write a library service
In a deeper movement, let's create a simple library to manage Web service applications using Slim Lines. In this application, we can list, add, delete, and update Web service calls in detail.
The following table lists the endpoints that will support Web services:
For database interaction, I will use NotORM's written JakubVr ána as an alternative to ORM. It provides a simple and intuitive API to interact with the database's data, PHP library. NotORM uses PHP's PDO extension to access the database, so the PDO instance is passed to the NotORM structure.
1 <? Php
2 require "NotORM. php ";
3
4 $ pdo = new PDO ($ dsn, $ username, $ password );
5 $ db = new NotORM ($ pdo );
Listed books
The first endpoint column is used to export all the books from the database, so that we can use the ultra-thin method to create the endpoint and return the encoded data in JSON format.
01 <? Php
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 });
() Is a self-tuning method that routes GET requests to the specified URI. Its first parameter is URI and the last parameter is a callback function. Using keywords, we can access external variables from the scope of anonymous functions.
In the function, we create and traverse each record returned by the database (the book array $ DB-> book () returns a book table for Traversing reference ). The Content-Type Header for sending the response is an array of encoding book data that we sent from "application/json.
Now let's write a book with the detailed information endpoint of a given ID:
01 <? Php
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 transfer route of the book. Upon execution of this route, slim uses the called callback function as the parameter value.
Note that this parameter is mandatory. You can use it to put it in brackets (optional):/book (/ID). If you are making an optional parameter, however, you will not be able to specify the callback function parameter. In this case, you can use func_get_args () to pass any parameter to the callback function.
Add and edit books
Now, let's add and update the library information at our address endpoint. We will use the post () method to add new data and () to update existing data.
01 <? Php
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 });
Return the current request object for the application request () (use POST for Slim_Http_Request) or put data. You can get the POST value POST () method of this object and use the () method to sell the value. Here, we assume that the names of two columns in the POST and PUT data table are the key/value pairs. In real-world applications, you will need to add some verification and error handling, but I have omitted it for the sake of simplicity.
If you are planning to access your slim application from a browser, you will not be able to easily make PUT requests. Generally, the browser does not pass the HTML method publicly. To overcome this problem, there is a rule that allows you to overwrite the POST request and place it in the form of a hidden field. The field name should be the value of "_ method" set to "PUT.
1 <form action = "#" method = "post">
2 <input type = "hidden" name = "_ METHOD" value = "PUT">
3 Title: <input type = "text" name = "title"> <br>
4 Author: <input type = "text" name = "author"> <br>
5 Summary: <textarea name = "summary"> </textarea>
6 <br>
7 <input type = "submit" value = "Submit">
8 </form>
Delete books
The next obvious thing we need is to add, edit, and delete books at our Web service endpoints and endpoints. It should accept the ID of the book to be deleted and delete the corresponding records from the database.
01 <? Php
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 take the given ID from the corresponding row in the database, as we have 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 all relevant books for the necessary endpoints. In some cases, you may want to have a single route that will respond to multiple request methods. It can implement the slim method of the map () used.
Summary
In this article, we have discussed creating a RESTful Web service using a slim framework. Now, you should be able to create your own Web service applications without much trouble.
Of course, there are also many things that can be done simply than the ones discussed here. You can have many parameters, data verification, and other routes. Therefore, deep dive and love slim and NoORM tools to help you achieve your goals.
Author: ssoftware