数据源架构模式之行入口模式

来源:互联网 发布:阿里云ace下线原因 编辑:程序博客网 时间:2024/06/08 16:41

在上一篇文章中我们提到了表入口模式,今天我们来讲行入口模式。

在《企业应用架构模式》中对行入口模式的定义是:充当数据源中单条记录入口的对象。每行一个实例。

与表入口模式一张表作为一个对象不同,行入口模式使用表中的一行数据作为一个对象。

行数据入口和活动记录模式的主要区别在于行数据入口仅包含数据库访问逻辑而没有领域逻辑,而活动记录则两者皆有。

具体实现如下代码所示:

入口类gameGateway.php

<?php require_once 'database.php';class GameGateway extends Database{public $instance;    private $_id;    private $_name;public $table = 'game';public function __construct($id, $name){$this->instance = self::getInstance();        $this->_id = $id;        $this->_name = $name;}    public function setId($id){        $this->_id = $id;    }    public function getId(){        return $this->_id;    }    public function setName($name){        $this->_name = $name;    }    public function getName(){        return $this->_name;    }    public function insert(){        $data = array(            'name' => $this->_name,            'id' => $this->_id        );        $sql = "INSERT INTO $this->table ";        $sql .= "(" . implode(",", array_keys($data)) . ")";        $sql .= " VALUES('" . implode("','", array_values($data)) . "')";        echo $sql;        return $this->instance->query($sql);    }    public function update() {        $data = array(            'id' => $this->_id,            'name' => $this->_name        );        $sql = "UPDATE $this->table SET ";        foreach ($data as $field => $value) {            $sql .= $field . " = '" . $value . "',";        }        $sql = substr($sql, 0, -1);        $sql .= " WHERE id = " . $this->_id;        return $this->instance->query($sql);    }    public static function load($rs) {        return new self(!empty($rs['id']) ? $rs['id'] : NULL, $rs['name']);    }}
查找类gameFinder.php

<?phprequire_once 'database.php';require_once 'gameGateway.php';class GameFinder extends Database{    public $instance;    public $table = 'game';    public function __construct(){        $this->instance = self::getInstance();    }    public function find($id) {        $sql = "SELECT * FROM $this->table WHERE id = " . $id;        $rs = $this->instance->query($sql)->fetch_assoc();        return GameGateway::load($rs);//返回行对象    }    public function findAll() {        $sql = "SELECT * FROM $this->table";        $rs = $this->instance->query($sql);        $result = array();        if (is_array($rs)) {            foreach ($rs as $row) {                $result[] = GameGateway::load($row);            }        }        return $result;    }}
测试代码index.php:

<?phprequire_once 'gameGateway.php';require_once 'gameFinder.php';//新增//$data = array('name' => 'new land');//$game = GameGateway::load($data);//var_dump($game->insert());//查询与更新//$finder = new GameFinder();//$game = $finder->find(3);//$game->setName('stormy night');//var_dump($game->update());

0 0
原创粉丝点击