0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Drupal Entity API ハンズオン:Drushコマンドで記事データを取得・保存してみる

0
Posted at

はじめに

画面表示のロジックを書いて、画面を表示して動作確認することの多い Drupal ですが、データ取得の処理を試してみるには Drush コマンドが非常に適していると思いました。

画面表示の処理を書く場合も、同様にデータ取得・保存などの処理は行います。しかし、表示や出力周りの処理に気を取られ、データ処理そのものの把握が難しくなることがあります。

Drush コマンドを作ることで、出力をシンプルに保ちつつ、データ取得・保存の処理だけを切り出して確認できます。

そこで本記事では、Drush コマンドを作成し、Drupal の Entity API を利用したデータ取得・保存の挙動を確認します。

※ Entity API は取得・保存だけを指すものではありませんが、本記事では説明を簡単にするため、主に Entity の取得・更新・保存を扱う API 群という意味で使用します。

今回作るもの

次のコマンドを作成します。

drush study:articles

実行すると、公開済みの Article コンテンツを取得し、Node ID とタイトルを表示します。

1 : Hello Drupal
2 : Acquia Study
3 : Entity API

環境

  • Drupal 11

Drush コマンド作成

ディレクトリ構成

学習用のカスタムモジュールとして、study_module を作成します。

modules/custom/study_module/
├── study_module.info.yml
├── drush.services.yml
└── src/
    └── Commands/
        └── StudyCommands.php

Composer 構成によって Drupal のドキュメントルートが web/ の場合は、次の場所になります。

web/modules/custom/study_module/

study_module.info.yml

モジュールの基本情報を定義します。

name: Study Module
type: module
description: Drupal Entity API study module.
package: Custom
core_version_requirement: ^11

ファイル名は次のとおりです。

study_module.info.yml

drush.services.yml

Drush にコマンドクラスを登録し、entity_type.manager サービスを注入します。

services:
  study_module.commands:
    class: Drupal\study_module\Commands\StudyCommands
    arguments:
      - '@entity_type.manager'
    tags:
      - { name: drush.command }

arguments に指定した @entity_type.manager が、コマンドクラスのコンストラクタへ渡されます。

StudyCommands.php

<?php

namespace Drupal\study_module\Commands;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drush\Commands\DrushCommands;

final class StudyCommands extends DrushCommands {

  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {
    parent::__construct();
  }

  /**
   * Display published articles.
   *
   * @command study:articles
   * @aliases sa
   */
  public function articles(): void {
    $storage = $this->entityTypeManager->getStorage('node');

    $nids = $storage
      ->getQuery()
      ->condition('type', 'article')
      ->condition('status', 1)
      ->accessCheck(FALSE)
      ->execute();

    if ($nids === []) {
      $this->output()->writeln('No published articles found.');
      return;
    }

    $nodes = $storage->loadMultiple($nids);

    foreach ($nodes as $node) {
      $this->output()->writeln(
        sprintf('%d : %s', $node->id(), $node->label()),
      );
    }
  }

}

モジュールを有効化する

Drupal にモジュールを認識させるため、キャッシュを再構築します。

drush cr

モジュールを有効化します。

drush en study_module -y

モジュールが有効になったことを確認します。

drush pml --status=enabled | grep study_module

Drush コマンドを確認する

コマンド一覧から、作成したコマンドを確認します。

drush list | grep study

次のように表示されれば、コマンドの登録は成功です。

study:articles    Display published articles.

コマンドを実行する

drush study:articles

出力例です。

1 : Hello Drupal
2 : Acquia Study
3 : Entity API

遊ぶ

記事作ってみます。

image.png

tarohida@drupal-lab-web:/var/www/html$ drush study:articles
3 : Q
4 : i
5 : i
6 : t
7 : a

drush コマンドの処理を書き換えて、実行のたびに記事タイトル末尾の文字を複製して保存するようにします。

      $node->set('title', $node->label() . mb_substr($node->label(), -1));
      $node->save();

できました。

tarohida@drupal-lab-web:/var/www/html$ drush study:articles
3 : Q
4 : i
5 : i
6 : t
7 : a
tarohida@drupal-lab-web:/var/www/html$ drush study:articles
3 : QQ
4 : ii
5 : ii
6 : tt
7 : aa
tarohida@drupal-lab-web:/var/www/html$ drush study:articles
3 : QQQ
4 : iii
5 : iii
6 : ttt
7 : aaa

管理画面側も更新されています。

image.png

こうやって触ると、なんか単純なものに感じてこないでしょうか。

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?