0

I have an existential question that I hope someone can answer.
Why is it that Cakephp controller needs to have the "controller" word attached?

I know what is the naming convention, but nowhere does it says why is it so (well, maybe it's written somewhere, but I haven't found it).

Controller classnames are plural, CamelCased, and end in Controller

We don't have PostModel.php, WhateverModel.php or viewView.ctp, addView.ctp. With models it's just Post.php or Item.php. With views is... well, anything, but there's no need of a "View" append at the end of the action. Why the difference with controllers?

I have seen a few questions where the error is that they have ItemModel.php, and I understand why the confusion if the controller is ItemsController.php (though, granted, it's not an excuse to not read the docs).

I thought maybe it was to help avoiding inflection problems, like with a Fish.php model, the controller would be also Fish.php if we didn't add the controller part. But the separation of folders is quite clear and having

/Controller
   Fish.php
/Model
   Fish.php

isn't really a problem... or is it?

My question is why, not how the naming convention for controllers is like that, and if there's any logical reason besides a "just because". Even a "we started like that in version 0.0.1 and then it was to late to change it" would suffice.

Nunser
  • 4,512
  • 8
  • 25
  • 37

1 Answers1

6

Models are the only classes that do not have the type appended.

Something <- model class
SomethingBehavior <- behavior class
SomethingHelper <- helper class
SomethingController <- controller class
SomethingComponent <- Component class
SomethingView <- View class

You can not do the following:

/Controller
   Fish.php
/Model
   Fish.php

Ever tried importing two classes into PHP with the same class name? (CakePHP expects the class name to match the file name since 2.x)

Fatal error: class `Whatever` already exists (or something similar)

Before PHP 5.3 and namespaces this is what had to be done to avoid these fatal errors. Since CakePHP 2.x and below was targeted at versions of PHP below 5.3 and namespaces this was what was done.

Also to make importing classes easier file names map to class names, this is why you can not have Fish.php with class FishController. That would avoid the Fatal error for sure, but Cake does not load classes like that.

Even though CakePHP 3.x will target PHP 5.4, the Controller/Component/Behavior etc will continue to exist for backwards compatibility (probably, its still there in the latest 3.x branch)

dogmatic69
  • 7,574
  • 4
  • 31
  • 49