Showing posts with label ConnectionManager. Show all posts
Showing posts with label ConnectionManager. Show all posts

Friday, April 20, 2018

Extending from Laravel 5 core - SqlServerConnection | Extending The Connection Class In Laravel

The first thing the ConnectionFactory::createConnection() method does is to check if the db.connection.{$driver} alias is bound, and if so, it returns that connection object. If it is not bound, it returns the base connection object (Illuminate\Database\MySqlServerConnection for the mysql driver)
Therefore, all you need to do to use your own custom connection is to bind the db.connection.mysql alias to your custom MySqlServerConnection class
You can create a new service provider in which to do this, or you can just add the line to your existing AppServiceProvider
<?php
namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
    }

    public function register() {
        $this->app->bind('db.connection.mysql', \App\Database\MySqlConnection::class);
    }
}
Remember that there may be two methods in any ServiceProvider, first call "register" method of each ServiceProvider listed and after that "boot" method called each ServiceProvider listed in "config/app.php" in providers section.
<?php
return [
    'providers' => [
        App\Providers\EventServiceProvider::class,
        App\Providers\AppServiceProvider::class
    ]
];
You have to create a MySQL connection class \App\Database\MySqlConnection
<?php
namespace App\Database;

use Illuminate\Database\MySqlConnection as ParentMySqlConnection;

class MySqlConnection extends ParentMySqlConnection {
    public function select($query, $bindings = [], $useReadPdo = true) {
        return parent::select($query, $bindings, $useReadPdo);
    }
}
So its completed, MySqlConnection is now extended with our own connection class.
So you can now anything do with your custom connection class.

Thursday, August 8, 2013

CakePHP: Accessing database.php values

$fields = get_class_vars('DATABASE_CONFIG')

print_r($fields['default']);
or you can use; 
 
App::Import('ConnectionManager');
$ds = ConnectionManager::getDataSource('default');
$dsc = $ds->config;

print_r($dsc);
Will output like this:
Array
(
    [persistent] => 
    [host] => localhost
    [login] => root
    [password] => 
    [database] => db_name
    [port] => 3306
    [driver] => mysql
    [prefix] => 
)