Skip to content

Instantly share code, notes, and snippets.

@EdwardBock
Last active May 18, 2021 12:36
Show Gist options
  • Save EdwardBock/c12b817dd1c4c2f89fa43c99cd954db2 to your computer and use it in GitHub Desktop.
Save EdwardBock/c12b817dd1c4c2f89fa43c99cd954db2 to your computer and use it in GitHub Desktop.
Repository for a service that fetches additional data to a post
<?php
namespace PublicFunctionOrg\WordPress;
class Repsitory {
public function __construct($service){
$this->service = $service; // service api implementation class
}
private function getTransientKey($post_id){
return "my_data_key_$post_id";
}
private function getPostMetaKey(){
return "my_data_key";
}
public function getData($post_id){
// cached data
$data = get_transient($this->getTransientKey($post_id);
if(false !== $data) return $data;
// fetch fresh data from service
try{
$data = $this->service->fetch($post_id);
// update cache
set_transient($this->getTransientKey($post_id), $data, 60*5);
// update long-term cache
update_post_meta($post_id, $this->getPostMetaKey(), $data);
return $data;
} catch(\Exception $e){
error_log($e->getMessage());
// use long-term cache
$data = get_post_meta($post_id, $this->getPostMetaKey(), true);
if(false !== $data) return $data;
}
return new \WP_Error("Data not available");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment