vendredi 9 octobre 2015

Unserialized object can't be passed from origin?

So I have a complex object which I wish to cache after creation as it is expensive to initialize. I'm able to reconstitute an instance within the class defining file but I need to be able to return the reconstituted instance in place of a new MyClass if my scheme is going to be of any use. (Don't I?)

Here's what I've done so far:

class PayPeriodService
{
    public $type;           // weekly,bi-weekly, semi-monthly, monthlly
    public $payday_first;
    public $close_first;
    public $hours_start;
    public $hours_end;
    public $length;         // in days
    public $periods;        // array of all periods this year
    public $dayInterval;
    public $oneWeekInterval;
    public $twoWeekInterval;
    public $semiFirstInterval;
    public $monthInterval;
    public $initialYear;
    public $today;          // date object

    public function __construct()
    {
        if( Redis::exists('pay-period-instance')) {
            Log:info( 'Fetching Pay-Period from cache.');
            $instance = json_decode(Redis::get('pay-period-instance'));
//            var_dump( $instance );
//            exit();
            return $instance;
        }
        return $this->init();
    }


    public function init()
    {
        Log::info('Reconstituting Pay-Period from primitive definition.');

        $ppdef = PayPeriod::all()->last();
        // etc etc etc, setting up all the properties, loading arrays etc

        // finally I cache the object 
        Redis::set('pay-period-instance', json_encode($this));
        return $this;
    }
}

So when I instantiate this class, with $ppsvc = new PayPeriodService; in another class, the $instance variable in the PayPeriodService file is valid and fully reconsituted, fully functional. But the returned instance in $ppsvc is a mindless zombie shell of what it ought to be: no instance data, no methods.

What is the magic I need to invoke to get the restored object to travel abroad as it needs must do? I have explored the Serializable interface, and tried with un/serialize in place of the json_encode/decode with no significant change to my problem.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire