LoginSignup
1
3

More than 1 year has passed since last update.

PHPDocによる型情報の補足

Last updated at Posted at 2022-05-16

PHPDocとは?

PHPDocとはコードに詳細な情報を記述することができる、特別な種類のコメント文です。

これを書くことで下記のメリットがあります。

  • 型チェックされる。(予期しない値が渡されないか確認できる)
  • IDEで補完が効きやすくなる。
  • 静的解析がより正確に実行できる。(PHPStan 等)

タグの説明

  • propaty
    各クラスでModelクラスや別クラスを呼びだしている場合に必要。
    また、定義しないと未定義のプロパティとなり、アクセスできない。

  • param、return
    引数、戻り値の情報を記載するためのタグ。

  • var
    変数、オブジェクトのプロパティの情報を記述する。

  • method
    クラスのメソッドに関する情報を補足する。
    マジックメソッドなどアクセス不可なものを保管する。
    (例)findBy、findAllBy等

開発環境

  • PHP 7.4.12
  • CakePHP 4.2.5

サンプルコード

MainController.php
/**
 * ○○デフォルトページ用のコントローラーのファイル
 *
 * @property \App\Model\Table\ArticlesTable $Articles
 */
class MainController extends AppController
{
	/**
	 * メインページ
	 *
	 * @return void
	 */
	public function index(): void
	{
		$this->loadModel('Articles');

		$date = $this->Articles->findDate(id: 1, inputDate: new FrozenDate());
	}
    /**
     * サンプル
     *
     * @return void
     */
    public function sample(): void
    {
        try {
            /** @var string|false $foo */
            $foo = json_encode([1, 2]);
            if ($foo === false) {
                throw new Exception('Exception発生');
            }
            /** @var string $foo */
            $this->test($foo);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}
ArticlesTable.php
/**
 * @method \Cake\ORM\Query findById(int $id)
 * @method \Cake\ORM\Query findAllById(int $id)
 */
class ArticlesTable extends AppTable
{
	/**
	 * イニシャライズ
	 *
	 * @param array $config コンフィグ
	 * @return void
	 */
	public function initialize(array $config): void
	{
		parent::initialize($config);

		$this->setTable('articles');
		$this->setEntityClass('App\Model\Entity\Article');
		$this->setPrimaryKey('id');
	}

	/**
	 * データを取得
	 *
	 * @param int $id Id
	 * @param \Cake\I18n\FrozenDate $inputDate 日付
	 * @return \App\Model\Entity\Article|null データ
	 */
	public function findDate(int $id, FrozenDate $inputDate): ?Article
	{
		return $this->find()
			->where([
				"{$this->getAlias()}.id" => $id,
				"{$this->getAlias()}.input_date" => $inputDate,
			])
			->first();
	}
}

VSCodeでは、このように関数が表示される

スクリーンショット 2022-05-16 164533.png
スクリーンショット 2022-05-17 085256.png

最後に

型の指定を明確にすると、可読性が各段と上がるため、
開発の際は、ぜひ活用してみてください。

1
3
1

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
1
3