Skip to content

Instantly share code, notes, and snippets.

@ceceprawiro
Created April 12, 2015 04:08
Show Gist options
  • Save ceceprawiro/6ab5c270dc06210df62d to your computer and use it in GitHub Desktop.
Save ceceprawiro/6ab5c270dc06210df62d to your computer and use it in GitHub Desktop.
Library CI 3 untuk Eloquent
<?php defined('BASEPATH') or die();
/**
* Filename: application/libraries/Orm.php
*
* composer.json :
* {
* "require": {
* "illuminate/database": "5.0.27",
* "illuminate/events": "5.0.26",
* "illuminate/pagination": "5.0.26",
* "twig/twig": "1.18.0"
* },
* "config": {
* "vendor-dir": "application/vendor"
* }
* }
*
* https://github.com/ceceprawiro/codeigniter-twig
*/
class Orm
{
/**
* Reference to code CodeIgniter instance.
* @var codeIgniter object
*/
private $_CI;
public function __construct()
{
// Get reference to CodeIgniter Instance
$this->_CI =& get_instance();
// Get database configuration
$db = (array) $this->_CI->db;
/**
* Create a new instance of the database component and add a new connection
*/
$capsule = new Illuminate\Database\Capsule\Manager;
$capsule->addConnection(array(
'driver' => in_array($db['dbdriver'], ['mysqli', 'mysql']) ? 'mysql' : $db['dbdriver'],
'host' => $db['hostname'],
'database' => $db['database'],
'username' => $db['username'],
'password' => $db['password'],
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => $db['dbprefix'],
));
$capsule->setAsGlobal();
$capsule->bootEloquent();
/**
* Get query log
* Be careful!
* Query log (in memory) is eating all your memory when you execute such a large # of queries.
*
* Turn off/on query logging:
* DB::connection()->disableQueryLog();
* DB::connection()->enableQueryLog();
*/
$events = new Illuminate\Events\Dispatcher;
$events->listen('illuminate.query', function($query, $bindings, $time, $name)
{
// Format binding data for sql insertion
foreach ($bindings as $i => $binding)
{
if ($binding instanceof \DateTime)
{
$bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
}
else if (is_string($binding))
{
$bindings[$i] = "'$binding'";
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $query);
$query = vsprintf($query, $bindings);
// Add it into CodeIgniter
$db =& get_instance()->db;
$db->query_times[] = $time;
$db->queries[] = $query;
});
$capsule->setEventDispatcher($events);
/**
* Enable pagination
*/
$capsule->getContainer()->bind('paginator', function() {
// View initialization
$twig = $this->twig;
return new Illuminate\Pagination\Factory(
// Initialize and setup Request
Illuminate\Http\Request::createFromGlobals(),
// Get ViewFactory instance
$twig->display(),
// Initialize Translator
new Symfony\Component\Translation\Translator('en')
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment