We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Some question about Database

How to configure the table prefix?Is it support?



98.9k

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;
}


15.6k

Thank you very much!



29.4k

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