-1

Good morning

How Can I use $settings $logger and $db in __construct from the $container in dependencies.php in a Model function in a Slim Api?

I have the following setup for my Slim framework Api:

settings.php (has $settings $looger and $db in $container)

/src/Models/DataModel.php

namespace Namespace\Api\Models\v1;

class DataModel
{
    private $settings;
    private $logger;
    private $db;


    function __construct($settings, $logger, $db) {
        $this->settings = $settings;
        $this->logger = $logger;
        $this->db = $db;
    }
    function get() {
         ****
    }
}

routes.php

use Slim\Http\Request;
use Slim\Http\Response;

$app->group('/v1', function () use ($app) {
    $app->GET('/imprint/[{id}]', 'Namespace\Api\Models\v1\DataModel:get');
});

The Error Message I get is:

 Too few arguments to function eRecht24\Api\Models\v1\ImprintModel::__construct()

If I understand correctly I need to instantiate the model like so in order to pass $settings $logger and $db:

$model = new Namespace\Api\Models\v1\DataModel($container->settings, $container->logger, $container->db);

As far as I can tell they ($container->settings etc.) are not resolving however. Is this instantiation correct and where do I put it in order to be able to use $settings $logger and $db in my Model functions?

yivi
  • 42,438
  • 18
  • 116
  • 138
j00ls
  • 95
  • 2
  • 14

2 Answers2

0

If you want to able to pass parameter other than container to constructor, you need to register its factory in dependency container.

When class can not be found inside dependency container, Slim try to create it and pass container instance for you. That is why your ImprintModel in your answer is working.

If you want to use constructor with parameters

namespace Namespace\Api\Models\v1;

class DataModel 
{

   public function __construct($settings, $logger, $db) 
   {
      ...
   } 
}

in you dependency registration, you need to add

$container[\Namespace\Api\Models\v1\DataModel::class] = function ($c) {
    $settings = $c['settings']; 
    $logger = $c['logger']; 
    $db = $c['db']; 
    return new \Namespace\Api\Models\v1\DataModel($settings, $logger, $db);
}
Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
-1

Thanks to fresh morning spirit I figured it out on my own but I really sat on this for 2 hours yesterday... :(

The DataModel has to look like this:

class ImprintModel
{
    protected $c;
    private $settings;
    private $logger;
    private $db;


    function __construct($container) {

        $this->c = $container;
        $this->settings = $container['settings'];
        $this->logger = $container['logger'];
        $this->db = $container['db'];
    }
j00ls
  • 95
  • 2
  • 14