2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP + Slim Framework + PHPActiverecord + Twig な環境で Relations を使えるようにする

Posted at

自分用メモ。

PHP + Slim + PHPActiverecord + Twig で以下のような環境。

Hoge.php
<?php
class Hoge extends ActiveRecord\Model
{
    static $belongs_to = array(
        array('Fuga'),
    );
}
?>
Fuga.php
<?php
class Fuga extends ActiveRecord\Model
{
}
?>
test.php
<?php
$app = new ¥Slim¥Slim();

$app->get('/', function() use ($app) {
    $hoge = new ¥Hoge();
    $app->render('hoge.twig', array('hoge' => $hoge));
});

$app->run();
?>
hoge.twig
<html>
<body>
{{ hoge.fuga.name }}
</body>
</html>

各種ライブラリをダウンロードしたままだと、

An exception has been thrown during the rendering of a template ("Call to undefined method: fuga") in "hoge.twig" at line 3.

というエラーになる

どうも、公開状態のままでは、Associates にうまく対応できていないみたい。
Stable(2010/06/27) はそこそこ古い状態なのでしょうがないかな。
Nightly Build(2013/04/13) も古いけどw

で、PHPActiverecord を一部書き換えて、エラーを回避する。

MyModel.php
class MyModel extends ActiveRecord¥Model
{
    public function __isset($attribute_name)
    {
        if (array_key_exists($attribute_name, $this->attributes))
            return true;

        if (array_key_exists($attribute_name, static::$alias_attribute))
            return true;

        if (method_exists($this, "get_${attribute_name}"))
            return true;

        if (static::table()->has_relationship($attribute_name))
            return true;

        return false;
    }
}
Hoge.php
<?php
class Hoge extends MyModel
<後略>
?>
Fuga.php
<?php
class Fuga extends MyModel
<後略>
?>

今回のような環境を利用しているなら、すでに対応済みだと思うけど。
自分でハマったのでメモ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?