Some question about Database

How to configure the table prefix´╝čIs it support?



81.8k

You can override the getSource method to set the prefix:

<?php

class Users extends Phalcon\Mvc\Model
{

    public function getSource()
    {
        return 'my_' . 'users';
    }

}

Or, you can set a common base class to set the table prefix for all models:

<?php

class BaseModel extends Phalcon\Mvc\Model
{

    public function getSource()
    {
        return 'my_' . strtolower(get_class($this));
    }

}

And use it as base class for your models:

<?php

class Users extends BaseModel
{

}

Or in PHP 5.4 you can create a trait:

<?php

trait CustomPrefix
{
    public function getSource()
    {
        return 'my_' . strtolower(get_class($this));
    }
}

Then in your model:

<?php

class Users extends Phalcon\Mvc\Model
{
    use CustomPrefix;
}


6.8k

Thank you very much!



18.0k

What is the best practice to set DB tables prefix dynamically? For example set prefix through the controller.

Should I register some service that will do the job?

<?php
class Users extends Phalcon\Mvc\Model
{
  public function getSource()
  {
    $prefix = $this->customService->getPrefix();
    return $prefix . strtolower(get_class($this));
  }
}
edited May '15

This is the way i do in my project: config prefix in my config.ini file

$di->set('config', function() { .... }, true);

in my modelBase:

public function getSource() { $this->di->get('config')->database->prefix . 'table1'; }

other models all extends modelBase