views:

243

answers:

2

Howdy!

I got layout, nothing special, three columns, just to learn CakePHP. In documentation I found nothing about this case.

I got some statistics in sidebars, si I send them to layout file (default.ctp) cause they are displayed on every page.

I build (thanks to one user here) a component:

class SidebarComponent extends object {
    function startup(&$controller) {
        $this->controller = $controller; // Stores reference Controller in the component
    }

    function count_articles() {
        $articles = ClassRegistry::init('Articles')->count_articles();
        $this->controller->set(compact('articles')); 
    }
}

Everything is working perfectly. I got question about my technique. I needed to load component method in controller by putting:

$this->Sidebar->count_articles();

So I decided to make it a bit shorter, cause I will have to put it in every controller. So, I created new component's function:

function sidebars($userid) {
        return array(
                $this->top_articles(), 
                $this->random_article()
                );
}

And I initialize it in controller that way:

$this->Sidebar->sidebars();

Everything is working correctly, I need only advice/feedback if it's good way I do this :)

Thanks for your time.

+1  A: 

you don't need to call it explicitly in every controller. component's startup() method is called automatically before every action in the controller that is using your component.

so you can use startup() to get and set your data for views, and if you need some initialization before (like getting reference to controller), put it in component's initialize() method.

parserr
Hm...didn't think of it. Any code samples? :)
Johannes
have a look at http://book.cakephp.org/view/64/Creating-Components#MVC-Class-Access-Within-Components-65 . basically, you could move startup() from your example to initialize(), and sidebars() to startup(). mind the parameters, of course. sample - http://bin.cakephp.org/view/1135878647 .
parserr
A: 

If you have sidebars with the same things in them, also sounds like a case for elements as well

Matt