Umi Blog
ウミブログ
Drush 9 からカスタムのDrushコマンドの追加は.incファイルではなく、クラスによって追加されるようになりました。
Drupal 8.4.x 以上のバージョンでは、Drush 9.xだけをサポートしているので、カスタムDrushコマンドの追加方法は把握しておくべきと言えるでしょう。
カスタムDrushコマンドは作成するには、カスタムモジュールディレクトリにdrush9_exampleファルダを作成後、次の4つのファイルを作成しましょう。
name: Drush 9 Commands Example
description: Provides examples for writing custom Drush 9 commands.
core: 8.x
type: module
package: Examples
services:
drush9_example.commands:
class: \Drupal\drush9_example\Commands\Drush9ExampleCommands
tags:
- { name: drush.command }
モジュールの場合、通常はservices.ymlを使用しますが、カスタムDrushコマンドの場合、drush.services.ymlを使用します。
もしservices.ymlを使用すると、エラーが発生します。
Fatal error: Class 'Drush\Commands\DrushCommands' not found in Drush9ExampleCommands
{
"name": "drupal/drush9_example",
"description": "A example module for Drush 9 commands.",
"type": "drupal-module",
"autoload": {
"psr-4": {
"Drupal\\drush9_example\\": "src/"
}
},
"extra": {
"drush": {
"services": {
"drush.services.yml": "^9"
}
}
}
}
drush.services.ymlは正しく動作させるために、composer.json内で宣言されている必要があります。
Drushのバージョン毎に、複数のdrush.services.ymlを宣言することも可能です。
Drush 9 でcomposer.jsonに明示的にサービスファイルを定義することは、必須ではありません。もしファイルが定義されていなければ、デフォルトのdrush.services.ymlが呼び出されます。
しかしDrush 10 以降ではcomposer.json内に定義されていることが必須になりましたので、Drush 9 でも宣言しておくことをオススメします。
srcフォルダを作成し、その中にファイルを作成してください。<?php
namespace Drupal\drush9_example\Commands;
use Drush\Commands\DrushCommands;
/**
* A Drush commandfile.
*
* In addition to this file, you need a drush.services.yml
* in root of your module, and a composer.json file that provides the name
* of the services file to use.
*/
class Drush9ExampleCommands extends DrushCommands {
/**
* Echos back hello with the argument provided.
*
* @param string $name
* Argument provided to the drush command.
*
* @command drush9_example:hello
* @aliases d9-hello
* @options arr An option that takes multiple values.
* @options msg Whether or not an extra message should be displayed to the user.
* @usage drush9_example:hello akanksha --msg
* Display 'Hello Akanksha!' and a message.
*/
public function hello($name, $options = ['msg' => FALSE]) {
if ($options['msg']) {
$this->output()->writeln('Hello ' . $name . '! This is your first Drush 9 command.');
}
else {
$this->output()->writeln('Hello ' . $name . '!');
}
}
}
使用されているアノテーションの使い方を見ていきましょう。
設定は以上になります。
shell=
drush en -y drush9_example
drush cr
と実行し、カスタムコマンドが実行できることを確認してみましょう。
説明は以上になります。ありがとうございました。
小さなご意見も、私たちにとっては大きなヒントです!
ぜひ率直なご感想をお寄せください
この

Masters of Drupal Engineering.
人に、