Use Eloquent ORM in Slim framework

1

Slim is a micro web framework like Flask or Sinatra but for PHP. Eloquent ORMis a powerful database toolkit and it serves as a database layer of the Lravel PHP framework. Now, this time i will install Elequent ORM in Slime framework and build some Restful API with it. Let’s get started!

Here is the part of composer.json in my project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
"require": {
"php": ">=5.5.0",
"slim/slim": "^3.1",
"slim/php-view": "^2.0",
"monolog/monolog": "^1.17",
"overtrue/pinyin": "~3.0",
"illuminate/database": "~4.2"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"app\\": "src/app/"
}
},

In my project, i use the illuminate/database 4.2 because my PHP version is 7.0 which is not support some feature like this:

1
[$foo, $bar] = [1,2];

But if you have higher PHP version you can try the latest Eloquent.

Run the composer install to install the repo into the project.

Config Eloquent

After downloading the Eloquent we should configure it so that our application will know about it. Open the src/config.php and add databse setting array:

1
2
3
4
5
6
7
8
9
10
'db' => [
'driver' => 'mysql',
'host' => '127.0.0.1:3306',
'database' => 'test_db',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]

boost Eloquent

now instantiate the capsule manager and boost Eloquent in public/index.php:

1
2
3
4
5
6
7
8
$dbSettings = $container->get('settings')['db'];
$capsule = new Illuminate\Database\Capsule\Manager;
$capsule->addConnection($dbSettings);
$capsule->bootEloquent();
$capsule->setAsGlobal();

// Run app
$app->run();

create Model

OK. Every thing has done, Let’s create my database model. Create src/app/model/Goods.php file and edit:

1
2
3
4
5
6
7
8
namespace app\model;

use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{
protected $table = 'goods';
}

Class Goods extends Illuminate\Database\Eloquent\Model so it can retrieve and store data from our databse. The $table property assigns which data table this model will use.

write restful API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace app\controller;

use Slim\Http\Request;
use Slim\Http\Response;
use app\model\Goods;

class GoodsController
{
public function index(Request $request, Response $response)
{
return Goods::orderBy('id', 'asc')->first()->toJson();
}

public function info(Request $request, Response $response, $args)
{
$id = $args['id'];
return $response->getBody()->write(Goods::find($id));
}
}

Edit the src/routes.php:

1
2
$app->get('/goods', 'app\controller\GoodsController:index');
$app->get('/goods/{id}', 'app\controller\GoodsController:info');

That’s works! Happy Hacking!