@@ -7,32 +7,43 @@ 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+ - Controllers coordinate request handling, model calls, and responses.
28+ - Each public method is an action by default.
29+ - Shared logic goes into ` AppController ` .
30+ :::
31+
32+ Your application's controllers extend the ` AppController ` class, which extends
33+ the core ` Controller ` class. The ` AppController ` class can be defined in
34+ ** src/Controller/AppController.php** and should contain methods shared between
35+ all of your application's controllers.
36+
37+ Controllers provide methods that handle requests. These are called * actions* .
38+ By default, each public method in a controller is an action and is accessible
39+ from a URL. An action interprets the request and creates the response. Usually
40+ responses are rendered views, but there are other response types as well.
41+
42+ ::: details Naming and Conventions
43+ - Controller names are plural, e.g. ` RecipesController ` .
44+ - Action names map to view templates by convention.
45+ - Use ` AppController ` for shared behavior.
46+ :::
3647
3748<a id =" app-controller " ></a >
3849
@@ -88,6 +99,12 @@ CakePHP puts all the important request information into the `$this->request`
8899property. See the section on [ Cake Request] ( controllers/request-response#cake-request ) for more information on the
89100CakePHP request object.
90101
102+ ::: info Request Flow Summary
103+ - Routes map URLs to a controller/action.
104+ - The request data is available via ` $this->request ` .
105+ - The action returns a response (often a rendered view).
106+ :::
107+
91108## Controller Actions
92109
93110Controller actions are responsible for converting the request parameters into a
@@ -138,6 +155,11 @@ If for some reason you'd like to skip the default behavior, you can return a
138155` Cake\Http\Response ` object from the action with the fully
139156created response.
140157
158+ ::: tip Explicit Responses
159+ Return a ` Response ` when you need full control (JSON, file downloads, or
160+ custom status codes).
161+ :::
162+
141163In order for you to use a controller effectively in your own application, we'll
142164cover some of the core attributes and methods provided by CakePHP's controllers.
143165
@@ -160,12 +182,9 @@ can be accessed in your view:
160182
161183``` php
162184// First you pass data from the controller:
163-
164185$this->set('color', 'pink');
165186
166187// Then, in the view, you can utilize the data:
167- ?>
168-
169188You have selected <?= h($color) ?> icing for the cake.
170189```
171190
@@ -190,6 +209,11 @@ Keep in mind that view vars are shared among all parts rendered by your view.
190209They will be available in all parts of the view: the template, the layout and
191210all elements inside the former two.
192211
212+ ::: tip View Data Scope
213+ View variables are shared with the layout and elements. Prefer specific keys
214+ to avoid accidental collisions.
215+ :::
216+
193217### Setting View Options
194218
195219If you want to customize the view class, layout/template paths, helpers or the
@@ -228,6 +252,11 @@ Available strategies are:
228252
229253You can retrieve the current strategy using ` getConfigMergeStrategy() ` .
230254
255+ ::: details When to Change Merge Strategy
256+ - Use shallow merges for small, explicit overrides.
257+ - Use deep merges when you want to extend nested defaults.
258+ :::
259+
231260::: info Added in version 5.3.0
232261` ViewBuilder::setConfigMergeStrategy() ` and ` ViewBuilder::getConfigMergeStrategy() ` were added.
233262:::
@@ -265,25 +294,20 @@ Although CakePHP will automatically call it after every action's logic
265294an alternate view file by specifying a view file name as first argument of
266295` Controller::render() ` method.
267296
297+ ::: tip Skipping Auto-Render
298+ Call ` $this->disableAutoRender() ` when the action fully handles the response.
299+ :::
300+
268301If ` $view ` starts with '/', it is assumed to be a view or
269302element file relative to the ** templates** folder. This allows
270303direct rendering of elements, very useful in AJAX calls:
271304
272- ``` php
305+ ::: code-group
306+ ``` php [Element]
273307// Render the element in templates/element/ajaxreturn.php
274308$this->render('/element/ajaxreturn');
275309```
276-
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
310+ ``` php [Custom Template]
287311namespace App\Controller;
288312
289313class PostsController extends AppController
@@ -294,15 +318,7 @@ class PostsController extends AppController
294318 }
295319}
296320```
297-
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
321+ ``` php [Plugin Template]
306322namespace App\Controller;
307323
308324class PostsController extends AppController
@@ -313,8 +329,22 @@ class PostsController extends AppController
313329 }
314330}
315331```
332+ :::
333+
334+ The second parameter ` $layout ` of ` Controller::render() ` allows you to specify the layout
335+ with which the view is rendered.
316336
317- This would render ** plugins/Users/templates/UserDetails/custom_file.php**
337+ #### Rendering a Specific Template
338+
339+ In your controller, you may want to render a different view than the
340+ conventional one. You can do this by calling ` Controller::render() ` directly.
341+ Once you have called ` Controller::render() ` , CakePHP will not try to re-render
342+ the view.
343+
344+ This renders ** templates/Posts/custom_file.php** instead of
345+ ** templates/Posts/my_action.php** . Rendering plugin templates uses the syntax
346+ ` $this->render('PluginName.PluginController/custom_file') ` and renders
347+ ** plugins/Users/templates/UserDetails/custom_file.php** .
318348
319349<a id =" controller-viewclasses " ></a >
320350
@@ -330,6 +360,10 @@ render an HTML view or render a JSON or XML response. To define the list of
330360supported view classes for a controller is done with the ` addViewClasses() `
331361method:
332362
363+ ::: info Content Negotiation
364+ Use ` addViewClasses() ` to serve multiple formats from the same action.
365+ :::
366+
333367``` php
334368namespace App\Controller;
335369
@@ -450,7 +484,8 @@ controller action and rendering a view.
450484
451485You can redirect using ` routing array ` values:
452486
453- ``` php
487+ ::: code-group
488+ ``` php [Array URL]
454489return $this->redirect([
455490 'controller' => 'Orders',
456491 'action' => 'confirm',
@@ -462,20 +497,16 @@ return $this->redirect([
462497 '#' => 'top',
463498]);
464499```
465-
466- Or using a relative or absolute URL:
467-
468- ``` php
500+ ``` php [Relative URL]
469501return $this->redirect('/orders/confirm');
470-
502+ ```
503+ ``` php [Absolute URL]
471504return $this->redirect('https://www.example.com');
472505```
473-
474- Or to the referer page:
475-
476- ``` php
506+ ``` php [Referer]
477507return $this->redirect($this->referer());
478508```
509+ :::
479510
480511By using the second parameter you can define a status code for your redirect:
481512
@@ -573,20 +604,20 @@ public function initialize(): void
573604## Request Life-cycle Callbacks
574605
575606CakePHP controllers trigger several events/callbacks that you can use to insert
576- logic around the request life-cycle:
577-
578- ### Event List
607+ logic around the request life-cycle.
579608
609+ ::: details Event List
580610- ` Controller.initialize `
581611- ` Controller.startup `
582612- ` Controller.beforeRedirect `
583613- ` Controller.beforeRender `
584614- ` Controller.shutdown `
615+ :::
585616
586617### Controller Callback Methods
587618
588- By default, the following callback methods are connected to related events if the
589- methods are implemented by your controllers
619+ By default, the following callback methods are connected to related events if
620+ the methods are implemented by your controllers.
590621
591622#### beforeFilter()
592623
@@ -623,13 +654,12 @@ To redirect from within a controller callback method you can use the following:
623654``` php
624655public function beforeFilter(EventInterface $event): void
625656{
626- if (... ) {
657+ if ($this->request->getParam('prefix') === 'Admin' ) {
627658 $event->setResult($this->redirect('/'));
628659
629660 return;
630661 }
631-
632- ...
662+ // Normal request handling continues.
633663}
634664```
635665
0 commit comments