Skip to main content

custom ControllerBase

Displaying 1 - 1 of 1

drupal10, when do I need to implement __construct in custom controllerBase

You implement __construct() in your custom ControllerBase when you need to bring in any external service or object that isn't provided as a convenience method by ControllerBase itself. Always pair it with the create() static factory method for proper dependency injection in Drupal.

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Custom controller that demonstrates dependency injection.
 */
class MyCustomController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * The logger factory service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $loggerFactory;

  /**
   * Constructs a new MyCustomController object.
   *
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   * The logger factory service.
   */
  public function __construct(LoggerChannelFactoryInterface $logger_factory) {
    $this->loggerFactory = $logger_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.factory') // Request the 'logger.factory' service
    );
  }

  /**
   * Displays a custom page.
   */
  public function myPage() {
    $this->loggerFactory->get('my_module')->notice('My custom page was accessed.');

    return [
      '#markup' => $this->t('Welcome to my custom page with logging!'),
    ];
  }

}