接“秒杀系列04”上文:
主要更改的文件有:
Dsn.php
<?php
namespace App\test;
class Dsn {
private $dsn = "mysql:host=192.168.0.101;dbname=seckill;charset=utf8;user=seckill;password=BBHyiFWiXrpxji5S;";
public function getdsn() {
return $this->dsn;
}
}
Db.php
<?php
namespace App\test;
use PDO;
class Db {
private $pdo;
public function __construct($dsn) {
try {
$this->pdo = new PDO($dsn);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "mysql连接失败:" . $e->getMessage();
}
}
public function queryForRows($sql) {
try {
$stmt = $this->pdo->query($sql);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "查询失败:" . $e->getMessage();
}
}
}
User.php
<?php
namespace App\test;
class User {
private $db;
public function __construct(Db $Db) // 这里直接注入Db的实例了
{
$this->db = $Db; // 这里不在主动实例化Db了,直接用注入的Db实例
}
public function getAllUsers() : array {
return $this->db->queryForRows("select * from users");
}
}
beans.php
<?php
namespace App\test;
use DI\Container;
return [
Dsn::class => function() {
return new Dsn();
},
Db::class => function(Container $c) {
return new Db($c->get(Dsn::class)->getdsn());
},
User::class => function(Container $c) {
return new User($c->get(Db::class));
}
];