How to pass argument in callback function in php? -
i have repository class method follows:
public function getone($id){ $method = __method__; $post = null; $post = $this->cachemanager($method, function($id) { return db::select("select * posts id = ?", [$id]); }); return $post; }
i want cache result, in closure/callback function $id parameter not working. cachemanager trait i'm using in repository.
public function cachemanager($method, $fn) { $obj = null; if(!$this->hascache($method)){ $obj = $fn(); } else { $obj = $this->getcache($method); } return $obj; }
i have other methods without parameters , they're working intended.
use use
. :d
with use
clause, can import variables parent scope scope of function.
public function getone($id){ $method = __method__; $post = null; $post = $this->cachemanager($method, function() use ($id) { return db::select("select * posts id = ?", [$id]); }); return $post; }
just side note. since looks building caching mechanism, need include id in cache well. check $method
, each id have different cache entry may or may not exist. think in function need line below make cache key more unique. call parameter $method
$cachekey
instead, since cache shouldn't linked method name per se.
$method = __method__ . ";$id";
Comments
Post a Comment