How to load a Model inside a Component in Cakephp 3.0? Before(in Cakephp 2) you could use
$Model = ClassRegistry::init($modelName);
$Model->create(false);
$saved = $Model->save($data);
Whats the equivalent of that in 3.0?
As pointed out before, you can use the TableRegistry to access a model:
use Cake\ORM\TableRegistry;
$this->Articles = TableRegistry::get('Articles');
See here for documentation.
As someone said in the comments, you should at least read the migration guide to understand what the differences with 3.0 are. To address your specific question, you now can use the TableRegistry
:
$table = TableRegistry::get($tableName);
One thing that I've done is to build a loadModel class in the component. This keeps my code consistent.
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\ORM\TableRegistry;
class MyComponent extends Component {
public function initialize(array $config) {
parent::initialize($config);
$this->loadModel('Users');
}
private function loadModel($model) {
$this->$model = TableRegistry::get($model);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With