Skip to content

Commit

Permalink
flush cache!
Browse files Browse the repository at this point in the history
  • Loading branch information
amrbedair committed Sep 14, 2017
1 parent 35fb5de commit 3c0635e
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 91 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ while you are inside the directory yii2
**Note:**
* Yii is an MVC framework so it should be familiar, navigating the code should be easy, as you can see directory names are self explanatory, controllers for application controllers, views for views, and tests for test
* Yii uses Codeception for testing that uses PHPUnit for unit testing
* Application is caching styles, and breweries' beers for 24 hours to enhance performance trying to minimize API hits, so I added a button to flush the cache if required
* The "Back" link will always lead to my test server as it is hard coded

## Laravel + Vue.js
Expand Down
6 changes: 6 additions & 0 deletions yii2/controllers/SiteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Yii;
use yii\web\Controller;
use app\models\forms\SearchForm;
use yii\helpers\Url;

class SiteController extends Controller {

Expand Down Expand Up @@ -54,4 +55,9 @@ public function actionSearch() {
return $this->renderPartial('_search_and_result', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]);
}

public function actionFlushCache() {
\Yii::$app->cache->flush();
\Yii::$app->session->setFlash('success', 'Cache flushed successfully');
return $this->redirect(Url::to('@web'));
}
}
163 changes: 73 additions & 90 deletions yii2/helpers/BreweryDbHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace app\helpers;

use app\models\forms\SearchForm;
use yii\helpers\Url;
use yii\web\HttpException;

$app = \Yii::getAlias("@app");
Expand All @@ -24,40 +23,35 @@ public function __construct() {
$this->init();
}

private function init() {

// try to get styles from the cache
$this->styles = \Yii::$app->cache->get('styles');
if(!$this->styles) {

$result = $this->request('styles');
$this->styles = $result['data'];
/**
* cache it for 24 hours, maybe we need more!
* it depends on how often new style may be added
* default chache in php is FileCache, we may use memcache or
* anything else, but this is enough for simplicity
*/
\Yii::$app->cache->set('styles', $this->styles, 60 * 60 * 24);
}
}

private function request($endpoint, $params=[], $method='GET') {
try {
$result = $this->bdb->request($endpoint, $params, $method);
if($result['status'] == 'failure') {
throw new HttpException(500, $result['errorMessage']);
//Url::toRoute('site/error');
}
return $result;
} catch (Exception $e) {
// log
\Yii::warning('[ERR-01] Error while trying to fetch styles '.$e->getMessage());
}
}


private function init() {

// try to get styles from the cache
$this->styles = \Yii::$app->cache->get('styles');
if(!$this->styles) {
try {
$result = $this->request('styles');
$this->styles = $result['data'];
/**
* cache it for 24 hours, maybe we need more!
* it depends on how often new style may be added
* default chache in php is FileCache, we may use memcache or
* anything else, but this is enough for simplicity
*/
\Yii::$app->cache->set('styles', $this->styles, 60 * 60 * 24);
} catch (Exception $e) {
// log
\Yii::warning('[ERR-01] Error while trying to fetch styles '.$e->getMessage());
}
\Yii::error('[ERR-00] Error while trying to access '.$endpoint.' endpoint '.$e->getMessage());
throw new HttpException(500, $e->getMessage());
}
}

Expand All @@ -76,36 +70,31 @@ public function getRandomBeer() {
* we may use hardcoded style id, if we are sure it will not go away!
*/
if(empty($this->styles)) {
\Yii::warning('[ERR-02] Empty style list!');
\Yii::error('[ERR-02] Empty style list!');
return null;
}

try {
while(true) {
$randomStyle = $this->styles[array_rand($this->styles)];
$result = $this->request('beers', [
'styleId' => $randomStyle['id'],
'order' => 'random',
'randomCount' => 1,
'withBreweries' => 'Y',
]);

if(!isset($result['data'])) {
\Yii::warning('[ERR-03] Error retreiving data '.$result['errorMessage']);
return null;
}

$data = $result['data'];
if( count($data) < 1 || // it may happen!
!isset($data[0]['labels']) ||
!isset($data[0]['description']) ) {
continue;
}
return $data[0];
while(true) {
$randomStyle = $this->styles[array_rand($this->styles)];
$result = $this->request('beers', [
'styleId' => $randomStyle['id'],
'order' => 'random',
'randomCount' => 1,
'withBreweries' => 'Y',
]);

if(!isset($result['data'])) {
\Yii::error('[ERR-03] Error retreiving data '.$result['errorMessage']);
return null;
}
} catch (Exception $e) {
\Yii::warning('[ERR-04] Error connecting to "/beers" end point '.$e->getMessage());
return null;

$data = $result['data'];
if( count($data) < 1 || // it may happen!
!isset($data[0]['labels']) ||
!isset($data[0]['description']) ) {
continue;
}
return $data[0];
}
}

Expand All @@ -115,54 +104,48 @@ public function search($q='', $type=SearchForm::TYPE_BEER, $breweryId=null, $pag

$beers = [];

try {
if($type == SearchForm::TYPE_BEER) { // TYPE_BEER
$result = $this->request('search', [
'p' => $page,
'q' => $q,
'type' => SearchForm::TYPE_BEER,
]);
if(isset($result['data'])) {
$this->mergeValidBeers($beers, $result['data']);
}

} else { // TYPE_BREWERY

if($type == SearchForm::TYPE_BEER) { // TYPE_BEER
$breweryIds = $breweryId ? [$breweryId] : [];

if(!$breweryId) {
// get brewery id first
$result = $this->request('search', [
'p' => $page,
'q' => $q,
'type' => SearchForm::TYPE_BEER,
'type' => SearchForm::TYPE_BREWERY,
]);
if(isset($result['data'])) {
$this->mergeValidBeers($beers, $result['data']);
}

} else { // TYPE_BREWERY

$breweryIds = $breweryId ? [$breweryId] : [];

if(!$breweryId) {
// get brewery id first
$result = $this->request('search', [
'q' => $q,
'type' => SearchForm::TYPE_BREWERY,
]);

// check valid result
if(isset($result['data']) && is_array($result['data'])) {
$breweries = $result['data'];
foreach ($breweries as $brewery) { $breweryIds[] = $brewery['id']; }
}
// check valid result
if(isset($result['data']) && is_array($result['data'])) {
$breweries = $result['data'];
foreach ($breweries as $brewery) { $breweryIds[] = $brewery['id']; }
}

if(!empty($breweryIds)) {
foreach ($breweryIds as $breweryId) {
// check if already cached
$result = \Yii::$app->cache->get("BREWERY_".$breweryId."_RESULT");
if(!$result) {
$result = $this->request("/brewery/$breweryId/beers");
\Yii::$app->cache->set("BREWERY_".$breweryId."_RESULT", $result, 60 * 60 * 24);
}
if(!isset($result['data'])) continue;
$this->mergeValidBeers($beers, $result['data']);
}

if(!empty($breweryIds)) {
foreach ($breweryIds as $breweryId) {
// check if already cached
$result = \Yii::$app->cache->get("BREWERY_".$breweryId."_RESULT");
if(!$result) {
$result = $this->request("/brewery/$breweryId/beers");
\Yii::$app->cache->set("BREWERY_".$breweryId."_RESULT", $result, 60 * 60 * 24);
}
if(!isset($result['data'])) continue;
$this->mergeValidBeers($beers, $result['data']);
}
}

} catch (Exception $e) {
\Yii::warning('[ERR-05] Error connecting to "/search" end point '.$e->getMessage());
}

return $beers;
}

Expand Down
13 changes: 12 additions & 1 deletion yii2/views/layouts/main.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,23 @@
<div class="navbar-header app-header">
<a href="<?= Url::to('@web')?>" style="text-decoration: none;"><?= Yii::$app->name ?></a>
</div>
<a type="button" class="btn btn-sm btn-default navbar-btn pull-right" href="<?= Url::toRoute('site/flush-cache') ?>">Flush Cache</a>
<?php NavBar::end(); ?>

<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?php
foreach (['success', 'info', 'warning', 'danger'] as $key) {
if(!empty($msg = \Yii::$app->session->getFlash($key))) {
echo "
<div class='alert alert-$key alert-dismissible' role='alert'style='margin: 5px;'>
<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
$msg
</div>";
}
}
?>
<?= $content ?>
</div>
</div>
Expand Down

0 comments on commit 3c0635e

Please sign in to comment.