在 Slim 中使用 Eloquent
你可以使用 Eloquent 这种数据库 ORM 将你的 Slim 应用程序连接到数据库。
为你的应用程序添加 Eloquent
composer require illuminate/database "~5.1"
Figure 1: Add Eloquent to your application.
配置 Eloquent
在 Slim 的 setting 数组中添加数据库设置项。
<?php
return [
'settings' => [
// Slim Settings
'determineRouteBeforeAppMiddleware' => false,
'displayErrorDetails' => true,
'db' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]
],
];
Figure 2: Settings array.
在 dependencies.php
中,或者其他任意位置添加你的 Service Factories:
// Service factory for the ORM
$container['db'] = function ($container) {
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
return $capsule;
};
Figure 3: Configure Eloquent.
传递数据表实例到控制器
$container[App\WidgetController::class] = function ($c) {
$view = $c->get('view');
$logger = $c->get('logger')
$table = $c->get('db')->table('table_name');
return new \App\WidgetController($view, $logger, $table);
};
Figure 4: Pass table object into a controller.
从控制器中查询数据表
<?php
namespace App;
use Slim\Views\Twig;
use Psr\Log\LoggerInterface;
use Illuminate\Database\Query\Builder;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class WidgetController
{
private $view;
private $logger;
protected $table;
public function __construct(
Twig $view,
LoggerInterface $logger,
Builder $table
) {
$this->view = $view;
$this->logger = $logger;
$this->table = $table;
}
public function __invoke(Request $request, Response $response, $args)
{
$widgets = $this->table->get();
$this->view->render($response, 'app/index.twig', [
'widgets' => $widgets
]);
return $response;
}
}
Figure 5: Sample controller querying the table.
使用 where 查询数据表
...
$records = $this->table->where('name', 'like', '%foo%')->get();
...
Figure 6: Query searching for names matching foo.
通过 id 查询数据表
...
$record = $this->table->find(1);
...
Figure 7: Selecting a row based on id.
了解更多
Eloquent 文档