在 Slim 中使用 Eloquent

你可以使用 Eloquent 这种数据库 ORM 将你的 Slim 应用程序连接到数据库。

为你的应用程序添加 Eloquent

  1. composer require illuminate/database "~5.1"

Figure 1: Add Eloquent to your application.

配置 Eloquent

在 Slim 的 setting 数组中添加数据库设置项。

  1. <?php
  2. return [
  3. 'settings' => [
  4. // Slim Settings
  5. 'determineRouteBeforeAppMiddleware' => false,
  6. 'displayErrorDetails' => true,
  7. 'db' => [
  8. 'driver' => 'mysql',
  9. 'host' => 'localhost',
  10. 'database' => 'database',
  11. 'username' => 'user',
  12. 'password' => 'password',
  13. 'charset' => 'utf8',
  14. 'collation' => 'utf8_unicode_ci',
  15. 'prefix' => '',
  16. ]
  17. ],
  18. ];

Figure 2: Settings array.

dependencies.php 中,或者其他任意位置添加你的 Service Factories:

  1. // Service factory for the ORM
  2. $container['db'] = function ($container) {
  3. $capsule = new \Illuminate\Database\Capsule\Manager;
  4. $capsule->addConnection($container['settings']['db']);
  5. $capsule->setAsGlobal();
  6. $capsule->bootEloquent();
  7. return $capsule;
  8. };

Figure 3: Configure Eloquent.

传递数据表实例到控制器

  1. $container[App\WidgetController::class] = function ($c) {
  2. $view = $c->get('view');
  3. $logger = $c->get('logger')
  4. $table = $c->get('db')->table('table_name');
  5. return new \App\WidgetController($view, $logger, $table);
  6. };

Figure 4: Pass table object into a controller.

从控制器中查询数据表

  1. <?php
  2. namespace App;
  3. use Slim\Views\Twig;
  4. use Psr\Log\LoggerInterface;
  5. use Illuminate\Database\Query\Builder;
  6. use Psr\Http\Message\ServerRequestInterface as Request;
  7. use Psr\Http\Message\ResponseInterface as Response;
  8. class WidgetController
  9. {
  10. private $view;
  11. private $logger;
  12. protected $table;
  13. public function __construct(
  14. Twig $view,
  15. LoggerInterface $logger,
  16. Builder $table
  17. ) {
  18. $this->view = $view;
  19. $this->logger = $logger;
  20. $this->table = $table;
  21. }
  22. public function __invoke(Request $request, Response $response, $args)
  23. {
  24. $widgets = $this->table->get();
  25. $this->view->render($response, 'app/index.twig', [
  26. 'widgets' => $widgets
  27. ]);
  28. return $response;
  29. }
  30. }

Figure 5: Sample controller querying the table.

使用 where 查询数据表

  1. ...
  2. $records = $this->table->where('name', 'like', '%foo%')->get();
  3. ...

Figure 6: Query searching for names matching foo.

通过 id 查询数据表

  1. ...
  2. $record = $this->table->find(1);
  3. ...

Figure 7: Selecting a row based on id.

了解更多

Eloquent 文档