diff --git a/composer.json b/composer.json index bacc4c8..253bc82 100644 --- a/composer.json +++ b/composer.json @@ -3,6 +3,7 @@ "require": { "slim/slim": "2.*", "slim/extras": "*", - "twig/twig": "*" + "twig/twig": "*", + "predis/predis": "0.8.*@dev" } } \ No newline at end of file diff --git a/public/index.php b/public/index.php index 917dd12..67f2646 100644 --- a/public/index.php +++ b/public/index.php @@ -2,6 +2,8 @@ require '../vendor/autoload.php'; require '../vots.php'; +$redis = new Predis\Client(); + //////////////////////// // Setup //////////////////////// @@ -14,6 +16,10 @@ //Twig hates the config array above $app->view(new \Slim\Extras\Views\Twig()); +//Do Dependancy Injection +$env = $app->environment(); +$env['redis'] = $redis; + //////////////////////// // Routes //////////////////////// @@ -45,9 +51,17 @@ //Status $app->get('/status/:last/:vin/', function ($last, $vin) use ($app) { - $jeep = new VOTSService($last, $vin); - if ($jeep->isValid()) + //Get environment and DI + $env = $app->environment(); + $redis = $env['redis']; + + //Check redis cache for record + if ($cached = $redis->get($vin)) { + //decode redis/JSON and pass it to VOTS class + $jeep = new VOTSService(json_decode($cached, TRUE)); + + $data = array( 'statusCode' => $jeep->getStatusCode(), 'statusDesc' => $jeep->getStatusDesc(), @@ -57,12 +71,35 @@ //Do something $app->render('response.twig', $data); } - else + + //redis has no key, lets go fetch Chrysler's response + else { - $data = array( - 'error' => $jeep->getError() - ); - $app->render('error.twig', $data); + $jeep = new VOTSService(); + $jeep->getJSON($last, $vin); + if ($jeep->isValid()) + { + $data = array( + 'statusCode' => $jeep->getStatusCode(), + 'statusDesc' => $jeep->getStatusDesc(), + 'statusExplanation' => $jeep->getStatusExplanation() + ); + + //put json into redis on key=vin for caching + $redis->set($vin, json_encode($jeep::$decoded)); + $redis->expire($vin,60*20); //cache for 20 minutes + + //Do something + $app->render('response.twig', $data); + } + else + { + //set an error message to display, courtesy of Chrysler + $data = array( + 'error' => $jeep->getError() + ); + $app->render('error.twig', $data); + } } }); diff --git a/vots.php b/vots.php index 675e157..cba5680 100644 --- a/vots.php +++ b/vots.php @@ -53,17 +53,19 @@ class VOTSService { ); - public function __construct($lastname, $vin) + public function __construct($json = NULL) { - $this->lastname = $lastname; - $this->vin = $vin; - self::$decoded = NULL; - $this->getJSON(); + self::$decoded = $json; + } - public function getJSON() + public function getJSON($lastname, $vin) { + //set our variables + $this->lastname = $lastname; + $this->vin = $vin; + //replace a space with +, as Chrysler expects $lastname = preg_replace("/ /","+",$this->lastname); $vin = $this->vin;