Jump to content

karma

New Members
  • Posts

    2
  • Joined

  • Last visited

karma's Achievements

Newbie

Newbie (1/5)

0

Reputation

  1. Hi Requinix, Thank you for your thorough response-- it was very helpful. In the factory class, Something, is it necessary to typecast $pdo? Would you suggest this approach to creating DB connections, or is there something more effective? In the Something class I wanted to be able to make insert & select queries. Below is the code I was planning on using, but I wasn't sure if this was the right approach. Do you see any improvements that can be made? Thank you so much for your help! I really appreciate it. class Something { private $pdo = null; public function __construct(PDO $pdo) { $this->pdo = $pdo; } public function push($sql) { try { $stmt = $this->pdo->query($sql); return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $ex) { throw new Exception($ex->getMessage()); } } public function fetch($sql, $params = array()) { try { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $ex) { throw new Exception($ex->getMessage()); } } }
  2. 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');
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.