Accessing class instantiated outside slim from class instantiated inside slim?

StackOverflow https://stackoverflow.com/questions/20736576

  •  20-09-2022
  •  | 
  •  

Pergunta

require ('dataclass.php');
$db = new DataClass();

$app = new \Slim\Slim();

$app->group('/api/v1', function () use ($app, $db) {

  require('processingclass.php');
  $foo = new FooClass();

});

This above is obviously an incomplete Slim example. But, how would I call a $db method from within $foo?

I have a bunch of routes and want to have access to the DB class from all the secondary classes used in the individual routes - w/o setting a global or loading/instantiating the DB class within each secondary class or route.

Foi útil?

Solução

Not 100% clear on the Slim framework structure or if there are built in methods to handle such a task in Slim, but would it not be best to pass it this way?

$foo = new FooClass($db);

And then in the FooClass() just have a call to set the $db in constructor? Something like this?

class FooClass {

  private $db = null;

  function __construct($db) {

    $this->db = $db;

  }

}

Again my POV is coming from generic PHP class & OOP knowledge. So unclear if there is a better way in Slim. If there is, would be welcome to understand more.

Outras dicas

The "right" way to do this is declare in the app container (index.php). You already got the $app initiating Slim. Get the container using $container = $app->getContainer();

After this you just simply do this:

$container['fooclass'] = function($container) {
    $fooClass = new FooClass(...)
    return $fooClass
}

Then you can use it everywhere doing

$this->fooclass
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top