0

How can I use a core classe in my ORM Model ?

Is working:

protected static $_properties  = array(
    'id',
    'user_id',
    'v_key' => array('default' => 'abc' ),
    'a_key' => array('default' => 'def' ),
    'created_at',
    'updated_at'
);

Isn't working:

protected static $_properties  = array(
    'id',
    'v_key' => array('default' => Str::random('alnum', 6) ),
    'a_key' => array('default' => Str::random('alnum', 6) ),
    'created_at',
    'updated_at'
);

The error

Thanks!!

Allan Stepps
  • 1,047
  • 1
  • 10
  • 23

3 Answers3

1

Your actual problem here is that you can't perform function calls when making static assignments in PHP. How to initialize static variables

Community
  • 1
  • 1
Emlyn
  • 852
  • 6
  • 16
  • A common work around for this is to use fuel's `_init()` method to set up "static" variables, so set an empty value for your default then do something like `static::$_properties['v_key']['default'] = Str::random()` – Emlyn Mar 24 '14 at 07:00
  • Is it _syntaxically_ right to override parameters like that? What do you think of using an observer "after_create" ? – Allan Stepps Mar 24 '14 at 12:54
  • An observer would not work as you are assigning `static` properties their values. – Emlyn Mar 24 '14 at 17:25
0

Ok, I used an observer to do that.

/classes/observer/session.php

<?php

namespace Orm;

use Str;

class Observer_Session extends Observer {
  public function after_create(Model $session) {

    $session->v_key = Str::random('alnum', 6);
    $session->a_key = Str::random('alnum', 6);

  }

/classes/model/session.php

enter image description here

Allan Stepps
  • 1,047
  • 1
  • 10
  • 23
0

To dynamically set default values, you can override the forge method in your session model:

public static function forge($data = array(), $new = true, $view = null, $cache = true)
{

    $data = \Arr::merge(array(
        'v_key'      => \Str::random('alnum', 6),
        'a_key'      => \Str::random('alnum', 6),
    ), $data);

    return parent::forge($data, $new, $view, $cache);

}
julesj
  • 754
  • 4
  • 10