DavidePastore / Slim-Config

A file configuration loader that supports PHP, INI, XML, JSON, and YML files for the Slim Framework. It internally uses https://github.com/hassankhan/config.
34 stars 7 forks source link

Ability to access configuration on middleware #3

Closed gusrub closed 8 years ago

gusrub commented 8 years ago

This is more of a question than anything. As I read on the documentation there are two possible ways to load the configuration values:

However, how can I load the configuration within a callable for a middleware? take the following code:

$app->add(function($request, $response, $next) {
    $this->db = new DatabaseManager('host', 'user', 'pwd', 'database');
    $response = $next($request, $response);
    return $response;
});

In the example above I'm adding the db instance so I can do queries within my routes, however, the configuration instance is not available at that point, so if I do this:

$app->add(function($request, $response, $next) {
    $config = $this->config->getConfig();
    $host = $config->get('database.host');
    $this->db = new DatabaseManager($host, 'user', 'pwd', 'database');
    $response = $next($request, $response);
    return $response;
});

It won't work because $config is null (or the return value of getConfig() for that matter). Is there a way to make that work? Maybe I'm missing something or I still don't completely understand the order of execution in the middleware/container.

Thanks in advance!

gusrub commented 8 years ago

I'm just going to answer my own silly question, thing is, that middleware runs on the opposite order that I thought so I was adding the config middleware to the container before adding the one for the database but it must be the other way around because of the order of the callables.

Reading the documentation on middleware helped me understood this.

DavidePastore commented 8 years ago

Hi @gusrub, it's nice to know that you were able to solve the problem. Thank you for sharing your solution. :+1: I'm closing this issue.

musaev-haybulla commented 3 years ago

I'm just going to answer my own silly question, thing is, that middleware runs on the opposite order that I thought so I was adding the config middleware to the container before adding the one for the database but it must be the other way around because of the order of the callables.

Reading the documentation on middleware helped me understood this.

I love you, man)))))))