get_called_class vs get_class
string get_called_class ( void ) // Gets the name of the class the static method is called in.
string get_class ([ object $object = NULL ] ) // Gets the name of the class of the given object.
-------- get_called_class
class foo {
static public function test() {
var_dump(get_called_class());
}
}
class bar extends foo {
}
foo::test(); // string(3) "foo"
bar::test(); // string(3) "bar"
--------- get_class
• get_class($this)
• get_class($bar)
class foo {
function name()
{
echo "My name is " , get_class($this) , "\n";
}
}
$bar = new foo(); // create an object
echo "Its name is " , get_class($bar) , "\n"; // external call // Its name is foo
$bar->name(); // internal call // My name is foo
----------
abstract class bar {
public function __construct()
{
var_dump(get_class($this));
var_dump(get_class());
}
}
class foo extends bar {
}
new foo;
string(3) "foo"
string(3) "bar"
Category: Uncategorized
Slim 3 API Part 2 DB Configurations
Database configuration
Create the file src/settings.php inside your api folder and place the following code
"db" => [
"host" => "locahost",
"dbname" => "your-database-name",
"user" => "your-mysql-user",
"pass" => "your-mysql-password"
],
Create the file src/dependencies.php inside your api folder and place the following code
$container['db'] = function ($c) {
$settings = $c->get('settings')['db']; // From src/settings.php
$pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
$settings['user'], $settings['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
This is injecting the database object into container, and you can now access all users
** For creating the users table see Create users table post
require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App;
$app->get('/', function ($request, $response) {
return 'hello world';
});
$app->post('/postit', function ($request, $response) {
$input = $request->getParsedBody();
return $this->response->withJson($input);
});
$app->get('/all', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
$users = $sth->fetchAll();
return $this->response->withJson($users);
});
$app->run();