I am new in cakephp, and trying to create a component using cakephp version 4.0.7 .
In component I need to save data in a table. I have followed this documentation on inserting data
In component I have tried below code for registry My table
use Cake\ORM\Locator\LocatorAwareTrait;
class MyComponent extends Component{
public function foo()
{
$ProductsTable = $this->getTableLocator()->get('Products');
}
}
In output I am getting below exception
Call to undefined method App\Controller\Component\MyComponent::getTableLocator()
How can I solve this problem ?
CakePHP 4.0.x
$productsTable = \Cake\ORM\TableRegistry::getTableLocator()->get('Products');
from CakePHP 4.1
Cake\ORM\TableRegistry has been deprecated. Use Cake\ORM\Locator\LocatorAwareTrait::getTableLocator() or Cake\Datasource\FactoryLocator::get('Table')
read https://book.cakephp.org/4/en/appendices/4-1-migration-guide.html#orm
and try to use FactoryLocator:
use Cake\Datasource\FactoryLocator;
$productsTable = FactoryLocator::get('Table')->get('Products');
//$productsTable->find()...
or inject trait inside component class
class MyComponent extends Component{
use Cake\ORM\Locator\LocatorAwareTrait;
public function foo()
{
$ProductsTable = $this->getTableLocator()->get('Products');
}
}