DEV Community

loading...
Cover image for First steps from monolithic applications to microservices

First steps from monolithic applications to microservices

alexdodonov
PHP developer
Updated on ・2 min read

Best practises recommend us to start from monolithic applications and then step-by-step split into services and micriservices.

But what are these steps?

As for me I have descided that on the first step we shoud split our database in a set of smaller ones. Each database represents it's domain. And then make your application work with these databases.

Splitting databases into domain based parts

Modern frameworks provide necessary routine for this transformation.

For example in Mezon Framework:

// setup connections
Conf::addConnectionToConfig('db1', 'dsn-string', 'user', 'password');
Conf::addConnectionToConfig('db2', 'dsn-string', 'user', 'password');
Enter fullscreen mode Exit fullscreen mode

And somewere in your model class

$this->getConnection('db1')->select(/* select parameters */);
$this->getConnection('db2')->select(/* select parameters */);
Enter fullscreen mode Exit fullscreen mode

But you can ask me about comples SQL queries which operate with multiple tables, wich will be placed in different databases after our first step?

You can make the first step easier for you, because some database engines can use tables placed in different databases in one query. For example:

SELECT 
    mydatabase1.table1.field1, 
    mydatabse2.table2.field2
FROM 
   mydatabase1.table1
       INNER JOIN mydatabase2.table2
           ON mydatabase1.table1.field1 = mydatabase2.table2.field2
Enter fullscreen mode Exit fullscreen mode

And it will work for a while. But sooner or later you will have to split it into two queries:

// getting data from the first table of the first database
$result = $this->getConnection('db1')->select('select table1.field1 from table1 where ...');

$fields1 = Fetcher::getFields(result , 'field1');

// getting data from the second table of the second database and using data from the first query as a filter
$result = $this->getConnection('db2')->select('select table2.field2 from table2 where ... AND field2 in ('.implode(', ', fields1 ).')');
Enter fullscreen mode Exit fullscreen mode

Of course you will get overhead, but don't worry - it will be bigger when you will use microservices ))

Thats all for now. Thumbs up, subscribe, and comment - I will be glad to see any feedback.

Want more articles?

Subscribe me in Twitter

Or you can get access to my code on github

Discussion (0)