Created
December 8, 2012 02:31
-
-
Save dhrrgn/4238278 to your computer and use it in GitHub Desktop.
The Db file for easy use of the Database package from L4 outside of L4.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Database\Connectors\ConnectionFactory; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Database\ConnectionResolver; | |
use Illuminate\Database\DatabaseManager; | |
class Db { | |
private static $resolver = null; | |
private static $factory = null; | |
private static $modelInitialized = false; | |
public static function makeConnection($name, array $config, $default = false) { | |
self::setupResolverAndFactory(); | |
self::$resolver->addConnection($name, self::$factory->make($config)); | |
if ($default) { | |
self::$resolver->setDefaultConnection($name); | |
} | |
if ( ! self::$modelInitialized) { | |
Model::setConnectionResolver(self::$resolver); | |
self::$modelInitialized = true; | |
} | |
} | |
public static function __callStatic($method, $parameters) { | |
return call_user_func_array(array(self::$resolver->connection(), $method), $parameters); | |
} | |
private static function setupResolverAndFactory() { | |
if (is_null(self::$resolver)) { | |
self::$resolver = new ConnectionResolver; | |
} | |
if (is_null(self::$factory)) { | |
self::$factory = new ConnectionFactory; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<pre><?php | |
require 'vendor/autoload.php'; | |
Db::makeConnection('main', [ | |
'driver' => 'mysql', | |
'host' => 'localhost', | |
'database' => 'test', | |
'username' => 'root', | |
'password' => 'root', | |
'collation' => 'utf8_general_ci', | |
'prefix' => '', | |
], true); | |
var_dump(Db::table('foo')->select('*')->get()); | |
/* | |
Result: | |
array(2) { | |
[0]=> | |
array(2) { | |
["id"]=> | |
string(1) "1" | |
["name"]=> | |
string(3) "Dan" | |
} | |
[1]=> | |
array(2) { | |
["id"]=> | |
string(1) "2" | |
["name"]=> | |
string(3) "Joe" | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment