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?

【PHPフレームワークFlow】createQueryForTypeを使ってRepositoryなしでデータ取得する方法

Posted at

初めに

FlowではRepositoryを作成していないDomainモデルを取得元にしたデータ取得はできないと思っていました。取得する際は無理やりJOINしたり、FlowではなくDoctrineの機能を用いて取得をしていたのですが、createQueryForType()を使えばRepositoryがなくてもデータ取得ができるようです。
今回はcreateQueryForType()の簡単な使い方を紹介したいと思います。

createQueryForTypeとは

createQueryForType()PersistenceManagerクラスのメソッドの一つです。
引数で指定したDomainモデルのQueryを作成することができます。

createQueryForTypeメソッドのインターフェース
interface PersistenceManagerInterface
{
    /**
     * Return a query object for the given type.
     *
     * @param string $type
     * @return QueryInterface
     * @api
     */
    public function createQueryForType(string $type): QueryInterface;
}

使い方も簡単で、Queryを作成した後はいつも通り条件を指定してexecute()するだけでデータ取得ができます。

createQueryForType()の使い方
$query = $this->persistenceManager->createQueryForType(Employee::class);
$result = $query->matching(
    $query->greaterThanOrEqual('age', 20)
)->execute()->toArray();

使いどころ

Repositoryがない時Domainモデルのデータを取得したい際などに役立ちます。
それだけのためにわざわざRepositoryを作成するのもなぁって時は利用する価値があるかもしれません。

終わりに

今回はcreateQueryForType()について解説しました。
便利ですが、使うとしたらRepository以外かと思うので、責務的にどうかみたいなのは考えたほうがいいかもしれないですね。個人的にはFlilter感覚で使えるのは便利だなと思いました。

ここまでお読みいただきありがとうございました!

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?