Skip to main content

Cloudsoft Zone Build, deploy and scale with practical guides to PHP, Node.js, React, DevOps and AI automation. Explore the guides

Cloudsoft Zone
Interview questionsCakePHPPHPInterview preparation

CakePHP interview questions and answers for CakePHP 5

Forty CakePHP interview questions with answers checked against CakePHP 5.4: ORM, associations, middleware, authentication, sessions, caching, routing and what was removed.

Cloudsoft Zone

Updated 19 min read

Two developers at a shared desk in an open-plan office, one pointing at code on a monitor while the other types, with more workstations behind them
Photograph: Kabren / CC BY-SA 3.0, via Wikimedia Commons
In this article

CakePHP interviews in 2026 test whether you can work in a modern CakePHP 5 codebase: the middleware queue, the ORM with tables and entities, the Authentication and Authorization plugins, and the conventions that let a small team move quickly. Questions about scaffolding, requestAction() or AuthComponent still turn up, but the right answer now is "that was removed, and this is what replaced it".

Updated for CakePHP 5.4 (5.4.3, released 3 October 2026), which needs PHP 8.2 or newer and supports PHP 8.5. The questions below keep everything from the classic CakePHP question list that is still useful, correct the answers for version 5, drop what no longer exists, and add the topics interviewers now ask about most. Snippets were run against CakePHP 5.4.3 on PHP 8.5.

Tested with: CakePHP 5.4.3, PHP 8.5.7, Composer 2.

Framework basics

1. What is CakePHP, and when was it developed?

CakePHP is a free, open-source PHP framework for building web applications and APIs, licensed under MIT. Michal Tatarynowicz started it in April 2005, inspired by Ruby on Rails, and version 1.0 followed in May 2006. It is now maintained by the Cake Software Foundation and a core team on GitHub. The current major is 5.x: 5.0 shipped in September 2023, 5.4.0 on 19 July 2026. Security fixes for the 4.x line ended on 10 September 2026, so any 4.x application should be on an upgrade plan (see our CakePHP 4 to 5 upgrade checklist).

2. What are the main features of CakePHP?

A good answer names what you actually use day to day:

  • Convention over configuration: table, class and file names follow rules, so most wiring needs no configuration.
  • A PSR-7/PSR-15 HTTP stack with a middleware queue.
  • An ORM with tables, entities, associations, finders, validation and application rules.
  • Built-in CSRF protection middleware, form tampering protection, and the official Authentication and Authorization plugins.
  • Caching, logging, email, internationalisation and a console framework.
  • Code generation with the Bake plugin, schema changes with the Migrations plugin, and an integrated PHPUnit test suite with fixtures.

3. What is the role of MVC in CakePHP?

CakePHP organises an application into models, views and controllers. The model layer is the ORM: a table class (for example ArticlesTable) holds queries, associations, validation and rules, and an entity class (Article) represents one row. The controller receives the request, calls the model layer and passes data to the view. The view renders a template, usually HTML, but it can also be JSON or XML through view classes. In practice you also have middleware before the controller, and services that you inject; MVC describes the core, not the whole request.

Diagram of a CakePHP 5 request: index.php, the middleware queue, routing, controller callbacks, ORM table and entity, view with layout and helpers, then the response
The path a request takes through a CakePHP 5 application, which many interview questions are really asking about.

4. What is the role of controllers?

A controller groups related actions. Each public method is an action that a route can reach, such as ArticlesController::view(). A controller reads input from $this->request, calls tables or services, chooses what to render, and returns or sets the response. Keep controllers thin: business logic belongs in tables, entities or service classes, which are easier to test and reuse from commands and queues.

5. What are "hooks" (callbacks) in CakePHP, and how do they work?

CakePHP implements hooks through its event system. Tables, controllers, views and commands dispatch events at fixed points, and you can either implement the matching callback method or attach a listener. The table events are Model.beforeMarshal, Model.afterMarshal, Model.beforeFind, Model.buildValidator, Model.buildRules, Model.beforeRules, Model.afterRules, Model.beforeSave, Model.afterSave, Model.afterSaveCommit, Model.beforeDelete, Model.afterDelete and Model.afterDeleteCommit. Older answers list afterFind() and beforeValidate(); those belong to CakePHP 2. Since 3.0, results are post-processed with formatResults() or a custom finder instead.

PHP
// src/Model/Table/ArticlesTable.php
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
    if ($entity->isNew() && !$entity->has('slug')) {
        $entity->set('slug', strtolower(Text::slug($entity->get('title'))));
    }
}

Use afterSaveCommit rather than afterSave for side effects such as sending email or queueing jobs, because it only fires once the transaction has committed.

6. What is a layout, and how do you set it from a controller?

A layout is the template that wraps every view: the HTML head, header, navigation and footer. The rendered view is inserted with $this->fetch('content'). Layouts live in templates/layout/, and default.php is used unless you choose another. Set one with $this->viewBuilder()->setLayout('admin'); in a controller, or $this->layout = 'admin'; inside a template. For a JSON response you disable it or use a JSON view class instead.

7. What does "scaffolding" mean, and what replaced it?

Scaffolding generated CRUD screens at runtime from the database schema. It was removed after CakePHP 2. The replacement is the Bake plugin, which writes real code you can review and edit: bin/cake bake all Articles creates the table, entity, controller, templates and tests. Interviewers like hearing that generated code is a starting point, not a finished feature: you still add authorisation, validation and tests.

8. What cache engines does CakePHP support?

CakePHP 5 ships six engines: File, Apcu, Memcached, Redis, Array (in memory, for tests) and Null (disables caching). You define named configurations under the Cache key in config/app.php and use them through Cache::read(), Cache::write() and Cache::remember(). The framework uses its own configurations for model metadata and translations, and you can cache ORM queries with $query->cache('key', 'configName') or cache a view element with the cache option of element(). Engines for Wincache and XCache from older versions no longer exist.

PHP
$stats = Cache::remember('dashboard_stats', function () {
    return $this->fetchTable('Orders')->find('summary')->toArray();
}, 'long');

The ORM: tables, associations and data

9. How many types of association are there?

Four: belongsTo (many-to-one, the foreign key is on this table), hasOne (one-to-one, the foreign key is on the other table), hasMany (one-to-many) and belongsToMany (many-to-many through a join table, for example articles_tags). You declare them in the table's initialize() method and load related data with contain().

PHP
public function initialize(array $config): void
{
    parent::initialize($config);
    $this->belongsTo('Authors');
    $this->hasMany('Comments', ['dependent' => true]);
    $this->belongsToMany('Tags');
    $this->addBehavior('Timestamp');
}

Since 5.4 the default loading strategy for hasMany and belongsToMany is subquery; you can pin 'strategy' => 'select' per association if a query plan gets worse. For more on loading strategies and N+1 queries, see our CakePHP 5 ORM performance guide.

10. How do you add or remove associations at runtime?

Associations are objects held in the table's association collection, so you can change them at runtime. Call $table->hasMany('RecentComments', [...]) to add one for a single request, and $table->associations()->remove('Comments') to drop one. Most of the time you do not need either: contain() with a query callback, or a custom finder, filters the related data without changing the table's definition. CakePHP 2 used bindModel() and unbindModel() for this; they no longer exist.

11. What database methods should every CakePHP developer know?

  • find() returns a select query; chain where(), contain(), orderBy(), limit(), then iterate or call first(), all() or toArray().
  • get($id) fetches one record by primary key and throws RecordNotFoundException if it is missing, which becomes a 404.
  • newEntity(), newEmptyEntity() and patchEntity() marshal request data into entities and run validation.
  • save(), saveOrFail(), delete() and saveMany() persist entities and fire events.
  • updateAll() and deleteAll() run bulk statements without loading entities and without callbacks.
  • Custom finders: a method such as findPublished(SelectQuery $query) becomes find('published'); in CakePHP 5, extra finder options are passed as named arguments.

Note that 5.x renamed order() to orderBy() and split the query object into SelectQuery, InsertQuery, UpdateQuery and DeleteQuery.

12. What is the difference between a table and an entity?

A table represents the collection: it builds queries, owns associations, behaviours, validation and rules, and saves or deletes. An entity represents one row and its data. Entities hold accessors and mutators (_getFullName(), _setPassword()), track dirty fields, and control mass assignment through the $_accessible property. A common follow-up: never set '*' => true in $_accessible on entities that hold roles or prices, or a crafted form field can overwrite them.

13. How do you display the schema of a model?

Call $this->fetchTable('Articles')->getSchema(). It returns a TableSchema object with columns(), getColumn(), getPrimaryKey(), indexes and constraints. CakePHP reflects the schema from the database and caches it, which is why a production deploy should run bin/cake schema_cache clear (or build) after migrations. For changes to the schema itself, use the Migrations plugin rather than editing tables by hand.

14. What is the difference between validation and application rules?

Validation checks the shape of incoming data before an entity is built: required fields, formats, lengths. It lives in validationDefault() and runs during newEntity() and patchEntity(). Application rules check things that need the database or the entity's state, such as uniqueness or "the author must exist", and run on save() through buildRules(). Putting isUnique in rules rather than validation is the correct answer, because only rules run inside the save transaction.

15. How do you create a standalone validator, for example in a controller?

Create a Cake\Validation\Validator, add rules and call validate(). It returns an array of errors keyed by field, or an empty array when the data is valid. This is useful for search forms and API filters that do not map to a table. For anything that saves data, prefer the table's validator or a Form class (Cake\Form\Form), so the rules live in one place.

PHP
$validator = new Validator();
$validator
    ->requirePresence('email')
    ->email('email')
    ->notEmptyString('name')
    ->maxLength('name', 100);

$errors = $validator->validate($this->request->getData());
// ['email' => ['email' => 'The provided value must be an e-mail address'], ...]

16. What is pagination, and how is it implemented?

Pagination splits a result set into pages. In a controller, call $this->paginate($query) and pass the result to the view; the PaginatorHelper renders page links and sort headers. Settings go in the controller's $paginate property: limit, maxLimit, order and sortableFields. Always set sortableFields, so users can only sort on indexed columns you chose. PaginatorComponent was removed in 5.0; pagination is now built into the controller.

PHP
protected array $paginate = [
    'limit' => 20,
    'maxLimit' => 50,
    'sortableFields' => ['title', 'published_at'],
];

public function index(): void
{
    $query = $this->Articles->find('published')->contain(['Authors']);
    $this->set('articles', $this->paginate($query));
}

Controllers, components, helpers and behaviours

17. What is the difference between a component, a helper and a behaviour?

TypeLayerShares logic betweenExamples
ComponentControllerControllersFlashComponent, FormProtectionComponent, Authentication's AuthenticationComponent
HelperViewTemplates and layoutsHtmlHelper, FormHelper, PaginatorHelper
BehaviourModel (table)TablesTimestampBehavior, TreeBehavior, CounterCacheBehavior, TranslateBehavior

A good one-line answer: components are reusable controller logic, helpers are reusable presentation logic, and behaviours are reusable table logic. If the code does not depend on the request or the view at all, it is better as a plain service class.

18. How do you load components and helpers?

Load components in the controller's initialize() with $this->loadComponent('Flash'); put shared ones in AppController. Load helpers for every view in AppView::initialize() with $this->addHelper('Form'), or for one controller with $this->viewBuilder()->addHelper('Time'). The old $components and $helpers array properties from CakePHP 2 are gone.

19. What does $this->set() do?

It passes variables from the controller to the view. $this->set('article', $article) makes $article available in the template, and $this->set(compact('article', 'tags')) sets several at once. For JSON views, add $this->viewBuilder()->setOption('serialize', ['article']) so the view class knows which variables to encode.

20. Which method runs before every action?

beforeFilter(EventInterface $event) runs before each action, after the controller and its components are initialised. It is the place for per-controller setup such as allowing unauthenticated actions: $this->Authentication->allowUnauthenticated(['login', 'display']). beforeRender() runs after the action but before rendering, and afterFilter() after rendering. Cross-cutting work that applies to every request, such as authentication, CORS or rate limiting, is better as middleware.

21. What are elements?

Elements are small reusable template fragments stored in templates/element/, such as a sidebar or a product card. Render one with $this->element('Products/card', ['product' => $product]); the array becomes variables inside the element. The third argument can enable caching. If a fragment needs its own data loading, use a View Cell instead, which has a small controller-like class of its own.

22. What was requestAction(), and what replaced it?

requestAction() called another controller action from inside a view to fetch data for a widget. It was deprecated in 3.3 and removed in 4.0, because it dispatched a full internal request and was slow and hard to reason about. Use View Cells ($this->cell('Inbox::unreadCount', [$userId])) for self-contained widgets, or load the data in the controller and pass it to an element.

23. What is the default extension for templates, and can you change it?

Templates are plain PHP files with a .php extension, stored in templates/<Controller>/<action>.php. CakePHP 2 used .ctp, and CakePHP 4.0 changed it to .php. The extension is a property of the view class ($_ext), so you can change it by creating a custom view class, but there is rarely a good reason to; editors and static analysis tools expect .php.

24. How do you include JavaScript, such as a menu script, in a page?

Put the file in webroot/js/ and add it with the HtmlHelper: $this->Html->script('menu', ['block' => true]) in the template appends it to the script block, and the layout outputs that block with echo $this->fetch('script'), usually just before </body>. The same pattern works for CSS with $this->Html->css() and the css block. Most teams now build front-end assets with Vite or a similar tool and include the generated files the same way.

Application, routing and configuration

25. What does the Application class do?

src/Application.php is the entry point that configures the app. Its hooks are bootstrap() (load configuration and plugins), middleware() (build the middleware queue), routes(), services() (register dependency injection services), console() and events(). Plugins are listed in config/plugins.php since 5.0, or added with $this->addPlugin().

26. What is the middleware queue, and which middleware does a new app use?

Every request passes through a queue of PSR-15 middleware before it reaches the controller, and the response passes back through the same queue in reverse order. A new cakephp/app skeleton adds error handling, asset serving, routing, body parsing and CSRF protection. Order matters: RoutingMiddleware must run before anything that needs the matched route, and authentication must run before authorisation. Writing your own middleware is a common practical task: implement MiddlewareInterface::process() and add it in Application::middleware().

27. How can you change URL structure without changing application code?

With routes in config/routes.php. Routes map URL patterns to controllers and actions, and the reverse routing used by HtmlHelper::link() and Router::url() builds URLs from the same definitions, so changing a route changes every generated link. Placeholders use braces.

PHP
$routes->scope('/', function (RouteBuilder $routes): void {
    $routes->connect('/blog/{slug}', ['controller' => 'Articles', 'action' => 'view'])
        ->setPass(['slug'])
        ->setPatterns(['slug' => '[a-z0-9-]+']);
    $routes->fallbacks();
});

Generate links with arrays or named routes rather than hard-coded strings, otherwise a route change still breaks links.

28. Where is the database configuration?

Connections are defined under Datasources. config/app.php holds defaults and is committed; config/app_local.php holds environment-specific values such as host, username and password and should not be committed. Many deployments set DATABASE_URL through environment variables instead. A test connection is used by the test suite.

29. How do you create a CakePHP project with Composer?

Composer is PHP's dependency manager. Create a project from the official skeleton with:

Shell
composer create-project --prefer-dist cakephp/app:~5.0 my_app
cd my_app
bin/cake server -p 8765

The skeleton requires the latest 5.x release that your PHP version allows. Commit composer.lock, so every environment installs the same versions, and run composer audit in CI.

Sessions, cookies, security and email

30. How do sessions work, and how do you read, write and delete session data?

CakePHP wraps PHP sessions in a Session object available from the request. Storage is configured under Session in config/app.php with the defaults key: php, cake (files in the app's tmp folder), database or cache. Use dot notation for nested keys.

PHP
$session = $this->request->getSession();
$session->write('Cart.items', $items);
$items = $session->read('Cart.items', []);
$flashOnce = $session->consume('Checkout.notice'); // read and delete
$session->delete('Cart.items');
$session->renew();   // new session ID after login
$session->destroy(); // on logout

Responses are immutable, so you build a Cookie object and assign the new response back. Read cookies with $this->request->getCookie('name'). To encrypt cookie values, add EncryptedCookieMiddleware; the old CookieComponent was removed in 4.0.

PHP
use Cake\Http\Cookie\Cookie;

$cookie = Cookie::create('remember_me', 'yes', [
    'expires' => new DateTime('+30 days'),
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
$this->response = $this->response->withCookie($cookie);

32. How does CakePHP protect against CSRF and form tampering?

CsrfProtectionMiddleware issues a token cookie and checks it on every state-changing request; FormHelper adds the hidden token field automatically, and JavaScript clients send it in the X-CSRF-Token header. FormProtectionComponent separately checks that a submitted form has not had fields added or removed. Both replace the old SecurityComponent, which was removed in 5.0. For APIs authenticated with tokens rather than cookies, you can skip CSRF for those routes with the middleware's skip check.

33. How do authentication and authorisation work in CakePHP 5?

Through two official plugins. cakephp/authentication identifies the user with authenticators (session, form, token, JWT) and identifiers (password, token), and exposes the identity on the request. cakephp/authorization decides what that identity may do with policies, for example ArticlePolicy::canEdit(), and scopes queries to what the user may see. AuthComponent was deprecated in 4.0 and removed in 5.0. Our guides to building a login with Authentication 4 and Authorization 3 policies and scopes go deeper.

34. How do you encrypt and decrypt data?

Cake\Utility\Security::encrypt($plain, $key) encrypts with AES-256-CBC and signs the result with an HMAC; Security::decrypt($cipher, $key) returns the plain text, or null if the data or key is wrong. The key must be at least 32 bytes, and the HMAC salt comes from Security::getSalt() (the SECURITY_SALT setting) unless you pass one. In our test, decrypting with a different key returned null rather than throwing, so always check for it. Never use encryption for passwords: hash them with DefaultPasswordHasher, which uses PHP's password_hash().

35. What are the email transport classes?

Email is sent by a Mailer through a transport configured under EmailTransport in config/app.php. CakePHP 5 ships Cake\Mailer\Transport\MailTransport (PHP's mail()), SmtpTransport and DebugTransport (renders the message without sending, useful in tests). You can write your own by extending AbstractTransport, for example to call a provider's HTTP API. Send heavy or slow mail from a queue worker, not in the request.

36. What logging levels does CakePHP support?

CakePHP's logger follows PSR-3, so it has the eight RFC 5424 levels: emergency, alert, critical, error, warning, notice, info and debug. Write with Log::write('warning', $message) or Log::warning(), or $this->log() from classes using LogTrait. Built-in engines are FileLog, SyslogLog, ConsoleLog and ArrayLog; you can scope a logger to a channel so payment messages go to their own file.

Modern CakePHP topics interviewers now ask about

37. How does dependency injection work in CakePHP 5?

You register services in Application::services(ContainerInterface $container) and type-hint them in controller actions, controller constructors and commands; the container resolves them. CakePHP 5.4 adds an optional built-in container alongside the League container used since 4.2. Typical use: inject a PaymentGateway interface and bind the real implementation in production and a fake in tests. See dependency injection in CakePHP 5 for providers and testing.

PHP
public function services(ContainerInterface $container): void
{
    $container->add(PaymentGateway::class, StripeGateway::class);
}

// In a controller: the container injects the argument
public function checkout(PaymentGateway $gateway): void { /* ... */ }

38. How do you test a CakePHP application?

With PHPUnit through CakePHP's TestSuite. Table and service tests use fixtures to load known rows; controller tests use IntegrationTestTrait to send requests ($this->get('/articles')) and assert on the response, session and flash messages. Use the transaction or truncate fixture strategy for speed, and mock external services through the container. Our CakePHP 5 testing guide covers the details.

39. What changed between CakePHP 4 and 5 that you should know?

  • PHP 8.1 minimum at 5.0, raised to 8.2 in 5.3; strict typing across the framework.
  • Removed: AuthComponent, SecurityComponent, PaginatorComponent and many deprecated methods.
  • Typed query classes (SelectQuery and others), orderBy(), and finder options as named arguments.
  • Plugins configured in config/plugins.php.
  • In 5.4: subquery eager loading by default, entity-to-table checks on save, request-to-DTO mapping and a built-in container. Our CakePHP 5.4 overview lists them.

If you are interviewing for a team still running CakePHP 2 or 3, expect questions about moving that code forward. That is usually a staged rewrite rather than an upgrade, and planning it well is the hard part; Cloudsoft Zone's legacy application modernisation service handles exactly that kind of move.

40. What are the drawbacks or limitations of CakePHP?

  • A smaller ecosystem and job market than Laravel or Symfony, so fewer third-party packages for niche needs.
  • Conventions help when you follow them and cost time when a legacy database does not, although every name can be configured.
  • Major upgrades (2 to 3 especially) have historically required substantial rewrites.
  • Fewer hosted products (queues, admin panels, deployment tools) built specifically for it.

The claim in older lists that CakePHP "loads the whole application for every task" is not accurate today: classes are autoloaded on demand, and with OPcache and the ORM's metadata cache, request overhead is modest. CakePHP is a reasonable choice for data-heavy business applications and APIs; it is less suited to a team that wants a large plugin marketplace.

How to prepare

Build something small in CakePHP 5 before the interview: two related tables, a paginated list with sorting, a form with validation and an application rule, a login with the Authentication plugin and one policy, and a test for each. Then practise explaining the request path out loud, from webroot/index.php through the middleware queue to the controller, view and back. Interviewers care much more about that than about recalling every method name. If the job also involves the database, our MySQL 8.4 interview questions are a good companion, and PHP interview questions for 2026 cover the language itself.

Need a CakePHP 2, 3 or 4 application brought onto a supported stack without stopping the business? Cloudsoft Zone modernises legacy PHP applications in planned stages, with tests around the code before it changes.

Frequently asked questions

  • Which CakePHP version should I prepare for in 2026?

    CakePHP 5, currently 5.4 (5.4.3 was released on 3 October 2026). CakePHP 4 stopped receiving security fixes on 10 September 2026, so new work and most interviews focus on 5.x. If the role maintains an older app, also learn what changed between your version and 5.

  • Is CakePHP scaffolding still available?

    No. Runtime scaffolding was removed after CakePHP 2. Use the Bake plugin, for example bin/cake bake all Articles, which generates real code you can review and change.

  • What replaced AuthComponent in CakePHP 5?

    The official cakephp/authentication plugin for identifying users and cakephp/authorization for permissions through policies. AuthComponent was removed in CakePHP 5.0.

  • Does CakePHP have an afterFind callback?

    Not since CakePHP 3. Use beforeFind to change queries, and formatResults() or a custom finder to post-process results.

Advertise on CloudSoftZone

Your next customer could start right here.

Introduce your tool, product or business to readers exploring technology.

Advertise with us

Explore placements and request a private quote

Sources

  1. CakePHP 5 Book: Views — Cake Software Foundation
  2. CakePHP 5 Book: Caching — Cake Software Foundation
  3. CakePHP 5 Book: Routing — Cake Software Foundation
  4. CakePHP 5 Book: Request and Response Objects — Cake Software Foundation
  5. CakePHP 5 Book: Table Objects (lifecycle callbacks) — Cake Software Foundation
  6. CakePHP 5.4 Migration Guide — Cake Software Foundation
  7. cakephp/cakephp releases (5.4.3) — GitHub, 2026-10-03

Written with substantial AI assistance. Facts checked against cited sources. Editorial policy.

Comments

No comments yet. Be the first to join the conversation.

Leave a comment

Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.

Never published. Used only to contact you about this comment.

Loading the security check…

Comments are moderated before publication.