Using the model in another controller with CakePHP

I have some controllers in my Cake application, namely servers and users . I want to write a simple API and have a controller called ApiController . Inside this controller, I want to use the servers and users models.

I am very new to Cake, but not MVC at all. From what I have taken so far, Cake automatically uses the servers model in the ServersController , I don’t know how to explicitly use the model from a specific controller.

In addition, I want API requests to serve only JSON without any HTML markup. I have a default layout that defines the header / footer of all the pages of my site and which is displayed when I request the API function, as well as JSON from the view. How can I stop layout output and instead just view the view?

+4
source share
2 answers

You need to declare the $uses property in your controller, see http://book.cakephp.org/2.0/en/controllers.html#controller-attributes

The $uses attribute indicates which model will be available to the controller:

 <?php class ApisController extends AppController{ public $uses = array( 'User', 'Server' ); } 

Also, you don't seem to follow the cake naming conventions where the controller names are plural ( Apis or Servers ) and the model names are singular ( Api or Server ). These names must also be in CamelCase. See http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html for details

Regarding JSON, there is an Ajax layout that you can use to help with JSON server requests. See http://book.cakephp.org/2.0/en/views.html#layouts for more information on how to achieve this.

+14
source

Yottatron's answer is a place, like Nick Dikage. It is important to know the differences between the different ways of loading the model, which is briefly described in the following comment: fooobar.com/questions/99900 / ...

Personally, I don’t want to overload the global $uses array, since very rarely I need a link to all model objects on a global level (and it's just bad practice to overload it, as is the case with Cake docs here: https: //book.cakephp .org / 1.3 / en / The-Manual / Developing-with-CakePHP / Controllers.html # components-helpers-and-uses )

+2
source

All Articles