Skip to content

Instantly share code, notes, and snippets.

@enminc
Last active August 29, 2015 14:00
Show Gist options
  • Save enminc/2a5a667e0543b2065d68 to your computer and use it in GitHub Desktop.
Save enminc/2a5a667e0543b2065d68 to your computer and use it in GitHub Desktop.
modx.getSnippet
<?php
/**
* Similar in practice to localizing getChunk and _getChunkTpl
* in your class to pull chunks from disk but for snippet code
*/
class putMethodsInYourClass {
/**
* Process and return the output from a PHP snippet by name.
*
* @param string $name The name of the snippet.
* @param array $params An associative array of properties to pass to the
* snippet.
* @return string The processed output of the snippet.
*/
public function getSnippet($name, array $params= array ()) {
$output= '';
if ( !$this->modx->getOption( 'debug', $this->_config, false ) ) {
$snippet = $this->modx->getObject( 'modSnippet', array( 'name' => $name ) );
}
if ( empty( $snippet ) ) {
$snippet = $this->_getSnippetSource( $name );
if ( $snippet == $name ) return $name;
}
if ($this->modx->getParser()) {
if ($snippet instanceof modSnippet) {
$snippet->setCacheable(false);
$output= $snippet->process($params);
}
}
return $output;
}
/**
* Returns a modSnippet object from a template file.
*
* @access private
* @param string $name The name of the Snippet. Will parse to name.snippet.php
* @param string $suffix The suffix to postfix the chunk with
* @return modChunk/boolean Returns the modChunk object if found, otherwise
* false.
*/
private function _getSnippetSource( $name, $suffix = '.snippet.php' ) {
$snippet = $name;
$suffix = $this->modx->getOption( 'suffix', $this->_config, $suffix );
$f = $this->_config['snPath'] . strtolower( $name ) . $suffix;
if ( file_exists( $f ) ) {
$o = file_get_contents( $f );
//@var modSnippet $snippet
$snippet = $this->modx->newObject( 'modSnippet' );
$snippet->set( 'name', $name );
$snippet->setContent( $o );
}
return $snippet;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment