Helper? Component? Lib? CakePHP2

Note: For 1.3 see the old article on this subject.

I want to outline some ideas on how to chose the appropriate class type if you want to add some additional feature to your cake app.
For a beginner it might be difficult to decide what to use in which case. Hope this article helps to clarify things.
Feel free to comment on this below.

Overview

The following generic levels and types for extending functionality are available, each for its own domain inside MVC:

  • bootstrap functions (most generic methods – no class context)
  • Lib (most generic class)
  • Helper (view level)
  • Component (controller level)
  • Behavior (model level)

And of course the base classes: Datasource, Model and Controller (and View) which you can extend (and provide further functionality this way).

Level of Independence

We need to ask ourselves if this feature needs to interact with other cake elements, like controller, some components, models, …

If it needs to save to the session, or if it needs some controller functionality, it will have to be a component.
With initialize(Controller $controllerReference) and startup(Controller $controllerReference) this is very easy to accomplish.

With Cake13 libs have been introduced. Not every piece of "controller" code necessarily needs to be component anymore.
So if you retrieve an RSS feed or get the weather from a weather channel web service you could just make a clean and independent lib class. No need to extend the cake object or even pass the controller reference. Less memory and dependency is a good thing. And its easier to test, anyway.

Helpers are used if the result is in relation to the view – in other words if its directly related to output or generation of markup (HTML usually). If you want to retrieve some web service information and save it to the database use a component instead.

Database related?

Often times we need to adjust some model data, we either use a component first and then pass it to the model or we use beforeValidate() and beforeSave() in the model. Same goes for the other direction (from model to controller): afterFind() or a component call afterwards.
This is fine for custom changes. As soon as it could be something useful for several models, it might make sense to build a behavior. The code gets cleaner and your models more powerful.

Examples would be:
"Last Editor/Last Change" (see my WhoDidBehavior), "Geocoding" (see my GeocoderBehavior), "Auto-Capitalize first letter of name/title", "Format/Localize Date/Time" (see my DecimalInput or NumberFormat behaviors), "Working with passwords", "Slugging", "Soft Delete", "Serializable input/output", …

Extending base classes

Once you decided what part of MVC is relevant for the functionality you can then proceed with coding such a helper class or method.
Sometimes, it does’nt have to a new class, it can also just be part of the App base class (AppHelper, AppController, AppModel, AppShell, …). And if it is generic enough
to be of use to more than this single application, consider putting it into a generic My base class and let your App base classes extend those:

class MyHelper extends Helper {}
// and
class AppHelper extends MyHelper {}

Don’t forget the appropriate App::uses() statements, though.

This is mainly useful, if your functionality is of use to all extending classes or if it overwrites/extends existing methods.

Reducing code redundancy

Now that we have a vague understanding where to use what type of tool, we should think about cutting down the redundancy.
Lets say we use the vendor class "phpThump". We would have to write two wrappers. one for the helper (display images in the view) and one for the component (uploading images and resizing), maybe even for some behavior (validating + uploading + resizing). This wrapper handles default values from Configure::read() and other cake related settings.
In this scenario we should build one single library in /Lib, maybe called PhpthumbLib.php.
Here we put our wrapper with our custom functions.
Then we build a helper (view side) as well as a component or a behavior (controller side). They will import and use the library file. This is a cleaner approach because changes in the library class will be available in all files it is used in.
Bonus: The main library file is easier to test. And therefore testing the other classes afterwards is easier, too.

Generally speaking, all web services should be some kind of library file (some would make a datasource out of it). It doesn’t matter then if we use it in components or helpers, because it will fit either way.

A helper in a controller, though, is not really a nice thing.
With Cake2.1 there is no need to use helpers in the controller or model code anymore. All text/number/time helper methods have been moved to the Utility package and can now by used from anywhere within your application in a dry and clean way:

App::uses('CakeNumber', 'Utility');
$myValueInPercent = CakeNumber::toPercentage(45.12, 0); // or dynamically - but statically is easier in this case

Plugin or not?

If your feature is not site-specific but very generic it probably makes sense to build a plugin.
This way all other apps can easily use the same plugin. Additionally, test cases, assets etc are all combined in one folder – clean and extendable.

Examples:
A bookmark helper usually can be used in several apps, whereas a custom helper with two functions for this one app will not be very useful anywhere else.

Usage of those resources

For components, add it to the controller in order to use it in the corresponding actions:

public $components = array('MyC'); # file is in /APP/Controller/Component named MyCComponent.php

And in one of the controller’s actions:

$this->MyC->foo();

For helpers, add it to the controller in order to use it in the corresponding views:

public $helpers = array('MyH'); # file is in /APP/View/Helper named MyHHelper.php

And in one of the controller’s views:

$this->MyH->foo();

Libs can be used everywhere – include them at runtime:

App::uses('MyL', 'Lib'); # file is in /APP/Lib/ named MyL.php
$MyL = new MyL();
$result = $MyL->foo($input);

Possible in controllers, components, behaviors, view, helpers, elements and everything else.
They are the most generic classes you can create.

Sidenote: I like to keep those files appended with a suffix, as well (Lib to avoid collisions with other classes or core classes):

App::uses('MyLLib', 'Lib'); # file is in /APP/Lib/ named MyLLib.php
$MyL = new MyLLib();

But that is just my personal convention.

Also note that you are encouraged in 2.x to group your lib classes in packages. So if you have some Utility Helper of your own, you might want to create a subfolder for it (you can use the core folder names or your own naming scheme):

App::uses('MyUtilityLib', 'Utility'); # file is in /APP/Lib/Utility/ named MyUtilityLib.php
$MyUtility = new MyLUtilityLib();

Same with plugins:

App::uses('UrlCacheManagerLib', 'Tools.Routing'); # file is in /APP/Plugin/Tools/Lib/Routing/ named UrlCacheManagerLib.php
$UrlCacheManager = new UrlCacheManagerLib();

Behaviors and other elements are used similar to the above.

For Plugins simply add the plugin name: "Text" becomes "Plugin.Text" etc

bootstrap functions:
If those functions are so generic that you want to use them like h() or env() you can define them in your bootstrap. But be aware that this can lead to chaos if you do that for too many things.

Hacks for special use cases

Sometimes we need to break MVC in order to avoid redundance (and stay DRY).
If a helper has to be available in a controller we need to manually include it then at runtime:

App::uses('MySpecialHelper', 'Helper');
App::uses('View', 'View');
$MySpecialHelper = new MySpecialHelper(new View(null));
$myText = $MySpecialHelper->foo($myText);

I want to emphasize that this should only be done if not possible any other way.
What I do in this case: Move the functionality to a Lib class and use it inside the helper. This way we can use the Lib in the controller/model level and the helper is still the convenience access for the view level.

CakePHP 3.x

For 3.x it became even simpler. Just include the Lib class with "use statements". They Lib suffix is also not needed anymore, as conflicts with other classes can now be resolved using aliasing.

use App\Utility\MyUtility;
...
$myUtility = new MyUtility();
5.00 avg. rating (93% score) - 1 vote

3 Comments

  1. Very nice.
    I’m also in favor of using as much as possible Libs.

    About the filenames, in Cake 2, wouldn’t it be:

    # file is in /app/controllers/components named MyCComponent.php
    # file is in /app/views/helpers named MyHHelper.php
    
  2. You are right – copy and pasting the old document lead to some issues. Hopefully they are all sorted out now 🙂

  3. Hi Mark,

    thank You for Your post!
    You wrote: „Move the functionality to a Lib class and use it inside the helper.“ How do I have to do this in detail? Is this correct:

    App::uses('AppHelper', 'View/Helper');
    App::uses('MyTextLib', 'Lib');
    
    class MyTextHelper extends AppHelper {
        public function foo($bar) {
            MyTextLib::foo($bar);
        }
    }

    It seems a bit odd to me, to repeat all the methods’ names of the Lib inside my helper.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.