Alex
Alex

Reputation: 838

Where to put a custom function in CakePHP

I have a function in one of my views that formats data coming from the DB before displaying it. Since I use this function in many views, I'd like to make a global function that would be accessible from every view. How would I do that ?

Upvotes: 9

Views: 11868

Answers (4)

Rémi Becheras
Rémi Becheras

Reputation: 15222

Yes you have to create your owns View Helpers.

You will find the documentation in the Section "View > Helpers" of the cook book : here

But the section "Core Libraries > Helpers" just explains how to use the ready-to-use cakephp Helpers like HtmlHelper or FormHelper: here

Likewise you can note that this is the same logic with firstly controllers and components, and secondly model and behaviours.

  • Then the cook book presents the core components in core-libraries/toc-components
  • How to create your own is explained in controllers/components
  • The core behaviours are presented in core-libraries/toc-behaviors
  • The how to create your own is in models/behaviours

This system is really efficient and makes cakePHP a handy framework (thank you the great documentation) that implement efficiently the Model-View-Controller design pattern.

If you understand that question correctly, you never ask yourself this kind of issue about cakePHP and by the same time, about the MVC pattern.

Upvotes: 0

dhofstet
dhofstet

Reputation: 9964

As mentioned in the other answers, creating a helper is probably what you are looking for. See the cookbook entry for more information.

To make your helper available in all your views, add the helper to the $helpers array of your AppController (app/Controller/AppController.php).

Upvotes: 12

Mouad Debbar
Mouad Debbar

Reputation: 3226

Creating a helper (as Headshota and preinheimer explained) is the best idea if the function is complex..

But if your function is simple, you can open the file app/config/bootstrap.php

write your function in this file and that's it..

the function will be accessible anywhere (models, controllers, views, etc)

hope that helps...

Upvotes: 5

preinheimer
preinheimer

Reputation: 3722

I think you want to create a view helper, here's an example one: Minify Helper

Upvotes: 0

Related Questions