Search code examples
phpormredbean

RedBean returns null when unboxing model from bean?


I can't get the box() method to work, I only get NULL from it.

For example if I do this

$bean = \R::load('comment', 2);

print("\n\nBEAN:\n");
var_dump($bean);

$model = $bean->box();

print("\n\nMODEL:\n");
var_dump($model);

I get this

BEAN:
class RedBeanPHP\OODBBean#68 (10) {
  protected $properties =>
  array(4) {
    'id' =>
    string(1) "2"
    'user' =>
    string(1) "2"
    'reply_to' =>
    NULL
    'message' =>
    string(30) "Test comment 1"
  }
  protected $__info =>
  array(4) {
    'type' =>
    string(7) "comment"
    'sys.id' =>
    string(2) "id"
    'sys.orig' =>
    array(5) {
      'id' =>
      string(1) "2"
      'user' =>
      string(1) "1"
      'reply_to' =>
      NULL
      'message' =>
      string(30) "Test comment 1"
    }
    'tainted' =>
    bool(false)
    'changed' =>
    bool(false)
  }
  protected $beanHelper =>
  class RedBeanPHP\BeanHelper\SimpleFacadeBeanHelper#17 (0) {
  }
  protected $fetchType =>
  NULL
  protected $withSql =>
  string(0) ""
  protected $withParams =>
  array(0) {
  }
  protected $aliasName =>
  NULL
  protected $via =>
  NULL
  protected $noLoad =>
  bool(false)
  protected $all =>
  bool(false)
}


MODEL:
NULL

Clearly there is data in the bean, so why does box() return NULL?


Solution

  • Seems it was a namespacing problem.

    The documentation says that

    If you like your models to reside in the namespace \Model, you can set the following constant:

       //with namespace Model
       define( 'REDBEAN_MODEL_PREFIX', '\\Model\\' )
    

    You can now create a model class like this:

       class \Model\Band extends \RedBeanPHP\SimpleModel { ... }
    

    The phrasing "... you can set ..." led me to believe that it's optional. However, it turns out that if you like your models to reside in the namespace \Model, and you want to be able to use FUSE methods, you MUST set the above constant and you MUST call your model class Band.

    Also, note that you MUST use double backslashes (\\) everywhere when you define that namespace string.

     

    To add to the confusion, right before the above documentation paragraph, there is a paragraph saying

    RedBeanPHP automatically connects beans with models using a naming convention (i.e. Model_{TYPE OF BEAN}).

    Apparently, you should use the naming convention Model_Band when NOT using namespaces, and the naming convention Band when you do, or things break down.