Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Last active December 27, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamwathan/7312919 to your computer and use it in GitHub Desktop.
Save adamwathan/7312919 to your computer and use it in GitHub Desktop.
Base controller for Laravel 4.0 that lets you use the new instance filter functionality from 4.1
<?php
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* @return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
/**
* Prepare a filter and return the options.
*
* @param string $filter
* @param array $options
* @return array
*/
protected function prepareFilter($filter, $options)
{
// When the given filter is a Closure, we will store it off in an array of the
// callback filters, keyed off the object hash of these Closures and we can
// easily retrieve it if a filter is determined to apply to this request.
if ($filter instanceof Closure)
{
$options['run'] = $hash = spl_object_hash($filter);
$this->callbackFilters[$hash] = $filter;
}
elseif ($this->isInstanceFilter($filter))
{
$options['run'] = $filter;
$this->callbackFilters[$filter] = $this->makeInstanceFilter($filter);
}
else
{
$options['run'] = $filter;
}
return $options;
}
/**
* Check if a filter is a local method
* @param mixed $filter
* @return boolean
*/
protected function isInstanceFilter($filter)
{
return is_string($filter) and starts_with($filter, '@');
}
/**
* Create a callable from a local filter name
* @param string $filter
* @return Closure
*/
protected function makeInstanceFilter($filter)
{
$filter = substr($filter, 1);
$controller = $this;
return array($controller, $filter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment