@@ -7,32 +7,47 @@ description: "Learn CakePHP controllers: handle requests, render views, manage c
77
88` class ` Cake\\ Controller\\ ** Controller**
99
10- Controllers are the 'C' in MVC. After routing has been applied and the correct
11- controller has been found, your controller's action is called. Your controller
12- should handle interpreting the request data, making sure the correct models
13- are called, and the right response or view is rendered. Controllers can be
14- thought of as middle layer between the Model and View. You want to keep your
15- controllers thin, and your models fat. This will help you reuse
16- your code and makes your code easier to test.
17-
18- Commonly, a controller is used to manage the logic around a single model. For
19- example, if you were building a site for an online bakery, you might have a
20- RecipesController managing your recipes and an IngredientsController managing your
21- ingredients. However, it's also possible to have controllers work with more than
22- one model. In CakePHP, a controller is named after the primary model it
23- handles.
24-
25- Your application's controllers extend the ` AppController ` class, which in turn
26- extends the core ` Controller ` class. The ` AppController `
27- class can be defined in ** src/Controller/AppController.php** and it should
28- contain methods that are shared between all of your application's controllers.
29-
30- Controllers provide a number of methods that handle requests. These are called
31- * actions* . By default, each public method in
32- a controller is an action, and is accessible from a URL. An action is responsible
33- for interpreting the request and creating the response. Usually responses are
34- in the form of a rendered view, but there are other ways to create responses as
35- well.
10+ Controllers are the 'C' in MVC. After routing is applied and the correct
11+ controller is found, your controller's action is called. Your controller
12+ should interpret the request, ensure the right models are called, and return
13+ the appropriate response or view. Controllers sit between Model and View.
14+
15+ ::: tip Keep Controllers Thin
16+ Move heavy business logic into models and services. Thin controllers are easier
17+ to test and reuse.
18+ :::
19+
20+ Commonly, a controller manages logic around a single model. For example, for
21+ an online bakery you might have a RecipesController managing recipes and an
22+ IngredientsController managing ingredients. However, it's also possible to have
23+ controllers work with more than one model. In CakePHP, a controller is named
24+ after the primary model it handles.
25+
26+ ::: info At a Glance
27+
28+ - Controllers coordinate request handling, model calls, and responses.
29+ - Each public method is an action by default.
30+ - Shared logic goes into ` AppController ` .
31+
32+ :::
33+
34+ Your application's controllers extend the ` AppController ` class, which extends
35+ the core ` Controller ` class. The ` AppController ` class can be defined in
36+ ** src/Controller/AppController.php** and should contain methods shared between
37+ all of your application's controllers.
38+
39+ Controllers provide methods that handle requests. These are called * actions* .
40+ By default, each public method in a controller is an action and is accessible
41+ from a URL. An action interprets the request and creates the response. Usually
42+ responses are rendered views, but there are other response types as well.
43+
44+ ::: details Naming and Conventions
45+
46+ - Controller names are plural, e.g. ` RecipesController ` .
47+ - Action names map to view templates by convention.
48+ - Use ` AppController ` for shared behavior.
49+
50+ :::
3651
3752<a id =" app-controller " ></a >
3853
@@ -88,6 +103,14 @@ CakePHP puts all the important request information into the `$this->request`
88103property. See the section on [ Cake Request] ( controllers/request-response#cake-request ) for more information on the
89104CakePHP request object.
90105
106+ ::: info Request Flow Summary
107+
108+ - Routes map URLs to a controller/action.
109+ - The request data is available via ` $this->request ` .
110+ - The action returns a response (often a rendered view).
111+
112+ :::
113+
91114## Controller Actions
92115
93116Controller actions are responsible for converting the request parameters into a
@@ -138,6 +161,11 @@ If for some reason you'd like to skip the default behavior, you can return a
138161` Cake\Http\Response ` object from the action with the fully
139162created response.
140163
164+ ::: tip Explicit Responses
165+ Return a ` Response ` when you need full control (JSON, file downloads, or
166+ custom status codes).
167+ :::
168+
141169In order for you to use a controller effectively in your own application, we'll
142170cover some of the core attributes and methods provided by CakePHP's controllers.
143171
@@ -160,12 +188,9 @@ can be accessed in your view:
160188
161189``` php
162190// First you pass data from the controller:
163-
164191$this->set('color', 'pink');
165192
166193// Then, in the view, you can utilize the data:
167- ?>
168-
169194You have selected <?= h($color) ?> icing for the cake.
170195```
171196
@@ -190,6 +215,11 @@ Keep in mind that view vars are shared among all parts rendered by your view.
190215They will be available in all parts of the view: the template, the layout and
191216all elements inside the former two.
192217
218+ ::: tip View Data Scope
219+ View variables are shared with the layout and elements. Prefer specific keys
220+ to avoid accidental collisions.
221+ :::
222+
193223### Setting View Options
194224
195225If you want to customize the view class, layout/template paths, helpers or the
@@ -228,6 +258,13 @@ Available strategies are:
228258
229259You can retrieve the current strategy using ` getConfigMergeStrategy() ` .
230260
261+ ::: details When to Change Merge Strategy
262+
263+ - Use shallow merges for small, explicit overrides.
264+ - Use deep merges when you want to extend nested defaults.
265+
266+ :::
267+
231268::: info Added in version 5.3.0
232269` ViewBuilder::setConfigMergeStrategy() ` and ` ViewBuilder::getConfigMergeStrategy() ` were added.
233270:::
@@ -265,25 +302,22 @@ Although CakePHP will automatically call it after every action's logic
265302an alternate view file by specifying a view file name as first argument of
266303` Controller::render() ` method.
267304
305+ ::: tip Skipping Auto-Render
306+ Call ` $this->disableAutoRender() ` when the action fully handles the response.
307+ :::
308+
268309If ` $view ` starts with '/', it is assumed to be a view or
269310element file relative to the ** templates** folder. This allows
270311direct rendering of elements, very useful in AJAX calls:
271312
272- ``` php
313+ ::: code-group
314+
315+ ``` php [Element]
273316// Render the element in templates/element/ajaxreturn.php
274317$this->render('/element/ajaxreturn');
275318```
276319
277- The second parameter ` $layout ` of ` Controller::render() ` allows you to specify the layout
278- with which the view is rendered.
279-
280- #### Rendering a Specific Template
281-
282- In your controller, you may want to render a different view than the
283- conventional one. You can do this by calling ` Controller::render() ` directly. Once you
284- have called ` Controller::render() ` , CakePHP will not try to re-render the view:
285-
286- ``` php
320+ ``` php [Custom Template]
287321namespace App\Controller;
288322
289323class PostsController extends AppController
@@ -295,14 +329,7 @@ class PostsController extends AppController
295329}
296330```
297331
298- This would render ** templates/Posts/custom_file.php** instead of
299- ** templates/Posts/my_action.php** .
300-
301- You can also render views inside plugins using the following syntax:
302- ` $this->render('PluginName.PluginController/custom_file') ` .
303- For example:
304-
305- ``` php
332+ ``` php [Plugin Template]
306333namespace App\Controller;
307334
308335class PostsController extends AppController
@@ -314,7 +341,22 @@ class PostsController extends AppController
314341}
315342```
316343
317- This would render ** plugins/Users/templates/UserDetails/custom_file.php**
344+ :::
345+
346+ The second parameter ` $layout ` of ` Controller::render() ` allows you to specify the layout
347+ with which the view is rendered.
348+
349+ #### Rendering a Specific Template
350+
351+ In your controller, you may want to render a different view than the
352+ conventional one. You can do this by calling ` Controller::render() ` directly.
353+ Once you have called ` Controller::render() ` , CakePHP will not try to re-render
354+ the view.
355+
356+ This renders ** templates/Posts/custom_file.php** instead of
357+ ** templates/Posts/my_action.php** . Rendering plugin templates uses the syntax
358+ ` $this->render('PluginName.PluginController/custom_file') ` and renders
359+ ** plugins/Users/templates/UserDetails/custom_file.php** .
318360
319361<a id =" controller-viewclasses " ></a >
320362
@@ -330,6 +372,10 @@ render an HTML view or render a JSON or XML response. To define the list of
330372supported view classes for a controller is done with the ` addViewClasses() `
331373method:
332374
375+ ::: info Content Negotiation
376+ Use ` addViewClasses() ` to serve multiple formats from the same action.
377+ :::
378+
333379``` php
334380namespace App\Controller;
335381
@@ -450,7 +496,9 @@ controller action and rendering a view.
450496
451497You can redirect using ` routing array ` values:
452498
453- ``` php
499+ ::: code-group
500+
501+ ``` php [Array URL]
454502return $this->redirect([
455503 'controller' => 'Orders',
456504 'action' => 'confirm',
@@ -463,20 +511,20 @@ return $this->redirect([
463511]);
464512```
465513
466- Or using a relative or absolute URL:
467-
468- ``` php
514+ ``` php [Relative URL]
469515return $this->redirect('/orders/confirm');
516+ ```
470517
518+ ``` php [Absolute URL]
471519return $this->redirect('https://www.example.com');
472520```
473521
474- Or to the referer page:
475-
476- ``` php
522+ ``` php [Referer]
477523return $this->redirect($this->referer());
478524```
479525
526+ :::
527+
480528By using the second parameter you can define a status code for your redirect:
481529
482530``` php
@@ -573,20 +621,22 @@ public function initialize(): void
573621## Request Life-cycle Callbacks
574622
575623CakePHP controllers trigger several events/callbacks that you can use to insert
576- logic around the request life-cycle:
624+ logic around the request life-cycle.
577625
578- ### Event List
626+ ::: details Event List
579627
580628- ` Controller.initialize `
581629- ` Controller.startup `
582630- ` Controller.beforeRedirect `
583631- ` Controller.beforeRender `
584632- ` Controller.shutdown `
585633
634+ :::
635+
586636### Controller Callback Methods
587637
588- By default, the following callback methods are connected to related events if the
589- methods are implemented by your controllers
638+ By default, the following callback methods are connected to related events if
639+ the methods are implemented by your controllers.
590640
591641#### beforeFilter()
592642
@@ -623,13 +673,12 @@ To redirect from within a controller callback method you can use the following:
623673``` php
624674public function beforeFilter(EventInterface $event): void
625675{
626- if (... ) {
676+ if ($this->request->getParam('prefix') === 'Admin' ) {
627677 $event->setResult($this->redirect('/'));
628678
629679 return;
630680 }
631-
632- ...
681+ // Normal request handling continues.
633682}
634683```
635684
0 commit comments