jamis0n
jamis0n

Reputation: 3820

Setup CakePHP with an existing Database

I have a MySQL server database currently setup which has a few simple tables to track orders, such as tblOrders, tblUsers, tblProducts.

Although I have a website working with it fine now, I'd like to setup CakePHP to act as the server side framework for handling interaction with the database rather than using hand written queries in my PHP pages.

Is there a simple way to setup CakePHP with my existing Database/tables?

If I understand correctly, I will have a main MyApplication class which Extends Controller, as well as Order, User, Product, (... other tables) classes which each extend the MyApplication class.

It looks like the REST guide uses a method in the configuration file called Router::mapResources('recipes');. Will this create the controllers for each table with the default methods to use for REST?

I.e., in the /app/config/routes.php configuration file:

// /app/config/routes.php
Router::mapResources('tblOrders');
Router::mapResources('tblUsers');
Router::mapResources('tblProducts');

// /app/config/database.php
<?php
class DATABASE_CONFIG {
    public $default = array(
        'datasource'  => 'Database/myStoreDB',
        'persistent'  => false,
        'host'        => 'localhost',
        'login'       => 'admin_user',
        'password'    => 'c4k3roxx!',
        'database'    => 'main_db',
        'prefix'      => ''
    );
}

Upvotes: 0

Views: 1594

Answers (1)

Ben Graham
Ben Graham

Reputation: 2099

If you want Model, Controller and View code created for you, you're looking for baking.

Cake expects your database tables to follow a naming convention. I'm not sure how the bake will go because your tables don't match this convention. You may need to create your model classes by hand and specify the useTable attribute on each class. For example:

<?php
class Order extends AppModel {
    public $useTable = 'tblOrders';
}

Once this is done, I expect the baking of Controllers and Views should work as normal. Note that with mapResources you still need Controller code. That function just generates routes.

If Cake is the only thing that will be touching this database, I recommend renaming tables and columns in line with the conventions it expects.

Upvotes: 3

Related Questions