如何在Cakephp 3.0中加载组件内部的模型?之前(在Cakephp2中)您可以使用
$Model = ClassRegistry::init($modelName);
$Model->create(false);
$saved = $Model->save($data);
3.0中的等价物是什么?
如前所述,您可以使用TableRegistry访问模型:
use Cake'ORM'TableRegistry;
$this->Articles = TableRegistry::get('Articles');
请参阅此处获取文档。
正如有人在评论中所说,您至少应该阅读迁移指南,了解3.0的区别。为了解决您的具体问题,您现在可以使用TableRegistry
:
$table = TableRegistry::get($tableName);
访问组件的控制器
从组件中,您可以通过注册表访问当前控制器:
$controller = $this->_registry->getController();
欲了解更多信息,请阅读此链接:http://book.cakephp.org/3.0/en/controllers/components.html
我所做的一件事是在组件中构建一个loadModel类。这使我的代码保持一致。
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);
}
}
如果你坚持使用loadModel,它将实例作为属性添加到控制器中,那么你就是这样做的。
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);
}
}
这种方式就像告诉控制器为您打开一个模型:
$article=$component->controller->UserModel;
但是,当您可以使用TableRegistry
直接调用模型时,调用控制器为您调用模型有什么意义。
$article=$component->UserModel;
长话短说loadModel()
是TableRegistry
的包装器
我的答案与其他答案相同。但是,我试图将记录保存在组件内部。
在这种情况下,代码如下。。。
use Cake'ORM'TableRegistry;
---
$model = TableRegistry::get('MyModeles');
$entity = $model->newEntity();
$entity->set('filed1', 'newValue');
....
$model->save($entity);
您可以使用下一个片段动态访问表:
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);
}
}