Randy Hall
Randy Hall

Reputation: 8167

CakePHP multiple controllers using same method

I have a method (the function in the controller, am I terming that correctly?) and view that I want to use in every controller on my site. Is there a way to make the method global across all controllers and the view .ctp file generic as well? I'd rather not have to copy-paste it everywhere.

This seems like something that should be obvious, so if I'm just searching for the wrong terms, let me know.

Thanks

Upvotes: 0

Views: 1190

Answers (2)

Dave
Dave

Reputation: 29141

Shared/Common Controller Code:

What you've described is a "Component":

Components are packages of logic that are shared between controllers. If you find yourself wanting to copy and paste things between controllers, you might consider wrapping some functionality in a component.

See: http://book.cakephp.org/2.0/en/controllers/components.html


Shared/Common View Code:

As far as the View is concerned, there are a few options. If you want the entire view, you can just specify which view to render: $this->render('TestView/index');

Or, if you want a small chunk of code, you can try an Element.


All together:

If you find yourself creating a lot of the different "parts" (View, Controller/Component, Model/Behavior)...etc, all for the same general purposes (ie cropping a photo), you could think about creating a Plugin.


Side note:

Side note: Usually, I've heard the functions in Controllers referred to as "actions", and the functions in Models called "methods". They're all really methods (a function within a class/object), but - that's how they're commonly referred to.

Upvotes: 2

cornelb
cornelb

Reputation: 6066

You can put the method in AppController and make only one view.

You will use $this->render('/myview.ctp');

Upvotes: 1

Related Questions