1
votes

I'm new to cakephp. I have a class called Rest that is shared by two controllers: Pages and Categories.

I therefore thought of making the instance of the class in the AppController:

class AppController extends Controller {
    public $rest;


    public function DoRest() {
        require 'Component/Rest.php';

        if(!isset($this->rest))
        $this -> rest = new Rest();

        return $this -> rest;
    }
}

then i can access it at the categoriesController:

public function index() 
    {
        if ($this->request->is('requested')) {
            return $this -> DoRest() -> getCategories();
        } else {
            $this -> set('categories', $this -> DoRest() -> getCategories());
        }
    }

and in the pages controller:

public function category() {

        $this -> set('items',$this -> DoRest() -> getCategoryById($this->request->query['id']));
    }

within category.ctp i can access the categories through:

$categories = $this->requestAction('categories/index');

however now im getting this error: Error: Cannot redeclare class Rest

What have i done wrong?

2
just now, didn't solve it :( - bicycle
@nlsbshtr i got it, there was a file inside the Rest class with a require as well. After chancing that to require_once 'PestXML.php'; solved the error. But still, it appears the Rest class get's called twice though it's called in the AppController. How should i prevent that that both the categories and pages use the same Rest instance? - bicycle

2 Answers

1
votes
require 'Component/Rest.php';

Thats not how its done in cake. Please read the documentation. If anything you use App::uses().

But with components you should just follow the official way:

public $components = array('Rest');

and the component class file should be named RestComponent.php, again as documented.

If you are using something else, its not a component, but a lib and requires the above app::uses() (place your file in /Lib folder then):

App::uses('Rest', 'Lib');
1
votes

You’ve a couple of issues. First, you’re not including files the “Cake” way; and second you’re not naming components the “Cake” way either.

Components should be suffixed as such. So your Rest component should look like this:

<?php
class RestComponent extends Component {
}

Secondly, components should then be loaded in your controller via the relavant property:

<?php
class YourController extends AppControler {
    public $components = array('Rest');
}

Everything should then work. However, I’d question your need to create a Rest component at all. CakePHP has built-in REST handling, and also a HTTP component for making requests to third-party services via HTTP.