Skip to content

Instantly share code, notes, and snippets.

@burzum
Created August 7, 2015 13:31
Show Gist options
  • Save burzum/3aaea92e13b70f66f514 to your computer and use it in GitHub Desktop.
Save burzum/3aaea92e13b70f66f514 to your computer and use it in GitHub Desktop.
CakePHP 3.0 DB Connection Prefix
<?php
namespace App\Model\Table;
use Cake\Core\Configure;
/**
* Database Prefix Trait for CakePHP 3.0
*
* @author Florian Krämer
* @license MIT
*/
trait DbPrefixTrait {
protected $_dbPrefix = '';
/**
* Getter and setter for the DB prefix
*/
public function dbPrefix($prefix = '') {
if (empty($prefix)) {
$connectionConfig = $this->connection()->config();
if (isset($connectionConfig['prefix'])) {
$prefix = $connectionConfig['prefix'];
}
}
if (!empty($prefix)) {
$this->_dbPrefix = $prefix;
}
return $this->_dbPrefix;
}
/**
* Returns the database table name or sets a new one
*
* @param string|null $table the new table name
* @return string
*/
public function table($table = null) {
if (!empty($table)) {
$table = $this->_dbPrefix . $table;
}
return parent::table($table);
}
}
@hasentopf
Copy link

Hi @burzum. Do you think, this still works in CakePHP 4? Thanks for your time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment