How to upgrade your plugins to new DAO classes

From Osclass
Jump to: navigation, search

In version 2.3 we introduced much better DAO (Data Access Object) classes. The new classes introduce an easier way to work with the database. Also, all* inputs are sanitized now, so you don't need to worry about insecure inputs anymore. Yay!

The best way to work with the new DAO is to create a new model (class) for your plugin. It required a little bit more of work, but is totally worth it: cleaner code, more secure, less spaghetti.

First take a look at our already upgrade plugins Cars Attributes RealState Attributes LOPD

Create a class and extend DAO

Your class starts with something like

class MyClass extends DAO {

No need to use getConnection() anymore

Since you're going to use a class now, the constructor of the class will take care of the connection to the data base.

Define a few params on the constructor

Your class constructor should look something like this

function __construct() {
    $this->setTableName('t_table') ;
    $this->setPrimaryKey('pk_i_id') ;  // Or whatever your primary key column is
    $this->setFields( array('pk_i_id', 'x_another_column', 'y_one_more_column') ) ;

Create methods as your wish

Create as much functions as you wish inside your class, to call then you only need to use this code:


Do NOT reinvent the wheel

Since you're extending DAO class, you have some functions ready to be used (if you declared which table and fields has the table on the constructor). If you want to update a field on your table, you don't need to create a new function for it, just call the update method:

MyClass::newInstance()->update($params, $conditions);

Same for findByPrimaryKey, listAll, insert, delete,... This class-thing start to be useful, isn't it?

New DAO methods

Previously, you had to deal with the database and your only tools were osc_dbExec, osc_dbFetchResult and osc_dbFetchResults. Now, you have all these methods, select, like, where, from, join, ... and all* the methods sanitize the input, so no more worries about slashes or SQL injections. The only method that does not sanitize is the query one, which allows you to perform complex queries on the database (we suggest you to try to avoid it at any cost, but that will not always be possible).

Please, take a look at the current plugins, you will find them very useful.