Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3.0 - Load Model inside Component

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?

like image 865
Sultanen Avatar asked Mar 05 '15 10:03

Sultanen


3 Answers

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.

like image 199
Melvin Avatar answered Sep 21 '22 02:09

Melvin


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);
like image 38
José Lorenzo Rodríguez Avatar answered Sep 19 '22 02:09

José Lorenzo Rodríguez


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);
    }
}
like image 41
Dooltaz Avatar answered Sep 19 '22 02:09

Dooltaz