Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a model in a different controller with CakePHP

Tags:

php

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. Within this controller I want to use both the servers and users models.

I'm very new to Cake, but not MVC in general. From what I've picked up so far Cake will automatically use the servers model in the ServersController controller, I don't know how to explicitly use a model from a certain controller.

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

like image 686
James Dawson Avatar asked Dec 04 '22 15:12

James Dawson


1 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 states which model(s) the will be available to the controller:

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

Also you don't appear to be following Cake naming conventions where controller names are plural (Apis or Servers) and model names are singular (Api or Server). These names should also be in CamelCase. See http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html for more information

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

like image 50
93196.93 Avatar answered Dec 07 '22 04:12

93196.93