在使用面向对象程序( 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被传递为附庸者?先谢谢你
发布于 2017-04-27 15:06:07
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返回一个PDO实例。$factory->create('Something');,您将得到一个Something类实例,其中注入了来自StructureFactory的PDO实例。但在我看来,StructureFactory::create()有点没用。如果给定的类有更多的构造函数参数怎么办?如何使用create()设置它们?
Normaly a getInstance()是enuff
public function getInstance()
{
if ( $this->connection === null )
{
$this->connection = call_user_func( $this->provider );
}
return $this->connection;
}我还没有完全读到链接,但是用我的版本,你可以在工厂外面做这个
$something = new Something($factory->getInstance(),$anotherParameter);https://stackoverflow.com/questions/43661304
复制相似问题