I’m using Slim
framework for develop a Restful API
. I configured the Framework
dependencies in this way:
<?php
$container = $app->getContainer();
$container['db'] = function($config)
{
$db = $config['db'];
$pdo = new PDO('mysql:host=' . $db['host'] . ';port=' . $db['port'] . ';dbname=' . $db['dbname'], $db['user'], $db['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
this file is called from index.php
which contains the following structure:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require('vendor/autoload.php');
$settings = require __DIR__ . '/src/settings.php';
$app = new \Slim\App($settings);
require __DIR__ . '/src/dependencies.php';
require __DIR__ . '/src/routes.php';
$app->run();
I read the database configuration from settings.php
, which return an array that have the following content:
return [
'settings' =>
[
//Configurazione database.
'db' =>
[
'port' => 3306,
'host' => 'localhost',
'dbname' => 'mydb',
'user' => 'root',
'pass' => 'root',
],
],
];
inside the routes.php
I defined a simple method that return all the countries available:
<?php
use Slim\Http\Request;
use Slim\Http\Response;
$app->get('/get_countries', function (Request $request, Response $response, array $args)
{
$sth = $this->db->query("SELECT * FROM country");
$countries = $sth->fetchAll(PDO::FETCH_OBJ);
echo json_encode($countries);
});
my request is done as: http://localhost:8081/swp/get_countries
but will return:
if I write only echo "test"
inside get_countries
all working well, what is wrong?
you can download my project here: https://files.fm/u/5ww8c4be