【问题标题】:PDO factory patternPDO工厂模式
【发布时间】:2017-09-25 10:57:38
【问题描述】:

在尝试使用 OOP 的 PHP 时,我在 Stackoverflow 上遇到了关于 PDO 的讨论,而不是使用全局变量和单例。我看到了这个问题 How to properly set up a PDO connection 展示了一种为 PDO 使用工厂模式和匿名函数的方法。我只是无法理解其中的一部分

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 作为参数传递?提前谢谢你

【问题讨论】:

  • $name 应该是 new 实例的类名。为什么这段代码没有很好的文档记录?
  • 当您知道变量$this->connection 不持有mysql 连接,而是持有PDO 实例时,也许会更清楚一点。
  • @JustOnUnderMillions something = $factory->create('Something'); 这就是它的使用方式。你能再解释一下吗?我无法理解如何在另一个类方法中使用 pdo

标签: php html mysql oop pdo


【解决方案1】:
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');
  • 正如您在帖子$provider 中的link_answer 中看到的那样,返回一个PDO 实例。
  • 如果您知道使用$factory->create('Something');,您将获得Something 的类实例,其中注入了来自StructureFactory 的PDO 实例。

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

通常getInstance() 是足够的

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

我没有完整阅读链接,但使用我的版本,您可以在工厂外执行此操作

 $something = new Something($factory->getInstance(),$anotherParameter);

【讨论】:

  • 哦,所以$something 可以是$anything = $factory->create('something');
  • @feetnappy 您可以随意调用/命名变量。但是如果你使用create()'something' 必须是一个声明的类。只用$factory->create('NonExistingClassName'); 测试它会得到Fatal Error
  • 我明白了,现在我明白了很多。该问题针对的是更有经验的程序员,而不是像我们这样的绝对初学者,所以感谢您回答这样的简单问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 2016-11-01
  • 1970-01-01
相关资源
最近更新 更多