LoginSignup
5
4

More than 5 years have passed since last update.

プロパティにアクセスするとAPIからデータを取得して使うようなModelを作るプラクティス

Last updated at Posted at 2014-02-23

例えばデータベースにTwitterIDが入っているとする。

Twitterのscreen_nameは自由に変更可能だから、DBには保存せずにAPIから取得するようにして、キャッシュが切れたら勝手に更新されるようにしたい。というケースの時。

FuelPHPでORMモデルを使った時はこういうふうに書ける。

例えばUser_ModelにORMの設定を書いて、以下のようなGetterを書く。

<?php
    protected static $_twitter = array();

    public function twitter() {
        if(!static::$_twitter[$this->twitter_id]) {
            static::$_twitter[$this->twitter_id] = \Model_Twitter::getStatus($this->twitter_id);
        }

        return static::$_twitter[$this->twitter_id];
    }

    public function & __get($property) {
        if($property == 'twitter') {
            return $this->twitter();
        }

        return parent::__get($property);
    }

Model_Twitterでは、APIからユーザーのステータスを返すようなコードを適宜書いておく。

そんで、ControllerやViewから以下のようにプロパティアクセスすると、必要な時だけAPIをコールするようになる。

Hello, <?php echo \Model_User::find($user_id)->twitter->screen_name; ?>!

もちろん、Model_Twitter側ではmemcachedやRedis等を使ってAPIレスポンスをキャッシュしておく。

5
4
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
5
4