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?
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');
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);
Accessing a Component’s Controller
From within a Component you can access the current controller through the registry:
$controller = $this->_registry->getController();
for more please read this link : http://book.cakephp.org/3.0/en/controllers/components.html
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 insist to use loadModel which adds the instance to the controller as a property then that's how you do it.
class ArticleComponent extends Component
{
public function initialize(array $config)
{
$this->controler = $this->_registry->getController();
}
public function myFunction($id)
{
$this->controller->loadModel('Articles');
$article = $this->controller->Articles->get($id);
debug($article);
}
}
This way is like telling controller to open a model for you:
$article = $component->controller->UserModel;
But when you can call a model straight away using TableRegistry
what's the point of calling controller to call a model for you.
$article = $component->UserModel;
Long story short loadModel()
is a wrapper for TableRegistry
my answer is same approch other answers. but, I try to save record inside component.
In this case, code is like following...
use Cake\ORM\TableRegistry;
---
$model = TableRegistry::get('MyModeles');
$entity = $model->newEntity();
$entity->set('filed1', 'newValue');
....
$model->save($entity);
You can dynamic access to table with the next snippet:
use Cake\Event\Event;
use Cake\Controller\Component;
use Cake\ORM\TableRegistry;
class TestComponent extends Component {
private $controller;
private $table;
public function startup(Event $event) {
$this->controller = $event->getSubject();
$this->table = TableRegistry::get($this->controller->name);
}
}