Using CakePHP without a database

If you solve a problem - blog about it, chances are that somebody, somewhere, is already facing the same problem.

We recently programmed a CakePHP app which relies solely on remote server talking Saleforce API for all data operations. The first challenge that we faced was how to prevent CakePHP from insisting on a database connection. The solution was simple enough and I never gave it much thought till the same question was brought up by more than one person on the CakePHP list. The solution involves creating a minimal dbo source file.

Without much fanfare - here are the steps to trick CakePHP into believing that there is a database even when there is none!

#1 Create a file called dbo_my_dbo_source.php in the directory app/models/datasources/dbo/
Put the following code in this newly created file

PHP:
  1. class DboMyDboSource extends DboSource
  2. {
  3.     function connect()
  4.     {
  5.         $this->connected = true;
  6.         return $this->connected;
  7.     }
  8.  
  9.     function disconnect()
  10.     {
  11.         $this->connected = false;
  12.         return !$this->connected;
  13.     }
  14.  
  15.  
  16. }

#2 Next we need to tell our app to use this dbo source by default - for that edit database.php and as driver put 'my_dbo_source' this is set to 'mysql' by default

PHP:
  1. 'driver' => 'my_dbo_source'

Your installation will now report that "Cake is able to connect to the database."

#3 Now make sure your models set useTable to false

PHP:
  1. $useTable = false;

That is it! you are free to take this forward as you wish. In our case we abstracted a lot of the functionality of the API into the dbo source and the app model. This made the models and controllers almost indistinguishable from the regular CakePHP ones - so at a future date if we want to shift to another datasource it will a *piece of cake*

Thanks to Amit Badkas who wrote the code for this.


About this entry