Hi everyone,
There is more than likely a better way to achieve what I want, by all means, please suggest an alternative method - I'm all ears.
I use afterUpdate to trigger a request to an external API. This trigger can be disabled via a private model property. As you can see in the "renameBreed" method I call $this->update() which will save the breed model to save in the "_postSaveRelated" method in \Phalcon\Mvc\Model. Because Phalcon does a findFirst to re-retrieve the relationship, it creates a new instance of the model meaning the value of any private properties are reset.
I've tried model caching hoping it would help preserve this but it still seems to cache only the data (obvisously of only public properties). The cache is started prior to "intialize" as well - so any userland data transformation is lost. If it were by reference then this would let us work around that. Unfortuntaly you can't save objects by reference if they have magic methods :|
Effectively, what I'm asking for is a way to retrieve the same object when you get a relation;
$dog = \Dog::findFirst();
var_dump(spl_object_hash($dog->breed), spl_object_hash($dog->breed));
My way of trying to get around this problem is without doubt the wrong approach. So if some kind soul can suggest a better way around naviating my problem that'd be wonderful. I feel like events might be a good place to start but I haven't used them enough to know if it's the right place to start.
Thanks everyone :)
$dog = \Dog::findFirst();
$dog->renameBreed('potato');
class Base extends \Phalcon\Mvc\Model
{
public $id;
public function initialize()
{
$this->useDynamicUpdate(true);
$this->keepSnapshots(true);
$this->setReadConnectionService('db');
$this->setWriteConnectionService('db');
$eventsManager = $this->getDI()->getShared('eventsManager');
$eventsManager->attach('model', function($event, $model) {
return true;
});
$this->setEventsManager($eventsManager);
unset($eventsManager);
}
}
class Dog extends \Base
{
public $name;
public $breed_id;
private $localUpdate = false;
public function initialise()
{
$this->hasOne('breed_id', 'Dog/Breed', 'id', ['alias' => 'breed']);
}
public function renameBreed($breedName)
{
$breed = $this->breed;
$breed->localUpdate(); // Only update locally
$breed->name = $breedName;
return $this->update();
}
}
namespace Dog;
class Breed extends \Base
{
public $name;
private $localUpdate = false;
public function localUpdate()
{
$this->localUpdate = !$this->localUpdate;
}
public function afterUpdate()
{
if (!$this->localUpdate) {
// Update dog breed at animal registry
// Or just do stuff
}
}
}