本文整理汇总了PHP中Cache::add方法的典型用法代码示例。如果您正苦于以下问题:PHP Cache::add方法的具体用法?PHP Cache::add怎么用?PHP Cache::add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cache
的用法示例。
在下文中一共展示了Cache::add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: returnRoutes
public static function returnRoutes($prefix = null)
{
$dics_for_cache = ['projects', 'types'];
foreach ($dics_for_cache as $dic_name) {
## Refresh dics cache
#Cache::forget('dic_' . $dic_name);
$dic_[$dic_name] = Cache::get('dic_' . $dic_name);
if (!$dic_[$dic_name]) {
Cache::forget('dic_' . $dic_name);
$dic_[$dic_name] = Dic::valuesBySlug($dic_name, function ($query) {
$query->orderBy('lft', 'ASC');
}, ['allfields', 'alltextfields'], true, true, true);
#Helper::d($dic_name); Helper::ta($dic_{$dic_name}); #die;
$dic_[$dic_name] = DicLib::loadImages($dic_[$dic_name], ['avatar', 'image', 'logo', 'photo', 'header_img']);
#Helper::d($dic_name); Helper::ta($dic_{$dic_name}); #die;
Cache::add('dic_' . $dic_name, $dic_[$dic_name], self::$global_cache_min);
}
View::share('dic_' . $dic_name, $dic_[$dic_name]);
#Helper::d($dic_name); Helper::ta($dic_{$dic_name});
}
#Helper::tad($dic_{'city'});
#die;
Route::group(array('prefix' => '{lang}'), function () {
Route::any('/project/{slug}', array('as' => 'app.project', 'uses' => __CLASS__ . '@appProject'));
#Route::any('/ajax/send-message', array('as' => 'ajax.send-message', 'uses' => __CLASS__.'@postSendMessage'));
#Route::any('/ajax/some-action', array('as' => 'ajax.some-action', 'uses' => __CLASS__.'@postSomeAction'));
});
Route::group(array(), function () {
#Route::any('/ajax/send-message', array('as' => 'ajax.send-message', 'uses' => __CLASS__.'@postSendMessage'));
#Route::any('/ajax/some-action', array('as' => 'ajax.some-action', 'uses' => __CLASS__.'@postSomeAction'));
});
}
示例2: searchTitle
/**
* Search for movie title
*
* @param string $q The search query
*
* @return Response
*/
public function searchTitle($q)
{
// init result array
$result = array();
// trim query
$q = trim($q);
// create slug from query
$q_slug = str_slug('imdb-' . $q);
// check if search is in cache
if (\Cache::has($q_slug)) {
// retrieve item from cache
$item = \Cache::get($q_slug);
// add data to array
$result = array('fromcache' => true, 'data' => $item);
} else {
// url encode query
$q = urlencode($q);
// Use the Imdb Api to search for movie
$imdbResult = json_decode(file_get_contents(sprintf(env('IMDB_SEARCH_TITLE_URL'), $q)));
// only proceed if the most popular title array is filled and at least contains 1 movie
if (isset($imdbResult->title_popular) && is_array($imdbResult->title_popular) && count($imdbResult->title_popular) > 0) {
// extract year from title_description
$year = intval(substr($imdbResult->title_popular[0]->title_description, 0, 4));
// create object for this movie
$item = new ImdbMovie($imdbResult->title_popular[0]->id, $imdbResult->title_popular[0]->title, $year);
// add item to cache for a year
\Cache::add($q_slug, $item, 60 * 24 * 365);
// add data to array
$result = array('fromcache' => false, 'data' => $item);
}
}
// return json formatted response
return response()->json($result);
}
示例3: get_exchange_rates
public function get_exchange_rates()
{
// \Cache::forget('money_exchange_rates');
if (\Cache::has('money_exchange_rates')) {
$data = \Cache::get('money_exchange_rates');
} elseif (is_connected("openexchangerates.org")) {
$api_key = "bbc128aa6f3645d78b098f0eef3dd533";
$json = file_get_contents("http://openexchangerates.org/api/latest.json?app_id={$api_key}");
$json = json_decode($json, true);
$data['rates'] = $json['rates'];
$data['base'] = $json['base'];
// $data['json_rates'] = json_encode($json['rates']);
\Cache::add('money_exchange_rates', $data, 360);
\Cache::add('money_exchange_rates_default', $data, 50000);
} else {
$data = \Cache::get('money_exchange_rates_default');
}
$currency_list = \Lst::common('currency1');
$arr["site_name"] = "Ahmed-Badawy.com";
$arr["base"] = $data['base'];
foreach ($currency_list as $key => $val) {
$n = ['short' => $key, "name" => $val, "value" => $data['rates'][$key]];
$arr['rates'][$key] = $n;
}
return $arr;
}
示例4: _getDepartmentList
protected function _getDepartmentList()
{
if (Cache::has('departmentList')) {
return Cache::get('departmentList');
} else {
$list = DB::table('sectionmasters')->join('departmentmasters', 'departmentmasters.sectioncd', '=', 'sectionmasters.sectioncd')->select('departmentmasters.departmentcd as departmentcd', 'sectionmasters.sectionname as sectionname', 'departmentmasters.departmentname as departmentname')->get();
$expiresAt = Carbon::now()->addMinutes(10);
Cache::add('departmentList', $list, $expiresAt);
return $list;
}
}
示例5: institucion
public function institucion($categoria, $id = null)
{
$this->options['categoria'] = $categoria;
$this->options['id'] = $id;
Estructuras::setOptions($this->options);
$encabezado = Estructuras::getEncabezado();
if ($encabezado) {
$this->data = Estructuras::getEstructuraEncabezado($encabezado);
}
$response = ApiHelper::prepareResponse($this->data, 'institucion', $this->options, $this->total);
Cache::add(Request::getRequestUri(), $response, Config::get('cache.time'));
return $response;
}
示例6: crear_key
public function crear_key($datos, $results)
{
$datos = $this->sii->orderParamsToKeyCache($datos);
$keyToService = md5(json_encode($datos));
$response['key'] = $keyToService;
if (Cache::has($keyToService)) {
$response['data'] = Cache::get($keyToService);
} else {
Cache::add($keyToService, $results, $this->minutesToCache);
$response['data'] = $results;
}
return $response;
}
示例7: fire
public function fire($job, $data)
{
if (isset(app('veer')->cachedView) && config('veer.htmlcache_enable') == true && !auth_check_session()) {
$cache_url = cache_current_url_value();
$expiresAt = now(24, 'hours');
\Cache::has($cache_url) ?: \Cache::add($cache_url, app('veer')->cachedView->render(), $expiresAt);
} else {
return $job->release();
}
// leave it here
if (isset($data['repeatJob']) && $data['repeatJob'] > 0) {
$job->release($data['repeatJob'], 'minutes');
}
}
示例8: store
public function store(Request $request)
{
$title = $request->input('title');
$content = $request->input('content');
$post = ['title' => trim($title), 'content' => trim($content)];
$posts = Cache::get('posts', []);
if (!Cache::get('post_id')) {
Cache::add('post_id', 1, 60);
} else {
Cache::increment('post_id', 1);
}
$posts[Cache::increment('post_id', 1)];
Cache::put('posts', $posts, 60);
return redirect()->route('post.show', ['post' => Cache::get('post_id')]);
}
示例9: start
public static function start()
{
$key = static::getKey();
$start = microtime(true);
Cache::add($key, 0, static::$intervalSeconds);
register_shutdown_function('Firewall::end');
while (Cache::increment($key) > static::$concurrency) {
Cache::decrement($key);
if (!static::$spinLockSeconds || microtime(true) - $start > static::$intervalSeconds) {
http_response_code(429);
die('429: Too Many Requests');
}
usleep(static::$spinLockSeconds * 1000000);
}
}
示例10: manufacture
public function manufacture($classname, $id, $row = null)
{
// Check that the id is valid
if ((int) $id == 0) {
throw new \Exception('Invalid id');
}
// Set up the name for the factory array
$factory_array_name = "_{$classname}s";
$item = null;
// Set up the manufactured array if it doesn't exist
if (!isset($this->{$factory_array_name})) {
Logging::log("Setting up manufactured array for {$classname}");
$this->{$factory_array_name} = array();
}
// If the current id doesn't exist in the manufactured array, manufacture it
if (!array_key_exists($id, $this->{$factory_array_name})) {
// Initialize a position for the item in the manufactured array
$this->{$factory_array_name}[$id] = null;
try {
// Check if the class is cacheable as well
$cacheable = in_array($classname, array('TBGProject', 'TBGStatus', 'TBGPriority', 'TBGCategory', 'TBGUserstate'));
$item = null;
// If the class is cacheable, check if it exists in the cache
if ($cacheable) {
if ($item = Cache::get("TBGFactory_cache{$factory_array_name}_{$id}")) {
Logging::log("Using cached {$classname} with id {$id}");
}
}
// If we didn't get an item from the cache, manufacture it
if (!$cacheable || !is_object($item)) {
$item = new $classname($id, $row);
Logging::log("Manufacturing {$classname} with id {$id}");
// Add the item to the cache if it's cacheable
if ($cacheable) {
Cache::add("TBGFactory_cache{$factory_array_name}_{$id}", $item);
}
}
// Add the manufactured item to the manufactured array
$this->{$factory_array_name}[$id] = $item;
} catch (Exception $e) {
throw $e;
}
} else {
Logging::log("Using previously manufactured {$classname} with id {$id}");
}
// Return the item at that id in the manufactured array
return $this->{$factory_array_name}[$id];
}
示例11: initialize
/**
* @param string $template The name of the template to use for events. These are JSON files and reside in
* [library]/config/schema
*
* @throws InternalServerErrorException
* @return bool|array The schema in array form, FALSE on failure.
*/
public static function initialize($template = self::SCRIPT_EVENT_SCHEMA)
{
if (false !== ($eventTemplate = \Cache::get('scripting.event_schema', false))) {
return $eventTemplate;
}
// Not cached, get it...
$path = Platform::getLibraryConfigPath('/schema') . '/' . trim($template, ' /');
if (is_file($path) && is_readable($path) && false !== ($eventTemplate = file_get_contents($path))) {
if (false !== ($eventTemplate = json_decode($eventTemplate, true)) && JSON_ERROR_NONE == json_last_error()) {
\Cache::add('scripting.event_schema', $eventTemplate, 86400);
return $eventTemplate;
}
}
\Log::notice('Scripting unavailable. Unable to load scripting event schema: ' . $path);
return false;
}
示例12: searchVideo
/**
* Search for video
*
* @param string $q The search query
*
* @return Response
*/
public function searchVideo($q)
{
// init result array
$result = array();
// create slug from query
$q_slug = str_slug('youtube-' . $q);
// check if search is in cache
if (\Cache::has($q_slug)) {
// retrieve item from cache
$items = \Cache::get($q_slug);
// add data to array
$result = array('fromcache' => true, 'data' => $items);
} else {
// init Google objects
$client = new \Google_Client();
$client->setDeveloperKey(env('YOUTUBE_API_KEY'));
$youtube = new \Google_Service_YouTube($client);
try {
$items = array();
// use youtube search to retrieve video data
$searchResponse = $youtube->search->listSearch('id,snippet', array('q' => $q, 'maxResults' => 3, 'type' => 'video'));
// loop through search results
foreach ($searchResponse['items'] as $video) {
// create object for this video
$item = new YoutubeVideo($video['id']['videoId'], $video['snippet']['title'], $video['snippet']['description'], $video['snippet']['thumbnails']['default']['url']);
// add object to results
$items[] = $item;
}
// add items to cache for a year
\Cache::add($q_slug, $items, 60 * 24 * 365);
// add data to array
$result = array('fromcache' => false, 'data' => $items);
} catch (\Google_Service_Exception $e) {
// log Google_Service_Exception
\Log::error('Google_Service_Exception: ' . $e->getMessage());
} catch (\Google_Exception $e) {
// log Google_Exception
\Log::error('Google_Exception: ' . $e->getMessage());
}
}
// return json formatted response
return response()->json($result);
}
示例13: testFetchArrayOfKeys
/**
* can we add several things to the cache and then return them all at once
*/
public function testFetchArrayOfKeys()
{
// to store all the keys and values we are testing with
$stored_values = array();
// build and store 26 different values with different keys
foreach (range('A', 'Z') as $letter) {
$key = $this->key . '-key-' . $letter;
$value = $this->key . '-value-' . $letter;
// put them in the cache one at a time
$this->assertTrue(Cache::add($key, $value, 10, false));
// so we can get them all at once below
$stored_values[$key] = $value;
}
// get all the keys simultaneously
$results = Cache::get(array_keys($stored_values));
// test all the records were returned as expected
foreach ($stored_values as $key => $value) {
$this->assertEquals($results[$key], $value);
}
}
示例14: lock
/**
param options [
processLink=>boolean, #whether to link lock to the process. Defaults to true
timeLink=timeout in seconds #whether to timeout lock hold, and if so, how many seconds to hold lock for before timeout. Defaults to false
]
*/
function lock($name, $options = [])
{
//Don't use with forking. forking will cause response code 47 (temporarily unavailable) for some time after forks end
$lockPackage = [];
if (!isset($options['processLink']) || $options['processLink']) {
$lockPackage['pid'] = getmypid();
}
if ($options['timeLink']) {
$lockPackage['time'] = time();
$lockPackage['timeout'] = $options['timeLink'];
}
$lockPackage = json_encode($lockPackage);
$initial = Cache::add($name, $lockPackage);
if (!$initial) {
$existingLockPackage = json_decode(Cache::get($name), true);
if (is_array($existingLockPackage)) {
if ($existingLockPackage['pid']) {
$processFile = '/proc/' . $existingLockPackage['pid'];
clearstatcache(false, $processFile);
//process is no longer running, attempt to get lock
if (!file_exists($processFile)) {
Cache::delete($name);
$return = Cache::add($name, $lockPackage);
return $return;
}
}
if ($existingLockPackage['time']) {
//timeout period has passed, unlock and attempt to gt lock
if (time() - $existingLockPackage['time'] > $existingLockPackage['timeout']) {
Cache::delete($name);
return Cache::add($name, $lockPackage);
}
}
}
} else {
return $initial;
}
}
示例15: getUploadToken
/**
* 获取上传token
* @return bool
* @throws \Exception
*/
public static function getUploadToken()
{
if (!config('l5-upload-client.enable')) {
return '';
}
$timestamp = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : 0;
$version = config('l5-upload-client.version', '1.0');
$param = ['app_key' => config('l5-upload-client.app_key'), 'timestamp' => $timestamp, 'sign' => self::calcSign($timestamp), 'version' => $version];
// 计算缓存过期
$cacheKey = self::cacheName(__CLASS__, 'token');
$uploadToken = '';
if (\Cache::has($cacheKey)) {
$cacheToken = \Cache::get($cacheKey);
if (isset($cacheToken['token']) && $cacheToken['expire_timestamp'] > $timestamp) {
// 存在 token 且不过期
$uploadToken = $cacheToken['token'];
} else {
\Cache::forget($cacheKey);
}
}
if (!$uploadToken) {
if (!config('l5-upload-client.token_url')) {
throw new \Exception('Please set lemon picture server token url');
} else {
$curl = new Curl();
$upload = $curl->get(config('l5-upload-client.token_url'), $param);
$upload = json_decode(json_encode($upload), true);
if ($upload['status'] == 'success') {
$uploadToken = $upload['data']['upload_token'];
$expired = (int) config('l5-upload-client.expires');
\Cache::add($cacheKey, ['token' => $uploadToken, 'expire_timestamp' => $timestamp + $expired * 60], config('l5-upload-client.expires'));
} else {
throw new \Exception($upload['msg']);
}
}
}
return $uploadToken;
}