Access Model Method from Different Controller in Cakephp

In cakephp, you can call model method from same controller but sometimes you may need to call method from different model, don’t worry – you can do that too 🙂


Let you have two controllers named home and search. you want to pull few data from search model to home controller. So define the method in search model which will be something like below –


<?php

class Search extends AppModel {

	var $name = 'Search';
	var $useTable='searches';
	
	//return a list of data as needed
	function getList(){			
	 ....
         ....
          return $data;
	}

}	
			
?>

so call getList method from home controller as below


<?php
	class HomeController extends AppController{
		
		var $name = 'Home';
				   
		function index(){
   		 $data = ClassRegistry::init('Search')->getList(); //get value from Search Model, getList method
                ..................
                ..................

		}
	}
?>

See the code above in index method. It will call getList method on Search Model. You can pass parameter as need. Exciting, nah?

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

6 thoughts on “Access Model Method from Different Controller in Cakephp

  1. Below one works for us:

    App::import(‘Controller’, ‘Products’);
    $Products = new ProductsController;
    $Products->constructClasses();
    $Products->ProductFunction();

    Hope it helps to some one else 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s