Browse Source

src: Set up an inventory helper

master
Elis Hirwing 3 years ago
parent
commit
de767e4f8d
Signed by: etu GPG Key ID: D57EFA625C9A925F
  1. 10
      public/index.php
  2. 20
      src/Etu/Controller/Inventory.php
  3. 29
      src/Etu/Helpers/Inventory.php

10
public/index.php

@ -2,6 +2,8 @@
require_once(__DIR__.'/../vendor/autoload.php');
use Etu\Controller\Inventory as InventoryController;
use Etu\Helpers\Inventory as InventoryHelper;
use Monolog\Logger;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
@ -27,7 +29,7 @@ $container['logger'] = function (Slim\Container $c) {
return $logger;
};
$container['db'] = function (Slim\Container $c) {
$container[PDO::class] = function (Slim\Container $c) {
$pdo = new PDO('sqlite:../sqlite.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
@ -44,11 +46,15 @@ $container['db'] = function (Slim\Container $c) {
return $pdo;
};
$container[InventoryHelper::class] = function (Slim\Container $c) {
return new InventoryHelper($c[PDO::class]);
};
/**
* Set up controllers
*/
$container[InventoryController::class] = function (Slim\Container $c) {
return new InventoryController($c['logger'], $c['db']);
return new InventoryController($c[Logger::class], $c[InventoryHelper::class]);
};
$app->run();

20
src/Etu/Controller/Inventory.php

@ -1,36 +1,28 @@
<?php
namespace Etu\Controller;
use Etu\Helpers\Inventory as InventoryHelper;
use Monolog\Logger;
use PDO;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class Inventory
{
/** @var PDO */
private $db;
/** @var InventoryHelper */
private $inventoryHelper;
/** @var Logger */
private $logger;
public function __construct(Logger $logger, PDO $db)
public function __construct(Logger $logger, InventoryHelper $inventoryHelper)
{
$this->db = $db;
$this->logger = $logger;
$this->inventoryHelper = $inventoryHelper;
}
public function get(Request $request, Response $response, array $args)
{
// Prepare query
$stmt = $this->db->prepare('SELECT * FROM inventory WHERE item_name = :item_name');
// Bind value
$stmt->bindValue('item_name', $args['item'], PDO::PARAM_STR);
// Execute and fetch result
$stmt->execute();
$items = $stmt->fetchAll();
$items = $this->inventoryHelper->get($args['item']);
// No such item
if (count($items) === 0) {

29
src/Etu/Helpers/Inventory.php

@ -0,0 +1,29 @@
<?php
namespace Etu\Helpers;
use PDO;
class Inventory
{
/** @var PDO */
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function get(string $name) : array
{
// Prepare query
$stmt = $this->db->prepare('SELECT * FROM inventory WHERE item_name = :item_name');
// Bind value
$stmt->bindValue('item_name', $name, PDO::PARAM_STR);
// Execute and fetch result
$stmt->execute();
return $stmt->fetchAll();
}
}
Loading…
Cancel
Save