use override table trait to allow for easily customzing table a controller uses

This commit is contained in:
2025-03-29 00:52:38 -07:00
parent b868cc11fb
commit 8229722779
7 changed files with 103 additions and 83 deletions

View File

@@ -0,0 +1,55 @@
<?php
namespace CakeProducts\Controller\Traits;
use Cake\Core\Configure;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
trait OverrideTableTrait
{
/**
* @var Table|null
*/
protected ?Table $_table = null;
/**
* @var string
*/
protected string $_defaultTable = '';
/**
* @var string
*/
protected string $_tableConfigKey = '';
/**
* Gets the table instance
*
* @return Table
*/
public function getTable(string $tableName = null)
{
if ($this->_table instanceof Table) {
return $this->_table;
}
$table = $tableName;
if (!isset($table)) {
$table = $this->_tableConfigKey && Configure::read($this->_tableConfigKey) ? Configure::read($this->_tableConfigKey) : $this->_defaultTable;
}
$this->_table = TableRegistry::getTableLocator()->get($table);
return $this->_table;
}
/**
* Set the users table
*
* @param Table $table table
* @return void
*/
public function setTable(Table $table)
{
$this->_table = $table;
}
}