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?

Laravelでのアノテーションの書き方ミスについて

Posted at

はじめに

とあるwebシステムでLaravelを10から11にアップグレードする際、lint-testにて以下のようなエラーが出ました。その際にアノテーションで型指定をより明確にして解決しようとしたのですが、アノテーションの書き方で凡ミスがあったので繰り返さないようにここに記しておこうと思います。
*以下のエラーの対処法の記事ではありません。

Method App\Models\Sample::files() return type with       
generic class Illuminate\Database\Eloquent\Relations\HasMany does not  
specify its types: TRelatedModel, TDeclaringModel

アノテーションの書き方ミス

以下のコードで、sampleTest()の戻り値に対してアノテーションを記述したのですが、うまくいきませんでした。原因は、メソッド内にアノテーションを記述してしまったこと。

  public function sampleTests(): HasMany
    {
       /**
       * @return HasMany<SampleTest, $this>
       */
        return $this->hasMany(SampleTest::class);
    }

通常アノテーションはメソッドの戻り値や引数の説明に用いられるもので、メソッド本体内に記述しても、アノテーションを解析するツールがメソッドの戻り値として扱ってくれないようです。そのため、以下のようにメソッド外にアノテーションを記述して、アノテーションがメソッド全体に対して説明することで、メソッドの戻り値の型を正しく解釈できるようです。

    /**
    * @return HasMany<SampleTest, $this>
    */
    public function sampleTests(): HasMany
    {
        return $this->hasMany(SampleTest::class);
    }

あとがき

アノテーションとは、PHPのフレームワークであるLaravelにおいてはPHPDoc(PHPで使用される特定形式のドキュメントコメント)と言うようですね。他の言語やフレームワークでは、また別の構文のようです。また一つ、学ぶことができました。

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?