Skip to content

Instantly share code, notes, and snippets.

@eseyden
Last active August 29, 2015 14:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eseyden/60dcf9185908b50e5014 to your computer and use it in GitHub Desktop.
Save eseyden/60dcf9185908b50e5014 to your computer and use it in GitHub Desktop.
Fetch Remote View Laravel
<?php namespace Acme\View;
use Illuminate\View\FileViewFinder;
use Cache;
use Carbon\Carbon;
use File;
class RemoteViewFinder extends FileViewFinder {
public function find($name)
{
if(strpos($name,'https://') !== false OR strpos($name,'http://')){
$this->cacheRemoteView($name);
return $this->views[$name] = $this->getRemoteViewLocalPath($name);
}
$path = parent::find($name);
return $path;
}
private function getRemoteViewLocalPath($name)
{
$filename = $this->getRemoteViewFileName($name);
return storage_path('remote_view').'/'.$filename;
}
private function cacheRemoteView($name)
{
if(!Cache::has($name)){
$expiresAt = Carbon::now()->addDays(7);
Cache::put($name,@file_get_contents($name),$expiresAt);
$this->storeRemoteViewLocally($name);
}
}
private function storeRemoteViewLocally($name)
{
$cachedRemoteView = Cache::get($name);
$localFilePath = $this->getRemoteViewLocalPath($name);
if(!File::isFile($localFilePath)){
$this->ensureRemoteViewStorageDirectoryExists();
File::put($localFilePath,$cachedRemoteView);
}
}
protected function ensureRemoteViewStorageDirectoryExists()
{
$storageLocation = storage_path('remote_view');
if(!File::isDirectory($storageLocation)){
File::makeDirectory($storageLocation);
}
}
private function getRemoteViewFileName($name)
{
return md5($name).'.blade.php';
}
}
<?php namespace Acme\View;
class ViewServiceProvider extends \Illuminate\View\ViewServiceProvider {
public function registerViewFinder()
{
$this->app->bindShared('view.finder', function($app)
{
$paths = $app['config']['view.paths'];
return new RemoteViewFinder($app['files'], $paths);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment