Search the Community
Showing results for tags 'factory pattern'.
-
Hi All, I've been interested in writing a PHP pdo configuration file so that I can include connections in various files on my site. While I was looking up some possible solutions I stumbled across an interesting post on stack overflow http://stackoverflow.com/questions/11369360/how-to-properly-set-up-a-pdo-connection The first responder suggested the code below. However, I don't understand how to access the connection and make query calls. I'm confused by how it's possible to return a variable name as an object { return new $name( $this->connection ) }. Also, If someone could explain what the author means by { $something = $factory->create('Something');}. Wouldn't the "Something" need to be a class? And how would that class get the db connection? All the best, Karma $provider = function() { $instance = new PDO('mysql:......;charset=utf8', 'username', 'password'); $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $instance; }; 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 ); } } $factory = new StructureFactory( $provider ); $something = $factory->create('Something'); $foobar = $factory->create('Foobar');
- 3 replies
-
- oop
- design patterns
-
(and 2 more)
Tagged with: