Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Handling Multiple Database

Posted in Teknologi, Tutorial PHP, Zend Framework, Zend Framework 2 by samsonasik on June 6, 2012

Pada skala aplikasi yang besar, kita sering menjumpai aplikasi yang menggunakan beberapa database sekaligus. Zend Framework 2 memfasilitasi kebutuhan ini dengan settingan yang super flexible. Cukup memanggil array konfigurasi, tak perlu pusing memikirkan sintax sql yang mungkin berbeda di teknologi database lain, cukup configure, and run!


Anggap saja, kita ingin membangun aplikasi dengan 2 database, yaitu Postgresql, dan Mysql, maka yang kita perlukan pertama adalah setting konfigurasi global di Zend Framework kita, seperti contoh berikut :

/**
 * Global Configuration Override
 *
 * You can use this file for overridding configuration values from modules, etc.  
 * You would place values in here that are agnostic to the environment and not 
 * sensitive to security. 
 *
 * @NOTE: In practice, this file will typically be INCLUDED in your source 
 * control, so do not include passwords or other sensitive information in this 
 * file.
 */

return array(
    // ...
    'db-pgsql' => array(
        'driver' => 'pdo_pgsql',
        'dbname' => 'zf2',
        'hostname' => 'localhost',
        'username' => 'developer',
        'password' => '123456'
    ),
    
    'db-mysql' => array(
        'driver' => 'pdo_mysql',
        'dbname' => 'zf2',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => ''
    ),
);

// file location : ZendSkeletonApplication\config\autoload\global.php

Kalau sudah, kita setting di module Application\Module.php :

//---------------------------------
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                
                'db-adapter-postgresql' =>  function($sm) {
                    $config = $sm->get('config');
                    $config = $config['db-pgsql'];
                    $dbAdapter = new DbAdapter($config);
                    return $dbAdapter;
                },
                
                'db-adapter-mysql' =>  function($sm) {
                    $config = $sm->get('config');
                    $config = $config['db-mysql'];
                    $dbAdapter = new DbAdapter($config);
                    return $dbAdapter;
                },
                
            ),
        );
    }
//---------------------------------

Nah, misalkan di module tertentu kita butuhkan, kita tinggal tambahkan di Module.php module tertentu tersebut :

//-------------------------
public function getServiceConfig()
    {
        return array(
            'factories' => array(
                
                'sample-table-pg' =>  function($sm) {
                    $dbAdapter = $sm->get('db-adapter-postgresql');
                    $table = new SampleTable($dbAdapter);
                    return $table;
                },
                
                'sample-table-my' =>  function($sm) {
                    $dbAdapter = $sm->get('db-adapter-mysql');
                    $table = new SampleTable($dbAdapter);
                    return $table;
                },
                
            ),
        );
    }
//----------------------

Untuk memanggil di Controller ? tinggal dipanggil seperti berikut :

//----------------------
    public function getSampleTable()
    {
        if (!$this->sampleTable) {
            $sm = $this->getServiceLocator();
            $this->sampleTable = $sm->get('sample-table-my'); 
            //change to "sample-table-pg" if need pgsql, just it 😉
        }
        return $this->sampleTable;
    }
//----------------------

Done !

Referensi :
http://akrabat.com/zend-framework-2-tutorial/
http://blog.evan.pro/sharing-a-database-connection-across-modules-in-zend-framework-2

22 Responses

Subscribe to comments with RSS.

  1. Arie W. Subagja said, on June 6, 2012 at 3:57 pm

    mangstab! makin sini makin keren aja neh tulisannya (apa karena baru merit? jadi makin tokcer? haha)
    BTW, di Kohana bisa lebih gampang lagi loh!

    misal: http://pastie.org/4036706

    Sayangnya, di Kohana, baru support mysql aja, ada juga sih yg nulis driver buat postgres.

  2. samsonasik said, on June 6, 2012 at 8:54 pm

    haha, cuma nulis2 yang sebagai catatan aja kok mas arie, minimal bermanfaat buat diri sendiri, hehe.
    di Framework lain, memang lebih simple. di Zend Framework, emang sedikit “overengineered” , hehe.

  3. alif akbar fitrawan said, on September 9, 2012 at 3:50 pm

    bang
    saya baru belajar zend framework
    saya masih belum bisa memasukkan value yg ada pada field ke database

    //ini formnya
    class Application_Form_Album extends Zend_Form
    {
    public function init()
    {
    $this->setName(‘album’);

    $id = new Zend_Form_Element_Hidden(‘id’);
    $id->addFilter(‘Int’);

    $artist = new Zend_Form_Element_Text(‘artist’);
    $artist->setLabel(‘Artist’)
    ->setRequired(true)
    ->addFilter(‘StripTags’)
    ->addFilter(‘StringTrim’)
    ->addValidator(‘NotEmpty’);

    $title = new Zend_Form_Element_Text(‘title’);
    $title->setLabel(‘Title’)
    ->setRequired(true)
    ->addFilter(‘StripTags’)
    ->addFilter(‘StringTrim’)
    ->addValidator(‘NotEmpty’);

    $jenis_kelamin = new Zend_Form_Element_Text(‘jenis_kelamin’);
    $jenis_kelamin->setLabel(‘Jenis_Kelamin’)
    ->setRequired(true)
    ->addFilter(‘StripTags’)
    ->addFilter(‘StringTrim’)
    ->addValidator(‘NotEmpty’);

    $agama = new Zend_Form_Element_Text(‘agama’);
    $agama->setLabel(‘Agama’)
    ->setRequired(true)
    ->addFilter(‘StripTags’)
    ->addFilter(‘StringTrim’)
    ->addValidator(‘NotEmpty’);

    $submit = new Zend_Form_Element_Submit(‘submit’);
    $submit->setAttrib(‘id’, ‘submitbutton’);

    $this->addElements(array($id, $artist, $title, $jenis_kelamin, $agama, $submit));
    }
    }

    ini di indexcontrollernya :

    public function addAction()
    {
    $form = new Application_Form_Album();
    $form->submit->setLabel(‘Add’);
    $this->view->form = $form;

    if ($this->getRequest()->isPost()) {
    $formData = $this->getRequest()->getPost();
    if ($form->isValid($formData)) {
    $artist = $form->getValue(‘artist’);
    $title = $form->getValue(‘title’);
    $jenis_kelamin = $form->getValue(‘jenis_kelamin’);
    $agama = $form->getValue(‘agama’);
    $albums = new Application_Model_DbTable_Albums();
    $albums->addAlbum($artist, $title, $jenis_kelamin, $agama);

    $this->_helper->redirector(‘index’);
    } else {
    $form->populate($formData);
    }
    }

    }

  4. alif akbar fitrawan said, on September 10, 2012 at 11:20 am

    iya bang
    ternyata ini yang kurang
    fungsi tambahnya

    public function addAlbum($id, $artist, $title, $jenis_kelamin, $agama)
    {
    $data = array(
    ‘id’ => $id,
    ‘artist’ => $artist,
    ‘title’ => $title,
    ‘jenis_kelamin’ => $jenis_kelamin,
    ‘agama’ => $agama,
    );
    $this->insert($data);
    }

    maklum baru belajar OOP,
    lain kali kalo nemuin kesulitan
    bolehkan bertanya ?

  5. alif akbar fitrawan said, on September 10, 2012 at 1:54 pm

    haha,
    tanya bang arie aja klo gitu

  6. alif akbar fitrawan said, on September 12, 2012 at 9:57 pm

    bang kalo ada error gini gimana ?

    “Notice: Zend_Loader::Zend_Loader::registerAutoload is deprecated as of 1.8.0 and will be removed with 2.0.0; use Zend_Loader_Autoloader instead in C:\ZendFramework\library\Zend\Loader.php on line 266

    Fatal error: Uncaught exception ‘Zend_Config_Exception’ with message ‘parse_ini_file(C:/xampp/configuration/config.ini) [function.parse-ini-file]: failed to open stream: No such file or directory’ in C:\ZendFramework\library\Zend\Config\Ini.php:182 Stack trace: #0 C:\ZendFramework\library\Zend\Config\Ini.php(202): Zend_Config_Ini->_parseIniFile(‘C:/xampp/config…’) #1 C:\ZendFramework\library\Zend\Config\Ini.php(126): Zend_Config_Ini->_loadIniFile(‘C:/xampp/config…’) #2 C:\xampp\htdocs\part3\application\bootstrap.php(34): Zend_Config_Ini->__construct(‘C:/xampp/config…’, ‘main’) #3 C:\xampp\htdocs\part3\public\index.php(3): require(‘C:\xampp\htdocs…’) #4 {main} thrown in C:\ZendFramework\library\Zend\Config\Ini.php on line 182″

    • Arie W. Subagja said, on September 12, 2012 at 10:02 pm

      Dari error itu sih udah kliatan, kita di kasih tau supaya jangan pake `Zend_Loader::registerAutoload()`, tapi disuruh pake `Zend_Loader_Autoloader` *ngacirr*

  7. alif akbar fitrawan said, on September 12, 2012 at 10:22 pm

    bang arie
    setelah saya ganti $autoloader = Zend_Loader_Autoloader::getInstance();
    menjadi $autoloader = Zend_Loader_Autoloader;

    muncul pesan gini ”
    Notice: Zend_Loader::Zend_Loader::registerAutoload is deprecated as of 1.8.0 and will be removed with 2.0.0; use Zend_Loader_Autoloader instead in C:\ZendFramework\library\Zend\Loader.php on line 266

    Notice: Use of undefined constant Zend_Loader_Autoloader – assumed ‘Zend_Loader_Autoloader’ in C:\ZendFramework\library\Zend\Loader.php on line 268

    Fatal error: Call to a member function setFallbackAutoloader() on a non-object in C:\ZendFramework\library\Zend\Loader.php on line 269″

    mohon bimbingannya
    maklum baru belajar zend dan OOP

  8. samsonasik said, on September 12, 2012 at 10:52 pm

    coba :


    defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

    defined('LIBRARY_PATH')
    || define('LIBRARY_PATH', realpath(dirname(__FILE__) . '/../library'));

    set_include_path(implode(PATH_SEPARATOR, array(realpath(APPLICATION_PATH . '/../library'),get_include_path())));
    require_once 'Zend/Loader/Autoloader.php';
    $autoloader = Zend_Loader_Autoloader::getInstance();

    Untuk yang error parse ini file, pastikan path nya bener, lihat APPLICATION_PATH konstanta di atas :
    misal :

    defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

    $fileconfig = APPLICATION_PATH.'/configs/application.ini';
    $application = new Zend_Application(
    APPLICATION_ENV,
    $fileconfig
    );
    $application->bootstrap()
    ->run();

    Contoh ZF 1.10.3 siap pakai ada bisa didownload di sini :
    http://www.4shared.com/file/nWGP3GEf/zfmodular_sample.html
    atau bisa list beberapa contoh ada di sini :
    https://samsonasik.wordpress.com/download/

  9. alif akbar fitrawan said, on September 12, 2012 at 11:04 pm

    makasih makasih bang
    saya download yg 1.12

    kemudian nyarinyari referensi project zend yg sudah aja
    trus nemu contoh project zend sederhana yg ada di http://zfsite.andreinikolov.com/,
    saya download.
    nah, mungkin beda versi ya bang, makanya muncul error seperti itu

    susah ya bang nyari tutorial zend yg berbahasa indonesia

    trus bedanya dengan yang zf 2 apa bang dgn versi 1.12 ?

  10. samsonasik said, on September 12, 2012 at 11:47 pm

    autoloader dari versi 1.8 sampai 1.11 sama.
    untuk 1.12 ada tambahan class-map-based autoloading.

    versi 2 full php 5.3 ke atas, module based, menggunakan namespace, closure, late static binding, dll.

  11. teste said, on October 15, 2012 at 9:11 am

    hey add…
    use Zend\Db\Adapter\Adapter as DbAdapter;

  12. Alif Akbar Fitrawan said, on November 7, 2012 at 5:54 am

    mas samsonasik
    mau tanya, membuat sms gateway dengan zend framework apakah bisa ya ?

  13. samsonasik said, on November 7, 2012 at 1:24 pm

    jadikan zf sbg service requester aja. mas bs pakai gammu atau yg lain.

  14. Chick leq said, on November 15, 2012 at 3:07 am

    I was looking for at least 4 hours, until I get the answer from your blog on how to use multiple databases for a module on ZF2 and you answer it!
    You should translate it in English!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: