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:



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');



        $result = $closure();




        return $result;


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

Name: app-legacy
      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


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

    how to use this snippet with a real example?

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