Reuse Business Logic between Web and API

Posted by fesja on Programmers See other posts from Programmers or by fesja
Published on 2012-12-13T00:48:24Z Indexed on 2012/12/13 5:16 UTC
Read the original article Hit count: 355

We have a website and two mobile apps that connect through an API. All the platforms do the exactly same things. Right now the structure is the following:

  • Website. It manages models, controllers, views for the website. It also executes all background tasks. So if a user create a place, everything is executed in this code.
  • API. It manages models, controllers and return a JSON. If a user creates a place on the mobile app, the place is created here. After, we add a background task to update other fields. This background task is executed by the Website.

We are redoing everything, so it's time to improve the approach. Which is the best way to reuse the business logic so I only need to code the insert/edit/delete of the place & other actions related in just one place?

Is a service oriented approach a good idea? For example:

  • Service. It has the models and gets, adds, updates and deletes info from the DB.
  • Website. It send the info to the service, and it renders HTML.
  • API. It sends info to the service, and it returns JSON.

Some problems I have found:

  • More initial work? Not sure..
  • It can work slower. Any experience?

The benefits:

  • We only have the business logic in one place, both for web and api.
  • It's easier to scale. We can put each piece on different servers.

Other solutions

  • Duplicate the code and be careful not to forget anything (do tests!)
  • DUplicate some code but execute background tasks that updates the related fields and executes other things (emails, indexing...)

A "small" detail is we are 1.3 person in backend, for now ;)

© Programmers or respective owner

Related posts about architecture

Related posts about web-applications