Skip to content

Instantly share code, notes, and snippets.

@shakyShane
Created July 22, 2012 09:36
Show Gist options
  • Save shakyShane/3159072 to your computer and use it in GitHub Desktop.
Save shakyShane/3159072 to your computer and use it in GitHub Desktop.
boilerplate for a Laravel Base Controller
<?php
class Base_Controller extends Controller {
public $layout = 'layouts.main';
public function __construct(){
//Styles
Asset::add('css', 'css/main.css');
//Scripts
Asset::add('jQuery', 'js/jquery.min.js');
Asset::add('custom', 'js/custom.js');
parent::__construct();
}
/**
* Catch-all method for requests that can't be matched.
*
* @param string $method
* @param array $parameters
* @return Response
*/
public function __call($method, $parameters)
{
return Response::error('404');
}
/**
*
* 1. Check if it's an ajax request
* 2. Set up Page Data (title, activenav etc)
* 3. add any addtional data to be passed to the View.
* @param $route
* @return mixed
*
*
*/
public function servePage($route, $extraViewData = null)
{
if (\Laravel\Request::ajax())
$this->layout = 'layouts.ajax';
else
$this->layout = 'layouts.main';
/**
* Helper to set the Page title and ACTIVE nav element
*/
$viewData = $this->setPageData($route);
/**
*
* Handle any extra data that needs to be passed to the view.
* If it's an Array, just merge it.
* If it's an object, make it accessible via it's class name.
*/
if (null !== $extraViewData){
if (is_array($extraViewData)){
$viewData = array_merge($extraViewData, $viewData);
}
if (is_object($extraViewData)){
$className = strtolower(get_class($extraViewData));
$viewData[$className] = $extraViewData;
}
}
return View::make($this->layout, $viewData)->nest('content', 'home.' . $route, $viewData);
}
/**
*
* Helper to reduce code duplication.
* @param $route
* @return array - The View data
*
*/
public function setPageData($route){
/**
* Sort out the Title and Other attributes specific to each page.
*/
$title = Helpers::setTitle(ucwords($route));
$viewData = array();
$viewData['title'] = $title;
$viewData['activeNav'] = $route;
/**
*
* If it's an ajax request, set a flag so that we don't send the layout along with the page.
*/
$viewData['isAjax'] = (\Laravel\Request::ajax()) ? true : false;
return $viewData;
}
@mikeritter
Copy link

Holy Shnikies! Thanks yo!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment