首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PDO工厂模式

PDO工厂模式
EN

Stack Overflow用户
提问于 2017-04-27 14:56:11
回答 1查看 797关注 0票数 1

在使用面向对象程序( OOP )进行PHP测试时,我讨论了Stackoverflow关于PDO的问题,而不使用全局和单例。我看到了这个问题How to properly set up a PDO connection,它展示了一种为PDO使用工厂模式和匿名函数的方法。我只是很难理解其中一个部分

代码语言:javascript
复制
class StructureFactory
{
    protected $provider = null;
    protected $connection = null;

    public function __construct( callable $provider )
    {
        $this->provider = $provider;
    }

    public function create( $name)
    {
        if ( $this->connection === null )
        {
            $this->connection = call_user_func( $this->provider );
        }
        return new $name( $this->connection );
    }
}

我不明白的是

return new $name( $this->connection );

$name是回调吗?还是一个物体?为什么$this->conection被传递为附庸者?先谢谢你

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-27 15:06:07

代码语言:javascript
复制
class Something {
   protected $PDO;
   public function __construct(\PDO $PDO){
      //after this, you can use the PDO instance in your class.
      $this->PDO = $PDO;
   }
}

//get an class instance that holds an refer to the PDO class
$something = $factory->create('Something');
  • 正如您在link_answer中看到的,在post中,$provider返回一个PDO实例。
  • 如果您知道使用$factory->create('Something');,您将得到一个Something类实例,其中注入了来自StructureFactory的PDO实例。

但在我看来,StructureFactory::create()有点没用。如果给定的类有更多的构造函数参数怎么办?如何使用create()设置它们?

Normaly a getInstance()是enuff

代码语言:javascript
复制
public function getInstance()
{
    if ( $this->connection === null )
    {
        $this->connection = call_user_func( $this->provider );
    }
    return $this->connection;
}

我还没有完全读到链接,但是用我的版本,你可以在工厂外面做这个

代码语言:javascript
复制
 $something = new Something($factory->getInstance(),$anotherParameter);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43661304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档