Slim 3 and pdo usage
I have seen and use database in Slim 3 with the code below:
in settings.php
'pdo' => [
'dsn' => 'mysql:host=localhost;dbname=dbnotes;charset=utf8',
'username' => 'uname',
'password' => 'upass',
],
In dependencies.php
$container['pdo'] = function ($c) {
$settings = $c->get('settings')['pdo'];
return new PDO($settings['dsn'], $settings['username'], $settings['password']);
};
$container['App\Action\HomeAction'] = function ($c) {
return new App\Action\HomeAction($c->get('view'), $c->get('logger'), $c['pdo']);
};
In Routes.php
$app->get('/', 'App\Action\HomeAction:dispatch')->setName('homepage');
In ActionController.php
public function dispatch(Request $request, Response $response, $args)
{
$this->logger->info("Home page action dispatched");
$stmt = $this->pdo->prepare('SELECT * FROM books ORDER BY id ASC');
$stmt->execute();
$result = array();
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$result[] = array($row['id'], $row['title']);
}
print_r($result);
}
It works but I wonder is there a better way?
Is there a way to make something like $SlimApp->db->query(), ->connect(), etc and call $SlimApp from anywhere?
If there is how is that done?
Thanks in advance.
Comments are currently closed for this discussion. You can start a new one.
Keyboard shortcuts
Generic
? | Show this help |
---|---|
ESC | Blurs the current field |
Comment Form
r | Focus the comment reply box |
---|---|
^ + ↩ | Submit the comment |
You can use Command ⌘
instead of Control ^
on Mac
1 Posted by chanh.ong on 03 Mar, 2016 10:00 PM
I try one method, instead of passing individual variable I just pass the entire $SlimApp variable then I just use it with whatever variable in $SlimApp.
In dependencies.php
In HomeAction Controller
$container['App\Action\HomeAction'] = function ($c) {
return new App\Action\HomeAction($c);
};
final class HomeAction
{
private $app;
public function __construct($app)
{
$this->app = $app;
}
public function dispatch(Request $request, Response $response, $args)
{
$this->app->logger->info("Home page action dispatched");
$stmt = $this->app->pdo->prepare('SELECT * FROM books ORDER BY id ASC');
$stmt->execute();
$result = array();
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$result[] = array($row['id'], $row['title']);
}
print_r($result);
$this->app->view->render($response, 'home.twig');
return $response;
}
}
Is this a good way?
Thanks
Josh Lockhart closed this discussion on 12 Feb, 2021 07:39 PM.