Connect SilverStripe with another Database on the fly

Imagine you need to grab data from a legacy database, e.g. while migrating stuff to a new setup. How can you easily do that easily and elegantly?

Loz Calver posted a nice snippet where you can pass what you want to call using a closure:

<?php

​

public function __construct()

    {

        $config = Config::inst()->get(DB::class, 'legacy_config');

        DB::setConfig($config, 'legacy');

    }

​

    /**

     * @param callable $closure

     * @return mixed

     */

    protected function withLegacyDatabase(callable $closure)

    {

        $defaultConnection = DB::get_conn('default');

        $connection = DB::get_conn('legacy');

        DB::set_conn($connection);

​

        $result = $closure();

​

        DB::set_conn($defaultConnection);

​

        return $result;

    }

The config for the legacy database is plain yml and may look like:

---
Name: app-legacy
---
SilverStripe\ORM\DB:
  legacy_config:
      type: 'MySQLPDODatabase'
      server: 'localhost'
      username: 'root'
      password: 'root'
      database: 'dbname'

This works well with SQLQueries. Something like "Page::get()" might not work if the database or code bases are not compatible; also make sure to really get the data from the database, cause SilverStripe's ORM does lazy load where possible.

Rate this post

Post your comment

Comments

  • Daniel 03/12/2019 11:26am (4 years ago)

    Hi,
    how to use this snippet with a real example?

RSS feed for comments on this page | RSS feed for all comments