Skip to content

Auto-wire controller constructor dependencies in 6.x #19827

Description

@delamux

Description

In 6.x the container auto-wires by default, so ControllerFactory::create() checks hasDefinition() instead of has(). #19696 restored auto-wiring for action arguments and commands, but controller constructors were left out on purpose.

The result is that a controller like this one fails with an ArgumentCountError unless you register it by hand in Application::services():

    class ArticlesController extends AppController
    {
        public function __construct(
            ServerRequest $request,
            private readonly ArticlesTable $articles,
            ?ComponentRegistry $components = null,
        ) {

The result is that a controller like this one fails with an ArgumentCountError unless you register it by hand in Application::services():

    class ArticlesController extends AppController
    {
        public function __construct(
            ServerRequest $request,
            private readonly ArticlesTable $articles,
            ?ComponentRegistry $components = null,
        ) {
            parent::__construct($request, components: $components);
        }
    }

In 5.x you could get this working by adding the ReflectionContainer delegate, but in 6.x there is no simple way, you need to define every controller in the container.

My proposal is that when the controller is not defined in the container, the factory resolves only the required class-typed constructor parameters from the container. The request and the component registry are passed like today, and optional parameters keep their default value, so existing controllers receive exactly the same arguments as before. The controller itself is still built with reflection, not with container->get(), so nothing new can be created from the URL.

CakePHP Version

6.0

Activity

  1. added this to the 6.0 milestone on Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions