Thursday, August 17, 2023

How to created the services in drupal 10

 Step 1. Create service file and add the class as service

Example : mymodule.services.yml

services:

  mymodule.custom_services:

    class: Drupal\mymodule\CustomService

    arguments: ['@current_user']

Step 2. Create the service Class

Example: src/CustomService.php

<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\AccountInterface;

/**

 * Class CustomService

 * @package Drupal\mymodule\Services

 */

class CustomService {

  protected $currentUser;


  /**

   * CustomService constructor.

   * @param AccountInterface $currentUser

   */

  public function __construct(AccountInterface $currentUser) {

    $this->currentUser = $currentUser;

  }

  /**

   * @return \Drupal\Component\Render\MarkupInterface|string

   */

  public function getData() {

    return $this->currentUser->getDisplayName();

  }

}

Step 4: Now you can call your service from other modules.

Example how to call service in hook__preprocess_node():

<?php

/**
 *  run cron
 */
function mymodule_preprocess_node(&$variables){

  $data = \Drupal::service('mymodule.custom_services')->getData();
  var_dump($data);
}

Step 2. Create the Controller Class

Example: src/Controller/MyController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\DependencyInjection\ContainerInterface;

use Drupal\mymodule\CustomService;


class MyController extends ControllerBase

{

 /**

   * The data services.

   *

   * @var Drupal\mymodule\CustomService;

   */

 protected $info_data;


 public function __construct(CustomService $info_data)

  {

    $this->info_data = $info_data;

  }

 /**

   * {@inheritdoc}

   */

  public static function create(ContainerInterface $container)

  {

    return new static(

        $container->get('mymodule.custom_services')

    );

  }

/**

   * Builds the response.

   */

  public function information()

  {

    $info = $this->info_data->getData(); //First way using DependencyInjection 

    $data = \Drupal::service('mymodule.custom_services')->getData(); // Second way using service 

    $build['content'] = [

      '#markup' => 'hi this is test',

    ];

    return $build;

  }

}

module.routing.yml module.test: path: '/test' defaults: _title: 'Example' _controller: '\Drupal\module\Controller\MyController::information' requirements: _permission: 'access content' }


No comments:

Post a Comment

If you have any problem please let me know.