Created
July 1, 2011 13:13
-
-
Save drslump/1058520 to your computer and use it in GitHub Desktop.
Simple example of how could look like injecting resources in objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Injects ZF Bootstrap resources in an object based on annotations | |
function InjectResources($obj) { | |
$obj = $this; | |
$reflObj = new \ReflectionObject($obj); | |
foreach ($reflObj->getProperties() as $prop) { | |
$doc = $prop->getDocComment(); | |
if (preg_match('/@resource(\s+(?<name>[A-Za-z_]+))?/', $doc, $m)) { | |
$name = empty($m['name']) | |
? $prop->getName() | |
: $m['name']; | |
$bs = Zend_Controller_Front::getInstance()->getParam('bootstrap'); | |
if (!$bs->hasPluginResource($name)) { | |
throw new \Exception('Unable to obtain resource "' . $name . '" for class ' . get_class($obj) ); | |
} | |
$resource = $bs->getPluginResource($name); | |
$prop->setAccessible(true); | |
$prop->setValue($obj, $resource); | |
$prop->setAccessible(false); | |
} | |
} | |
} | |
// Example use in a controller | |
class TestController extends Zend_Controller_Action | |
{ | |
/** | |
* Here the resource name is taken from the variable name (log) | |
* @resource | |
* @var \Zend_Log | |
*/ | |
protected $log; | |
/** @resource cache */ | |
protected $mycache; | |
public function init() | |
{ | |
InjectResources($this); | |
} | |
public function indexAction() | |
{ | |
$this->log->info('At index action'); | |
echo $this->mycache->load('index'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment