I've a shared $sdk object reference (it's Facebook PHP SDK) between many objetcs. I need to save the access token at very beginning of a function call and restore after $this->sdk->api call. See for example getAlbums() function.
How can automatically execute a callback before/after every function call on every FBItem instance?
abstract class Item { protected $id, $sdk, $auth; public function __construct(Facebook $sdk, $auth = null) { $this->sdk = $sdk; $this->auth = $auth; } public function getAlbums() // Require access token change { // Am i FBUser or FBPage? Call setAccessToken to set auth $backup = $this->sdk->getAccessToken(); $this->sdk->setAccessToken($auth ?: $backup); $as = array(); $rs = $this->sdk->api(sprintf('/%s/albums', $this->id)); foreach($rs['data'] as $i) $as[] = new Album($this->sdk, $this->auth); // Restore previous token backup $this->sdk->setAccessToken($backup); } } class User extends Item { $ps = array(); $rs = $this->sdk->api(sprintf('/%s/accounts', $this->id)); foreach($rs['data'] as $i) $ps[] = new Page($this->sdk, $i['access_token']); return $ps; } class Page extends Item { }