LoginSignup
0
0

More than 5 years have passed since last update.

【FuelPHP】users.profile_fieldsの情報を、取得済みのインスタンスから得る[unserialize]

Posted at

完全勝利。

助けていただいた記事

PHPの関数unserializeでエラーが発生する場合の対処方法 | cms helog - CMS構築を目的にPHPをベースとしたWordPress、CakePHPやPEARなどオープンソースを中心に解説しています

結論

html_entity_decode()をしよう。


/**
 * 文字コードエラーが出ないようにunserializeする
 * @param $string unserializeしたい文字列
 * @return mixed
 */
function safe_unserialize($string)
{
    return unserialize(html_entity_decode($string, ENT_QUOTES));
}

/**
 * usersテーブルから取得したインスタンスのprofile_fieldsにある特定情報を返す
 * @param $user Model_User::find()の返り値
 * @param $field profile_fieldsの中から欲しい情報
 * @return array|mixed
 */
function get_field_from_user($user, $field)
{
    if (isset($user['profile_fields']))
    {
        is_array($user['profile_fields']) or $user['profile_fields'] = (@safe_unserialize($user['profile_fields']) ?: array());
    }
    else
    {
        $user['profile_fields'] = array();
    }
    return is_null($field) ? $user['profile_fields'] : \Arr::get($user['profile_fields'], $field);
}

呼び出す際は

$users = Model_User::find('all');
foreach ($users as $user)
{
    echo $user->username."(".get_field_from_user($user, 'age').")<br>";
}
/*
 * Bob(30)
 * John(12)
 * ...
 */

のように使えば良い。

ネットによく広まっている方法

もともとそのままunserializeしたかったがエラーを吐かれてしまったので調べたところ、最も多かったのは

  • sereializeした後にbase64_encode()
  • unsereializeする前にbase64_decode()

という方法。
しかしModelsave()やらAuth::update_user()やらを直接いじるわけにいかないし、Auth::get($profile)みたいにやると、既に取得していてももう一回取らないといけないしなぁー…と思っていろいろ調べていたところ、この方法を発見した。

環境

一応ではあるが自分の環境を軽く書くと

  • PHP5.3
  • FuelPHP 1.7
  • AuthパッケージはSimpleAuth、usersテーブルは公式ドキュメントに基づいた構成

と言った感じである。

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