Skip to content

Commit

Permalink
Implementing helper lazy loading
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 28, 2012
1 parent c270e7f commit f688d57
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
51 changes: 51 additions & 0 deletions lib/Cake/View/HelperCollection.php
Expand Up @@ -43,6 +43,57 @@ public function __construct(View $view) {
$this->_View = $view;
}

/**
* Tries to lazy load a helper based on its name, if it cannot be found
* in the application folder, then it tries looking under the current plugin
* if any
*
* @param string $helper The helper name to be loaded
* @return boolean wheter the helper could be loaded or not
**/
public function __isset($helper) {
if (parent::__isset($helper)) {
return true;
}
if (!$this->_loadSandbox($helper)) {
return $this->_View->plugin && $this->_loadSandbox($this->_View->plugin . '.' . $helper);
}
return true;
}

/**
* Provide public read access to the loaded objects
*
* @param string $name Name of property to read
* @return mixed
*/
public function __get($name) {
if ($result = parent::__get($name)) {
return $result;
}
if ($this->__isset($name)) {
return $this->_loaded[$name];
}
return null;
}

/**
* Auxiliary function used for lazy loading helpers
* catches any MissingHelperException and converts it into
* a boolean return
*
* @param string $helper The helper name to be loaded
* @return boolean wheter the helper could be loaded or not
**/
protected function _loadSandbox($helper) {
try {
$this->load($helper);
} catch (MissingHelperException $e) {
return false;
}
return true;
}

/**
* Loads/constructs a helper. Will return the instance in the registry if it already exists.
* By setting `$enable` to false you can disable callbacks for a helper. Alternatively you
Expand Down
10 changes: 5 additions & 5 deletions lib/Cake/View/View.php
Expand Up @@ -785,9 +785,6 @@ public function set($one, $two = null) {
* @return mixed
*/
public function __get($name) {
if (isset($this->Helpers->{$name})) {
return $this->Helpers->{$name};
}
switch ($name) {
case 'base':
case 'here':
Expand All @@ -800,9 +797,12 @@ public function __get($name) {
return $this->request;
case 'output':
return $this->Blocks->get('content');
default:
return $this->{$name};
}
if (isset($this->Helpers->{$name})) {
$this->{$name} = $this->Helpers->{$name};
return $this->Helpers->{$name};
}
return $this->{$name};
}

/**
Expand Down

0 comments on commit f688d57

Please sign in to comment.