LoginSignup
2
1

More than 3 years have passed since last update.

CakePHP4 のエンティティでテーブルを使う

Last updated at Posted at 2020-07-23

環境

  • CentOS 6
  • PHP 7.2
  • CakePHP 4.1.0

やりたかったこと

エンティティの中でテーブルオブジェクトを扱いたかっただけなんですけどね…。CakePHP3 系で使っていた TableRegistory が非推奨のようで、PhpStorm で打ち消し線を引かれてて (´・ω・`) となったので、ちゃんと推奨されたの使いたいな、と思っただけです。ほぼ自分用メモ。

結論

Cake\ORM\Locator\LocatorAwareTrait を使うそうです。

ちなみに、Docs には

Deprecated:
4.1.0 Use \Cake\ORM\Locator\LocatorAwareTrait::getTableLocator() or \Cake\Datasource\FactoryLocator::get('Table') to get the table locator instance instead.

とありました。
どっちでもいいんですな。

今回は Cake\ORM\Locator\LocatorAwareTrait を使ってみます。


namespace App\Model\Entity;

use Cake\ORM\Entity;
use Cake\ORM\Locator\LocatorAwareTrait; # これが必要

class Hoge extends Entity
{

    use LocatorAwareTrait; # これが必要

    public function fuga()
    {

        $table = $this->getTableLocator()->get('TableName');
        .
        .
        .

    }
    .
    .
}

現時点(2020/07/23) の本家日本語ドキュメントでは CakePHP3 での使い方がそのまま載っているようでした。
英語の方にはきちんと新しい方の使い方が載ってました。そんなんあるんかい………\(^o^)/

▼本家 CookBook [ Entities -4.x- ]
https://book.cakephp.org/4/en/orm/entities.html#namespace-Cake\ORM

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