dongrandi8411 2016-05-13 14:11
浏览 96
已采纳

访问fetchObject()中的PDO连接 - 实例

I'm refactoring parts of my application and replace some fetch(PDO::FETCH_ASSOC) to dedicated classes with fetchObject().

Is there a way to access the pdo instance inside the generated class? See this example:

class User
{ 
    private $id;
    private $username;
    private $firstname;
    private $lastname;

    public function setFirstname($newValue)
    { 
        if (empty($newValue) || !is_string($newValue)) throw new Exception('Wrong');
        $this->firstname = $newValue;
    } 

    public function save()
    {
        // IMPORTANT PART:
        // I don't want to use the global object container here  
        $dbh = Application::getInstance()->getPDO();

        $sth = $dbh->prepare('UPDATE main_user SET firstname = :firstname WHERE id = :id');
        $sth->execute([ 
            'id'        => $this->id,
            'firstname' => $this->firstname,
        ]);
    } 
} 

$dbh = $application->getPDO();
$sth = $dbh->prepare('SELECT * FROM main_user WHERE id = ?');
$sth->execute([ 10 ]);
$user = $sth->fetchObject('User');
$user->setFirstname('Test');
$user->save();

Parts of my application use multiple databases and thus multiple pdo objects. To get reuseable code, I'd like to prevent using my global container class - and global of course.

  • 写回答

2条回答 默认 最新

  • donglefu6195 2016-05-13 14:20
    关注

    You can pass the PDO Instance so you don't have to call Application::getInstance()->getPDO() again.

    public function save(PDO $dbh)
    {
        $sth = $dbh->prepare('UPDATE main_user SET firstname = :firstname WHERE id = :id');
        $sth->execute([ 
            'id'        => $this->id,
            'firstname' => $this->firstname,
        ]);
    } 
    // and pass the (already available) $dbh to the save-Method at the buttom
    $user->save($dbh);
    

    or as CD001 mentioned in the comments, you can also pass it to the constructor:

    class User
    {
        // ...
        private $conn;
    
        public function __construct(PDO $conn)
        {
            $this->conn = $conn;
        }
    }
    // ... later at the bottom when fetching the Object:
    $user = $sth->fetchObject('User', [ $dbh ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)