Using Eloquent outside of a Laravel project? – Me too!

Collector Class

class PHPDebugBarEloquentCollector extends \DebugBar\DataCollector\PDO\PDOCollector
{
    public function __construct()
    {
        parent::__construct();
        $this->addConnection($this->getTraceablePdo(), 'Eloquent PDO');
    }

    /**
     * @return Illuminate\Database\Capsule\Manager;
     */
    protected function getEloquentCapsule() {
        // ... Return your Illuminate\Database\Capsule\Manager instance here...
    }

    /**
     * @return PDO
     */
    protected function getEloquentPdo() {
        return $this->getEloquentCapsule()->getConnection()->getPdo();
    }

    /**
     * @return \DebugBar\DataCollector\PDO\TraceablePDO
     */
    protected function getTraceablePdo() {
        return new \DebugBar\DataCollector\PDO\TraceablePDO($this->getEloquentPdo());
    }

    // Override
    public function getName() {
        return "eloquent_pdo";
    }

    // Override
    public function getWidgets()
    {
        return array(
            "eloquent" => array(
                "icon"    => "inbox",
                "widget"  => "PhpDebugBar.Widgets.SQLQueriesWidget",
                "map"     => "eloquent_pdo",
                "default" => "[]"
            ),
            "eloquent:badge" => array(
                "map"     => "eloquent_pdo.nb_statements",
                "default" => 0
            )
        );
    }
}

Collector Registration

require_once '/path/to/PHPDebugBarEloquentCollector.php';

$debugbar = new DebugBar\StandardDebugBar();

$debugbar->addCollector(new PHPDebugBarEloquentCollector());

Result

Eloquent Tab in the PHP Debug Bar

Don’t Like Separate Tabs?

Multiple PDO objects can be merged into the default Database tab using this approach…

/* @var Illuminate\Database\Capsule\Manager $capsule */
/* @var Doctrine\ORM\EntityManager          $em */
/* @var DebugBar\StandardDebugBar           $debugbar */

$ormToPdo = [
    "Eloquent" => $capsule->getConnection()->getPdo(),
    "Doctrine" => $em->getConnection()->getWrappedConnection()
];

$collector = new \DebugBar\DataCollector\PDO\PDOCollector();

foreach($ormToPdo as $orm => $pdo) {
    $traceablePDO = new \DebugBar\DataCollector\PDO\TraceablePDO($pdo);
    $collector->addConnection($traceablePDO, $orm);
}

$debugbar->addCollector($collector);

Environment

This post was written for, and tested under, the following technologies…

  • PHP (~5.5)
  • PHP Debug Bar (~1.10)
  • Eloquent ORM (~5.1)
  • Doctrine (~2.0)

Doctrine 2 PDO Object

Where, oh where, is that pesky Doctrine 2 PDO object…Doctrine actually uses a base class called \Doctrine\DBAL\Driver\PDOConnection which extends the native ... Continue reading

WordPress Domain Changer 2.0

Published on November 19, 2014

Setting Up LiveReload With Jekyll

Published on January 18, 2014