PDO Plugin

23 views
Skip to first unread message

Chris Boden

unread,
Mar 26, 2011, 7:20:46 PM3/26/11
to Alloy
For anyone who isn't using Spot/Doctrine with their Alloy project,
I've written a simple PDO Plugin. The file goes in /app/Plugin/DB/
Plugin.php

I played around with containing the PDO object and referencing it
through __call() in order to tie in to some Alloy debug features but
ran into a couple issues and settled for accessing the PDO object
directly. I may take another crack at it later.

Usage:
$db = Kernel()->db();
$db->pdo_method_call();

FIle contents:
<?php
namespace Plugin\DB;
use Alloy;
use PDO;

class Plugin extends PDO {
public function __construct() {
$k = Kernel();

parent::__construct($k->config('database.master.adapter') .
':dbname=' . $k->config('database.master.database') . ';host=' . $k-
>config('database.master.host'), $k-
>config('database.master.username'), $k-
>config('database.master.password'));

$options = $k->config('database.master.options');
foreach ($options as $attribute => $value) {
$this->setAttribute($attribute, $value);
}

$k->addMethod('db', $this);
}

public function __invoke() {
return $this;
}
}

Vance Lucas

unread,
Mar 28, 2011, 10:46:27 AM3/28/11
to allo...@googlegroups.com
Chris,

I like the plugin, but you may want to instantiate a PDO instance inside the plugin instead of directly extending PDO. The reason is that it should be in a try/catch block, because PDO reveals connection details if if cannot connect as part of the default exception message printing in PHP.

Something like this:

<?php
namespace Plugin\DB;
use Alloy;

class Plugin {
    protected $_pdo;

    public function __construct() {
       $k = Kernel();
       $k->addMethod('db', array($this, 'pdoInstance'));
    }


    public function pdoInstance() {
      if(!$this->_pdo) {
        $dbcfg = $k->config('database.master');

        // DSN String
        $dsn = $dbcfg['adapter'] . ':dbname=' . $dbcfg['database'] . ';host=' . $dbcfg['host'];

        // Use try/catch so credentials will never be revealed
        try {
          $this->_pdo = new \PDO($dsn, $dbcfg['username'], $dbcfg['password'], $dbcfg['options']);
        } catch(\PDOException $e) {
          throw new \Exception("Unable to connect to database: " . $e->getMessage());
        }
      }
      return $this->_pdo;
   }
}

--
Vance Lucas  
http://vancelucas.com

Chris Boden

unread,
Mar 28, 2011, 11:05:16 AM3/28/11
to Alloy
Good catch. Thanks Vance.
> Vance Lucashttp://vancelucas.com
Reply all
Reply to author
Forward
0 new messages