PHP DataMapper模式:我的类需要一个PDO的实例,我想把它包装在一个Db类中 [英] PHP DataMapper pattern: My class needs an instance of PDO, I want to wrap it inside a Db class

查看:136
本文介绍了PHP DataMapper模式:我的类需要一个PDO的实例,我想把它包装在一个Db类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我有的:

  class Entry 
{
public $ id;
public $ name;
public $ seoName;
public $ timeCreated;

public function someFunction()
{

}

}

class EntryMapper
{
protected $ db;

public function __construct(PDO $ db)
{
$ this-> db = $ db;
}

public function saveEntry(Entry& $ entry)
{
if($ entry-> id){
$ sql = ;
}
else {
$ sql =INSERT INTO tbl_entry(name,seo_name,time_created)VALUES(:name,:seo_name,,time_created);
$ stmt = $ this-> db-> prepare($ sql);
$ stmt-> bindParam(name,$ entry-> name);
$ stmt-> bindParam(seo_name,$ entry-> seoName);
$ stmt-> bindParam(time_created,$ entry-> timeCreated);
$ stmt-> execute();
$ entry-> id = $ this-> db-> lastInsertId();
}
}

}

这里是我在我的视图文件中使用它(目前只是测试插入命令):

  $ entry = new Entry(); 

$ entry-> name =KartonažaadGradačac;
$ entry-> seoName =kartonaza-ad-gradacac;
$ entry-> timeCreated = date(Y-m-d H:i:s);

$ entryMapper = new EntryMapper(new PDO(mysql:host = .....));
$ entryMapper-> saveEntry($ entry);

我想要这样的$ entryMapper行:

  $ entryMapper = new EntryMapper(new Database()); 

意思是我应该有一个单独的类Database.php,在那里我将建立连接。



我尝试过,但是由于我的类EntryMapper.php需要直接的PDO实例,所以我收到一个错误。我试过数据库从PDO扩展,但也引起错误,表示PDO构造函数未在EntryMapper中调用



任何想法?


$ b $编辑:如果你看到任何代码耦合或类似的迹象,让我知道,因为我想学习正确编码。非常感谢!

解决方案

这是我终于解决了(如果一个更好的实现出现,我会确定重新编码) 。这是在这里接受的答案下的解决方案的实现:数据库连接的全局或单例? / a>



我的ConnFactory.php

  include('config /config.php'); 

class ConnFactory
{
private static $ factory;

public static function getFactory()
{
if(!self :: $ factory){
self :: $ factory = new ConnFactory();
return self :: $ factory;
}

}

private $ db;

public function pdo()
{
if(!$ this-> db){
$ options = array(
PDO :: ATTR_PERSISTENT => true,
PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION,
PDO :: ATTR_EMULATE_PREPARES => false,
PDO :: MYSQL_ATTR_INIT_COMMAND =>SET NAMES utf8
);
$ this-> db = new PDO(mysql:host =。DB_HOST。; port =DB_PORT; dbname =DB_SCHEMA,DB_USER,DB_PASS,$ options);
}
return $ this-> db;
}

}

我的视图/ html文件中的用法(只是插入功能的测试):

  $ entry = new Entry(); 
$ entry-> name =KartonažaadGradačac;
$ entry-> seoName =kartonaza-ad-gradacac;
$ entry-> timeCreated = date(Y-m-d H:i:s);

$ entryMapper = new EntryMapper(ConnFactory :: getFactory() - > pdo());
$ entryMapper-> saveEntry($ entry);


here's what I have:

class Entry
{
    public $id;
    public $name;
    public $seoName;
    public $timeCreated;

    public function someFunction()
    {

    }

}

class EntryMapper
{
    protected $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    public function saveEntry(Entry &$entry)
    {
        if($entry->id){
            $sql = "";
    }
    else {
        $sql = "INSERT INTO tbl_entry (name, seo_name, time_created) VALUES (:name, :seo_name, :time_created)";
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam("name", $entry->name);
        $stmt->bindParam("seo_name", $entry->seoName);
        $stmt->bindParam("time_created", $entry->timeCreated);
        $stmt->execute();
        $entry->id = $this->db->lastInsertId();
        }
    }

}

Now, here's how I use it in my view file (currently just testing insert command):

$entry = new Entry();

$entry->name = "Kartonaža ad Gradačac";
$entry->seoName = "kartonaza-ad-gradacac";
$entry->timeCreated = date("Y-m-d H:i:s");

$entryMapper = new EntryMapper(new PDO("mysql:host=....."));
$entryMapper->saveEntry($entry);

I want to have the $entryMapper line like this:

$entryMapper = new EntryMapper(new Database());

meaning I should have a separate class Database.php where I would establish the connection.

I tried that, but since my class EntryMapper.php needs an instance of PDO directly, i'm getting an error. I have tried Database extend from PDO but that also raises error saying that PDO constructor was not called in EntryMapper

Any thoughts?

EDIT: if you see any signs of code coupling or similar, let me know because I want to learn to code properly. Thank you very much!

解决方案

This is how I finally solved it (if a better implementation arises, I will for sure recode). It is an implementation of solution under the accepted answer here: Global or Singleton for database connection?

My ConnFactory.php

include('config/config.php');

class ConnFactory
{
    private static $factory;

    public static function getFactory()
    {
        if(!self::$factory){
            self::$factory = new ConnFactory();
            return self::$factory;
        }

    }

    private $db;

public function pdo()
{
    if(!$this->db){
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
        );
        $this->db = new PDO("mysql:host=".DB_HOST.";port=".DB_PORT.";dbname=".DB_SCHEMA."", DB_USER, DB_PASS, $options);
    }
    return $this->db;
    }

}

Usage in my view/html file (just a test of insert functionalty):

$entry = new Entry();
$entry->name = "Kartonaža ad Gradačac";
$entry->seoName = "kartonaza-ad-gradacac";
$entry->timeCreated = date("Y-m-d H:i:s");

$entryMapper = new EntryMapper(ConnFactory::getFactory()->pdo());
$entryMapper->saveEntry($entry);

这篇关于PHP DataMapper模式:我的类需要一个PDO的实例,我想把它包装在一个Db类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆