在尝试使用OOP进行PHP时,我讨论了关于PDO的Stackoverflow,而没有使用全局变量和单例。我看到了这个问题 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
作为参数传递?提前谢谢你
答案 0 :(得分:0)
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()
设置它们?
Normaly 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);