Slim is a full-featured, open-source PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. It comes with a sophisticated URL dispatcher and middleware architecture that makes it ideal for static websites or API prototyping. It supports all(GET, POST, PUT, DELETE) the HTTP methods.
This article examines Slim in detail, illustrating how you can use it to rapidly build and deploy a REST API with support for authentication and multiple request/response formats.
How to install
If you are using Composer, the PHP dependency manager, simply issue the following command
$ php composer.phar create-project slim/slim-skeleton [my-app-name] (or) $ composer create-project slim/slim-skeleton [my-app-name]
Replace [my-app-name] with the desired directory name for your new application. The above command will create a project using Slim-Skeleton application and it has below show directory structure.
Now You can run it with PHP’s built-in webserver or you can point your browser with full URL.
$ cd [my-app-name]; $ php -S localhost:8080 -t public public/index.php
So after gone through the above steps, if you point your browser to http://locahost:8080/
, you would have following output in the browser –
Database design and table
Name your database whatever you want, and run below shown SQL it will create task table.
-- -- Table structure for `tasks` -- CREATE TABLE IF NOT EXISTS `tasks` ( `id` int(11) NOT NULL, `task` varchar(200) NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1', `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `tasks` ADD PRIMARY KEY (`id`); ALTER TABLE `tasks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Insert some sample data into the tasks table.
INSERT INTO `tasks` (`id`, `task`, `status`, `created_at`) VALUES (1, 'Find bugs', 1, '2016-04-10 23:50:40'), (2, 'Review code', 1, '2016-04-10 23:50:40'), (3, 'Fix bugs', 1, '2016-04-10 23:50:40'), (4, 'Refactor Code', 1, '2016-04-10 23:50:40'), (5, 'Push to prod', 1, '2016-04-10 23:50:50');
Database configuration
Open your src/settings.php
file and configure your database setting by adding/editing below showing database config array.
// Database connection settings "db" => [ 'driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'arjun', 'username' => 'root', 'password' => '', 'collation' => 'utf8_general_ci', 'charset' => 'utf8', 'prefix' => '' ],
Adding Eloquent to your application
Now that we have over application ready, let’s install Eloquent with the composer:
composer require illuminate/database
You should run above command from the root of your project and it will pull the eloquent library and its dependency to vendor directory.
Now instantiate the capsule manager and boot Eloquent in publc/index.php
file.
// Register routes require __DIR__ . '/../src/routes.php'; $container = $app->getContainer(); $dbSettings = $container->get('settings')['db']; $capsule = new Illuminate\Database\Capsule\Manager; $capsule->addConnection($dbSettings); $capsule->bootEloquent(); $capsule->setAsGlobal(); // Run app $app->run();
Lets create a folder to hold eloquent models,for example app/models
at root of your project.
// create folders $ mkdir -p app/models
Now open your composer.json
file and update it with below ps4 autoload options,
....... ..... "require-dev": { "phpunit/phpunit": ">=4.8 < 6.0" }, "autoload": { "psr-4": { "App\\": "app/" } }, "autoload-dev": { ..... ..../
Now run composer dump-autoload command from project root to update autoload reference files.
$ composer dump-autoload
Now create Task.php
model with following content:
We are going to implement following API calls -
Method | URL | Action |
---|---|---|
GET | /todos | Retrieve all todos |
GET | /todos/search/bug | Search for todos with ‘bug’ in their name |
GET | /todo/1 | Retrieve todo with id == 1 |
POST | /todo | Add a new todo |
PUT | /todo/1 | Update todo with id == 1 |
DELETE | /todo/1 | Delete todo with id == 1 |
Implementing the API calls with Slim
Now that we have our Slim app up and running with the database connection, we need to manage todos in the database.
Getting the Todos list - We are going to create a new route so that when a user hits /todos, it will return a list of all todos in JSON format. Open your src/routes.php
and add
// get all todos $app->get('/todos', function ($request, $response, $args) { $todos = Task::all(); return $this->response->withJson($todos); });
This function simply return all todos information as you can see in this query, to call this API use this URL http://localhost:8080/todos
.
Getting single todo - We are going to create a new route so that when a user hits /todo/{id}, it will return a todo in JSON format.
// Retrieve todo with id $app->get('/todo/[{id}]', function ($request, $response, $args) { $todo = Task::find($args['id']); return $this->response->withJson($todo); });
This function check record of given id and return if found anything, to call this API use this URL http://localhost:8080/todo/1
.
Find todo by name - We are going to create a new route so that when a user hits /todos/search/{Query}, it will return a list of all matched todos in JSON format.
// Search for todo with given search teram in their name $app->get('/todos/search/[{query}]', function ($request, $response, $args) { $todos = Task::where('task', 'like', "%".$args['query']."%"); return $this->response->withJson($todos); });
This function search in database for your given query, to call this API use this URL http://localhost:8080/todos/search/bug
Add todo - We are going to create a new route so that when a user sends a post request to /todo with required data, the app will add a new record to the database.
// Add a new todo $app->post('/todo', function ($request, $response) { $input = $request->getParsedBody(); $task = Task::craete(['task' => $input['task']]); return $this->response->withJson($task); });
This API accepts post request and insert submitted data into your database. To call this API use this URL http://localhost/todo
Delete Task - We are going to create a new route so that when a user sends a delete request to /todo/{id}, the app will delete a record from the database.
// DELETE a todo with given id $app->delete('/todo/[{id}]', function ($request, $response, $args) { $task = Task::destroy($args['id']); return $this->response->withJson($task); });
Update Task - We are going to create a new route so that when a user sends a put request to /todo/{id} with required data, the app will update a record based on match parameter in the database.
// Update todo with given id $app->put('/todo/[{id}]', function ($request, $response, $args) { $input = $request->getParsedBody(); $task = Task::find($args['id']); $task->task = $input['task']; $task->save(); return $this->response->withJson($task); });
This API accept put request and updates submitted data in your database. To call this API use this URL http://localhost/todo/{id}