Loading CakePHP Models Inside Other Models

Really quick tip that I'm always looking up is how to load CakePHP Models from within another Model, this is currently using version 2.x

<?php
// the other model to load & use
App::uses('AnotherModel', 'Model');

class MyModel extends AppModel {

	public $name = 'MyModel';
	
	public function test() {
		// load the Model
		$anotherModel = new AnotherModel();
		// use the Model
		$anotherModel->save($data);
	}
}

Instead of declaring uses at the top you can also import the Model class when you want to use it:

App::import('Model','AnotherModel');
$anotherModel = new AnotherModel();
$anotherModel->save($data);

Other ways can be found in this StackOverflow answer but I generally use the first method above.

Posted on 18th January 2013
4 years, 4 months, 1 week ago

comments powered by Disqus