Cakephp静态数据收集

问题描述:

I was unsure about what to call this question but here is my problem:

I am creating a webshop in Cakephp. For this purpose i have alot of different categories that is bound to a static menu line.

Now regardless of where you are on the webshop you will be able to see these categories.

All the categories are stored in the database and then looped into the default layout (meaning that if i add a new category it will automaticly add it self to the menu line).

My question is since all of these categories has to be fetch no matter where you are in my application how do i collect them?

Only way i can think of is collecting them in every controller and set them to a $_SESSIONvariable and then check if the variable is set.

I know there must be another way but how?

Im using CakePHP 2.4

Also the menu of my application is stoped in Layouts->default.ctp

which means that it does not "care" which controller or action you are in. Meaning that the categories must be loaded before the actions

Sound to me as if you are maybe looking for the beforeFilter() callback. Define it on your base controller (which is most likely AppController), and simply set the categories as a view variable, that way the data is available to all layouts on controllers that extend the base controller.

Here's an abstract example of what it could look like:

...

class AppController extends Controller
{
    ...

    public $uses = array
    (
        'Category'
    );

    public function beforeFilter()
    {
        parent::beforeFilter();

        $this->set('categories', $this->Category->find('all'));
    }

    ...
}

In your layout you could then simply check for the existence of $categories and do whatever you have to do.

if(isset($categories))
{
    // show the category menu
}

I would create an appropriate component like this

class CategoryLoaderComponent extends Component {

    public function beforeRender($controller)
    {
        parent::beforeRender($controller);
        $controller->loadModel('Category');
        $categories = $controller->Category->find('list');
        $controller->set('categories', $categories);
    }

}

in this way every controller that uses this component will have the $categories variable automatically set