Skip to content

Instantly share code, notes, and snippets.

@drock
Created July 24, 2013 17:18
Show Gist options
  • Save drock/6072560 to your computer and use it in GitHub Desktop.
Save drock/6072560 to your computer and use it in GitHub Desktop.
Trait for php classes to provide some boilerplate option/config functionality for the class
<?php
/**
* Trait OptionTrait
*
* A trait that will apply option configuration functionality to a class.
* Typical use would be to define a constructor which takes in an array
* of options and sets them with defaults like so:
*
* public function __construct(array $options = [])
* {
* $this->setOptions($options, [
* 'some options' => 'some option default'
* ]);
* }
*
* Then in the class when you need to refer to an option:
*
* $option = $this->option('some option');
*
*/
trait OptionTrait
{
/**
* @var array
**/
private $options = [];
/**
* @param array $options
*/
public function setOptions(array $options, array $defaults = [])
{
$this->options = array_merge($defaults, $options);
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Get an option set on this object
*
* @param $key
* @param null $default
* @return mixed
*/
public function option($key, $default = null)
{
return isset($this->options[$key]) ? $this->options[$key] : $default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment