Reputation: 159
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.
Upvotes: 1
Views: 758
Reputation:
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
Upvotes: 0
Reputation: 26056
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.
Upvotes: 2