slimphp / Slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
http://slimframework.com
MIT License
11.98k stars 1.95k forks source link

Example for beginners on how to call vars from $this when looking at values from settings.php #3134

Closed Guyverix closed 2 years ago

Guyverix commented 2 years ago

Thanks for the great framework! As a beginner it is really helping me learn more of the basics about how to write a good application. I am running into a bit of trouble however. I am attempting to pull my database connection values out of the settings.php, which IS loaded into the $this object (confirmed in get_object_vars), however I am not really able to get the syntax correct. Google is failing me on this as well, sadly.

I have added the database connection information as shown in some online examples and see the values themselves, but cannot for the life of me figure out how the hell to retrieve the values.

Any tips on how I can walk down an object tree to retrieve the values? Things like $this->db do not give me any data, and return errs.

from the object dump I see this:

[db] => Array ( [driver] => mysql [host] => 192.168.15.250 [username] => randoUser [database] => event [password] => XXXXXX [charset] => utf8mb4 [collation] => utf8mb4_unicode_ci [flags] => Array ( [12] => [3] => 2 [20] => 1 [19] => 2 ) ) ) )

So since I know it is loaded into the object, I just need to learn how to get TO the silly thing.. This is on PHP7.4, running on Ubuntu..

Config from settings.php:

            return new Settings([
                'displayErrorDetails' => true, // Should be set to false in production
                'logError'            => true,
                'logErrorDetails'     => true,
                'logger' => [
                    'name' => 'slim-app',
                    'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
                    'level' => Logger::DEBUG,
                ],
                "db" => [
                    'driver' => 'mysql',
                    'host' => '192.168.15.250',
                    'username' => 'randoUser',
                    'database' => 'event',
                    'password' => 'XXXXXX',
                    'charset' => 'utf8mb4',
                    'collation' => 'utf8mb4_unicode_ci',
                    'flags' => [
                        // Turn off persistent connections
                        PDO::ATTR_PERSISTENT => false,
                        // Enable exceptions
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        // Emulate prepared statements
                        PDO::ATTR_EMULATE_PREPARES => true,
                        // Set default fetch mode to array
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                    ],

The how-to for configuring the database connections was followed from: https://arjunphp.com/how-to-connect-to-mysql-database-in-slim-framework-4/

$test = $this->get(PDO::class);
returns:
"Call to undefined method…\NewPollerAction::get()"
RyanNerd commented 2 years ago

This isn't really a Slim issue. I'll try and help anyway. It appears that you've not properly set up your dependencies in app/dependencies.php

$test = $this->get(PDO::class): should return an instance of PDO with your DB configurations.

According to the guide you should do something more like this in app/routes.php:

$app->get('/db-test', function (Request $request, Response $response) { 
       $db = $this->get(PDO::class); // get a PDO instance with your DB configs baked in via Dependency Injection
       $sth = $db->prepare("SELECT * FROM tasks ORDER BY task"); // Assumes you have a tasks table to select from
       $sth->execute(); 
       $data = $sth->fetchAll(PDO::FETCH_ASSOC); // Get all records from the task table
       $payload = json_encode($data); // serialize the task table data
       $response->getBody()->write($payload); // Tell the response object what we are sending back as a response
       return $response->withHeader('Content-Type', 'application/json');  // Slim will send the tasks table data as JSON 
});

This may be of interest to you (It's a work in progress) but I've created a one-way framework called Willow that uses Slim and Eloquent ORM to quickly establish routes to a database CRUD interface.

Guyverix commented 2 years ago

I have the dependencies file updated the way the example shows, and I do see the values in the object itself. I am just trying to figure out how to pull those values from within the object.

What I am shooting for is something like this I THINK:

$foo = $this->setttings->db->host 
to retrieve the hostname for the database..

I do already have ways to get the auth (old stye requires) but if I want to learn how to do it right, I think I am going to have to learn much more about how to pull the info I want out of the container object since it is already loaded. I am trying to do this right (I hope), and not have my passwords scattered all over the application, and only call the object for connection info when needed.

I am reading up on your willow framework, but hesitate to switch over as I have a lot of API's written that are working, but need to clean my code up to at least kindergarten levels no matter which framework I use :)

RyanNerd commented 2 years ago

I think I am going to have to learn much more about how to pull the info I want out of the container object since it is already loaded. I am trying to do this right (I hope), and not have my passwords scattered all over the application, and only call the object for connection info when needed.

The example you are following uses Dependency Injection (which took me some time to wrap my head around). DI is great once you have that ah ha moment. If done correctly you shouldn't have any of your configuration data "scattered" it should be loaded once in the configuration settings and then be globally available through the DI get('thing_i_need') method.

I am reading up on your willow framework, but hesitate to switch over as I have a lot of API's written that are working, but need to clean my code up to at least kindergarten levels no matter which framework I use :)

Willow is a work in progress and I wouldn't suggest switching if you've already have a significant amount of code invested targeting a different API.

I wish you the best. You may want to move this issue to Slim-Skeleton since that is the repo the example you are following uses. Devs that subscribe to that repo may be better able to offer you help and direction.

Guyverix commented 2 years ago

Gotcha, will close this out and make a new one over there..