Вы можете использовать ORM базы данных, например Eloquent для подключения вашего приложения SlimPHP к базе данных.
composer require illuminate/database "~5.1"
Добавьте настройки базы данных в массив настроек Slim.
<?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' => '',
]
],
];
В вашем dependencies.php
или где вы добавляете свои Служебные Фабрики:
// 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;
};
$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);
};
<?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;
}
}
...
$records = $this->table->where('name', 'like', '%foo%')->get();
...
...
$record = $this->table->find(1);
...
Eloquent Documentation